repo_name
stringlengths 5
114
| repo_url
stringlengths 24
133
| snapshot_id
stringlengths 40
40
| revision_id
stringlengths 40
40
| directory_id
stringlengths 40
40
| branch_name
stringclasses 209
values | visit_date
timestamp[ns] | revision_date
timestamp[ns] | committer_date
timestamp[ns] | github_id
int64 9.83k
683M
⌀ | star_events_count
int64 0
22.6k
| fork_events_count
int64 0
4.15k
| gha_license_id
stringclasses 17
values | gha_created_at
timestamp[ns] | gha_updated_at
timestamp[ns] | gha_pushed_at
timestamp[ns] | gha_language
stringclasses 115
values | files
listlengths 1
13.2k
| num_files
int64 1
13.2k
|
---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
ntnguyen1234/deepmask-pytorch | https://github.com/ntnguyen1234/deepmask-pytorch | d78cb64434057b1f100dc0bd40f6133e398b9192 | 02efa7ad14a26f6fac065373f5f9caa0bd030e2f | 7129453acd808a0cda3119601cc8cbf6c6f2089d | refs/heads/master | 2020-05-26T11:50:22.133981 | 2019-05-23T15:14:10 | 2019-05-23T15:14:10 | 188,222,987 | 0 | 0 | MIT | 2019-05-23T11:43:53 | 2019-05-22T20:32:50 | 2019-02-21T13:14:51 | null | [
{
"alpha_fraction": 0.5246149301528931,
"alphanum_fraction": 0.5317124724388123,
"avg_line_length": 33.1340217590332,
"blob_id": "60a3b6f71a98ac1261ab7b3023670ad4d8f32903",
"content_id": "be80f98213113010c91593c5ebf7f22c0c3fc24a",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6622,
"license_type": "permissive",
"max_line_length": 119,
"num_lines": 194,
"path": "/preprocess.py",
"repo_name": "ntnguyen1234/deepmask-pytorch",
"src_encoding": "UTF-8",
"text": "import csv\nimport json\nimport sys\nimport pandas as pd\nfrom pycocotools import mask\nimport pycococreatortools as pycoco\nimport numpy as np\n\n#from PIL import Image\nfrom sklearn.model_selection import train_test_split\nfrom collections import OrderedDict\n\ndef rle_decode(mask_rle, shape):\n '''\n mask_rle: run-length as string formated (start length)\n shape: (height,width) of array to return \n Returns numpy array, 1 - mask, 0 - background\n\n '''\n s = mask_rle.split()\n starts, lengths = [np.asarray(x, dtype=int) for x in (s[0:][::2], s[1:][::2])]\n starts -= 1\n ends = starts + lengths\n rle = {\n 'counts': [],\n 'size': [shape[0], shape[1]]\n }\n img = np.zeros(shape[0]*shape[1], dtype=np.uint8)\n for i, (lo, hi) in enumerate(zip(starts, ends)):\n img[lo:hi] = 1\n rle['counts'].append(starts[i] - ends[i-1])\n rle['counts'].append(ends[i] - starts[i])\n \n rle['counts'][0] = starts[0]\n rle['counts'].append(shape[0]*shape[1] - ends[-1])\n img_rs = img.reshape(shape, order='F')\n return (rle, img_rs)\n\ndef create_coco_style(self, input_path, des):\n maxInt = sys.maxsize\n\n while True:\n try:\n csv.field_size_limit(maxInt)\n break\n except:\n maxInt = int(maxInt/10)\n \n data_path = input_path + 'train.csv'\n # json_des = '/kaggle/working/label_descriptions.json'\n\n # with open(json_des, 'r') as f:\n # des = json.load(f)\n \n info = des['info']\n categories = des['categories']\n attributes = des['attributes']\n\n #f = open(data_path, 'r')\n #\n X = pd.read_csv(data_path)\n\n X_train, X_test = train_test_split(X,test_size=0.2)\n # X_train = X\n\n X_dtrain = X_train.to_dict('records', into=OrderedDict)\n X_dtest = X_test.to_dict('records', into=OrderedDict)\n\n #reader = csv.DictReader(f)#, fieldnames=('imageid', 'height', 'width', 'encodedpixels', 'classid'))\n\n rows_train = []\n rows_test = []\n\n myorder = ['ImageId', 'Height', 'Width', 'EncodedPixels', 'ClassId']\n\n image_id = 1\n segmentation_id = 1\n\n coco_output = {\n \"info\": info,\n \"licenses\": \"\",\n \"categories\": categories,\n \"images\": [],\n \"annotations\": []\n }\n\n coco_output_test = coco_output\n\n with open('{}train.txt'.format(input_path), 'w') as output_text_file:\n for row in X_dtrain:\n # Write training text\n output_text_file.write('{} '.format(row['ImageId']))\n\n # Ordered Dict\n ordered = OrderedDict((k, row[k]) for k in myorder)\n # ordered['EncodedPixels'] = list(map(int, ordered['EncodedPixels'].split(' ')))\n if len(ordered['ClassId']) > 2:\n classes = [list(map(int, ordered['ClassId'].split('_')))]\n ordered['ClassId'] = classes[0][0]\n else:\n ordered['ClassId'] = int(ordered['ClassId'])\n \n # COCO\n image_info = pycoco.create_image_info(image_id, input_path + row['ImageId'], (row['Width'], row['Height']))\n coco_output[\"images\"].append(image_info)\n \n rle, binary_mask = rle_decode(row['EncodedPixels'], (row['Height'], row['Width']))\n fortran_binary_mask = np.asfortranarray(binary_mask.astype(np.uint8))\n\n binary_mask_encoded = mask.encode(fortran_binary_mask)\n # rle2 = pycoco.binary_mask_to_rle(fortran_binary_mask)\n \n area = mask.area(binary_mask_encoded)\n bounding_box = mask.toBbox(binary_mask_encoded)\n \n annotation_info = {\n \"id\": segmentation_id,\n \"image_id\": image_id,\n \"category_id\": ordered['ClassId'],\n \"iscrowd\": 1,\n \"area\": area.tolist(),\n \"bbox\": bounding_box.tolist(),\n \"segmentation\": rle,\n \"width\": row['Width'],\n \"height\": row['Height'],\n }\n coco_output[\"annotations\"].append(annotation_info) \n segmentation_id += 1\n image_id += 1\n \n rows_train.append(ordered)\n\n with open('{}train.json'.format(input_path), 'w') as output_json_file:\n json.dump(coco_output, output_json_file)\n\n with open('{}test.txt'.format(input_path), 'w') as output_text_file:\n for row in X_dtest:\n # Write test text\n output_text_file.write('{} '.format(row['ImageId']))\n \n # Ordered Dict\n ordered = OrderedDict((k, row[k]) for k in myorder)\n # ordered['EncodedPixels'] = list(map(int, ordered['EncodedPixels'].split(' ')))\n if len(ordered['ClassId']) > 2:\n classes = [list(map(int, ordered['ClassId'].split('_')))]\n ordered['ClassId'] = classes[0][0]\n else:\n ordered['ClassId'] = int(ordered['ClassId'])\n \n # COCO\n image_info = pycoco.create_image_info(image_id, input_path + row['ImageId'], (row['Width'], row['Height']))\n coco_output_test[\"images\"].append(image_info)\n \n rle, binary_mask = rle_decode(row['EncodedPixels'], (row['Height'], row['Width']))\n fortran_binary_mask = np.asfortranarray(binary_mask.astype(np.uint8))\n\n binary_mask_encoded = mask.encode(fortran_binary_mask)\n # rle2 = pycoco.binary_mask_to_rle(fortran_binary_mask)\n \n area = mask.area(binary_mask_encoded)\n bounding_box = mask.toBbox(binary_mask_encoded)\n \n annotation_info = {\n \"id\": segmentation_id,\n \"image_id\": image_id,\n \"category_id\": ordered['ClassId'],\n \"iscrowd\": 1,\n \"area\": area.tolist(),\n \"bbox\": bounding_box.tolist(),\n \"segmentation\": rle,\n \"width\": row['Width'],\n \"height\": row['Height'],\n }\n coco_output_test[\"annotations\"].append(annotation_info) \n segmentation_id += 1\n image_id += 1\n \n rows_train.append(ordered)\n\n with open('{}test.json'.format(input_path), 'w') as output_json_file:\n json.dump(coco_output_test, output_json_file)\n\n\n#out_train = json.dumps(rows_train)\n#out_test = json.dumps(rows_test)\n##\n#print('JSON parsed!')\n#\n#f2 = open('train2.json','w')\n#f2.write(out_train)\n#\n#f2 = open('test2.json','w')\n#f2.write(out_test)\n#print('JSON saved')\n"
}
] | 1 |
oneoffcoder/pyip | https://github.com/oneoffcoder/pyip | 1bbd674b6320ffdac24858203036ae9cd19b99e7 | b4de98a4077096ae2b0a37d01a248317a08c9278 | b7cde2a78a999fcce1099ba229f06e4de666f6a5 | refs/heads/master | 2020-07-03T09:01:51.163280 | 2019-10-14T01:33:00 | 2019-10-14T01:33:00 | 201,859,769 | 9 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6988148093223572,
"alphanum_fraction": 0.708575427532196,
"avg_line_length": 35.47457504272461,
"blob_id": "9d7cb14a4e92a1ba5c0cee4f481541c3e23215af",
"content_id": "1ce22877460b03ef5e6a02d05c77bf7d8d8e8d95",
"detected_licenses": [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 4303,
"license_type": "permissive",
"max_line_length": 283,
"num_lines": 118,
"path": "/README.md",
"repo_name": "oneoffcoder/pyip",
"src_encoding": "UTF-8",
"text": "\n\n# Intro\n\nA simple Python program that may be used as a service for Linux and Windows to get your external (public) IP and send it to yourself. Use at your own risk as password parameter for the email account being used has to be passed in unencrypted. The following is a printout of the help.\n\n```\nusage: IP Locator [-h] [-u URL] [-m MAX_EMAILS] [-s SLEEP] -e EMAIL -p\n PASSWORD [--subject SUBJECT] [--version]\n\noptional arguments:\n -h, --help show this help message and exit\n -u URL, --url URL the URL of the site to get your external IP (default: https://myexternalip.com/raw)\n Other sites that may work.\n - https://www.ipchicken.com\n - https://myexternalip.com/raw\n \n -m MAX_EMAILS, --max_emails MAX_EMAILS\n maximum emails; set to -1 for indefinite (default: -1)\n -s SLEEP, --sleep SLEEP\n seconds between checking/sending IP in email (default: 3600)\n -e EMAIL, --email EMAIL\n gmail email address\n -p PASSWORD, --password PASSWORD\n gmail email password\n --subject SUBJECT email subject line modifier (default: IP Address)\n --version show program's version number and exit\n\nOne-Off Coder, http://www.oneoffcoder.com\n```\n\nNote that only the email `-e` and password `-p` are required, and that this program has only been tested against a `gmail` account. A quick and dirty example of using this program is as follows (of course, substitute the email and password values with your own).\n\n```bash\npython ip.py -e [email protected] -p codebreaker\n```\n\n# Installation\n\n## CentOS Linux\n\n```bash\n# copy python file\nsudo cp ip.py /usr/bin\nsudo chmod 600 /usr/bin/ip.py\n\n# copy service file\n# make sure you modify ExecStart with the appropriate email and password\n# make sure the path to python is absolute e.g. /home/super/anaconda3/bin/python\nsudo cp pyip.service /lib/systemd/system\nsudo nano /lib/systemd/system/pyip.service\nsudo chmod 600 /lib/systemd/system/pyip.service \n\n# to enable, start, stop, etc.. the service\nsudo systemctl daemon-reload\nsudo systemctl enable pyip.service\nsudo systemctl start pyip.service\nsudo systemctl status pyip.service\nsudo systemctl stop pyip.service\nsudo systemctl restart pyip.service\n```\n\n## Windows\n\nOn Windows, use the [sc command](https://docs.microsoft.com/en-us/windows/win32/services/controlling-a-service-using-sc).\n\n```bash\nsc create PyIP binPath=\"C:\\ProgramData\\Anaconda3\\python.exe C:\\dev\\ip.py -e [email protected] -p codebreaker\"\nsc start PyIP\nsc delete PyIP\n```\n\n# References\n\n* https://tecadmin.net/setup-autorun-python-script-using-systemd/\n* https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/sc-create\n* https://docs.microsoft.com/en-us/windows-server/administration/windows-commands/sc-delete\n* https://datatofish.com/python-script-windows-scheduler/\n* https://www.digitalocean.com/community/tutorials/how-to-use-systemctl-to-manage-systemd-services-and-units\n* https://askubuntu.com/questions/814174/cannot-make-a-systemd-script-run\n\n# Citation\n\n```\n@misc{oneoffcoder_ip_locator_2019, \ntitle={External IP locator using Python for Linux and Windows}, \nurl={https://github.com/oneoffcoder/pyip}, \njournal={GitHub},\nauthor={One-Off Coder}, \nyear={2019}, \nmonth={Aug}}\n```\n\n# Copyright Stuff\n\n```\nCopyright 2019 One-Off Coder\n\nLicensed under the Apache License, Version 2.0 (the \"License\");\nyou may not use this file except in compliance with the License.\nYou may obtain a copy of the License at\n\n http://www.apache.org/licenses/LICENSE-2.0\n\nUnless required by applicable law or agreed to in writing, software\ndistributed under the License is distributed on an \"AS IS\" BASIS,\nWITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\nSee the License for the specific language governing permissions and\nlimitations under the License.\n```\n\n# Contact\n\n[One-Off Coder](https://cloud.docker.com/u/oneoffcoder/) \n* [Website](https://www.oneoffcoder.com)\n* [Twitter](https://twitter.com/oneoffcoder)\n* [Facebook](https://www.facebook.com/oneoffcoder)\n* [YouTube](https://www.youtube.com/channel/UCCCv8Glpb2dq2mhUj5mcHCQ)"
},
{
"alpha_fraction": 0.6128926873207092,
"alphanum_fraction": 0.6223822236061096,
"avg_line_length": 30.53191566467285,
"blob_id": "b5bdfcdaf62429a8ac18ce218a40a724da94321a",
"content_id": "e9917512c5b3f3508f980f8ef8f926c2bd356c0d",
"detected_licenses": [
"LicenseRef-scancode-warranty-disclaimer",
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3056,
"license_type": "permissive",
"max_line_length": 186,
"num_lines": 94,
"path": "/ip.py",
"repo_name": "oneoffcoder/pyip",
"src_encoding": "UTF-8",
"text": "import requests\r\nimport re\r\nimport smtplib, ssl\r\nimport time\r\nimport argparse\r\nimport sys\r\nfrom argparse import RawTextHelpFormatter\r\n\r\ndef parse_args(args):\r\n \"\"\"\r\n Parses arguments.\r\n :param args: Arguments.\r\n :return: Arguments.\r\n \"\"\"\r\n parser = argparse.ArgumentParser('IP Locator', epilog='One-Off Coder, http://www.oneoffcoder.com', formatter_class=RawTextHelpFormatter)\r\n \r\n parser.add_argument('-u', '--url', default='https://myexternalip.com/raw', required=False, help=\"\"\"the URL of the site to get your external IP (default: https://myexternalip.com/raw)\r\n Other sites that may work.\r\n - https://www.ipchicken.com\r\n - https://myexternalip.com/raw\r\n \"\"\")\r\n parser.add_argument('-m', '--max_emails', default=-1, type=int, required=False, help='maximum emails; set to -1 for indefinite (default: -1)')\r\n parser.add_argument('-s', '--sleep', default=3600, type=int, required=False, help='seconds between checking/sending IP in email (default: 3600)')\r\n parser.add_argument('-e', '--email', required=True, help='gmail email address')\r\n parser.add_argument('-p', '--password', required=True, help='gmail email password')\r\n parser.add_argument('--subject', default='IP Address', required=False, help='email subject line modifier (default: IP Address)')\r\n parser.add_argument('--version', action='version', version='%(prog)s v0.0.1')\r\n\r\n return parser.parse_args(args)\r\n\r\ndef get_html(url):\r\n \"\"\"\r\n Gets the HTML content from the specified URL.\r\n :param url: URL.\r\n :return: HTML content.\r\n \"\"\"\r\n resp = requests.get(url)\r\n content = resp.text\r\n return content\r\n\r\ndef get_ip(content):\r\n \"\"\"\r\n Gets the IP address(es) from the content.\r\n :param content: HTML content.\r\n :return: A pipe-delimited string of all IP addresses found.\r\n \"\"\"\r\n pattern = r'\\b\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\b'\r\n res = re.findall(pattern, content)\r\n return ' | '.join(res)\r\n\r\n\r\ndef send_email(ip, subject, email, pw):\r\n \"\"\"\r\n Sends email.\r\n :param ip: IP address.\r\n :param subject: Email subject line.\r\n :param email: Email.\r\n :param pw: Password.\r\n \"\"\"\r\n context = ssl.create_default_context()\r\n try:\r\n server = smtplib.SMTP('smtp.gmail.com', 587)\r\n server.ehlo()\r\n server.starttls(context=context)\r\n server.ehlo()\r\n server.login(email, pw)\r\n message = 'Subject: {}\\n\\n{}'.format(subject, ip)\r\n server.sendmail(email, email, message)\r\n except Exception as e:\r\n print(e)\r\n finally:\r\n server.quit()\r\n\r\nargs = parse_args(sys.argv[1:])\r\n\r\nurl = args.url\r\nsubject = args.subject\r\nemail = args.email\r\npw = args.password\r\nmax_emails = args.max_emails\r\nsleep = args.sleep\r\n\r\ncounter = 1\r\nwhile True:\r\n content = get_html(url)\r\n ip = get_ip(content)\r\n send_email(ip, subject, email, pw)\r\n print('{}: {} : done'.format(counter, ip))\r\n counter = counter + 1\r\n\r\n if max_emails > 0 and counter >= max_emails:\r\n break\r\n else:\r\n time.sleep(sleep)"
}
] | 2 |
smartgang/RsiWin | https://github.com/smartgang/RsiWin | a4eebc6d187ab0f13d323211302db8b29af0687d | 43ce67733b7b55438aff3a676acab5550cf4e03d | d4f3cb4d01592ef5f8c3eec06564f7c73211ea2d | refs/heads/master | 2020-03-26T21:36:15.019836 | 2018-09-04T09:15:11 | 2018-09-04T09:15:11 | 145,397,645 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.529109001159668,
"alphanum_fraction": 0.534439742565155,
"avg_line_length": 47.38754653930664,
"blob_id": "5d6f2811ff8e49eca890554ab1c465096379ba37",
"content_id": "cefea037365ad6c1f682feea68f73afae120eba9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 38729,
"license_type": "no_license",
"max_line_length": 163,
"num_lines": 787,
"path": "/HullRsiWin/HullRsiWin_Close.py",
"repo_name": "smartgang/RsiWin",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\nimport DynamicStopLoss as dsl\nimport OnceWinNoLoss as ownl\nimport FixRateStopLoss as frsl\nimport DslOwnlClose as dslownl\nimport MultiStopLoss as msl\nimport StopLossLib.AtrStopLoss as atrsl\nimport StopLossLib.GOWNL as gownl\nimport StopLossLib.AllClose as all_close\nimport DATA_CONSTANTS as DC\nimport pandas as pd\nimport os\nimport numpy as np\nimport multiprocessing\nimport datetime\nimport HullRsiWin_Parameter as Parameter\nimport time\n\n\ndef getDSL(strategyName, symbolInfo, bar_type, dsl_para_dic_list, parasetlist, bar1mdic, barxmdic, result_para_dic,\n indexcols, progress=False):\n symbol = symbolInfo.domain_symbol\n new_indexcols = []\n for i in indexcols:\n new_indexcols.append('new_' + i)\n allresultdf_cols = ['setname', 'slTarget', 'worknum'] + indexcols + new_indexcols\n allresultdf = pd.DataFrame(columns=allresultdf_cols)\n\n allnum = 0\n paranum = parasetlist.shape[0]\n for stoplossTarget_dic in dsl_para_dic_list:\n timestart = time.time()\n dslFolderName = (\"DynamicStopLoss%s\" % (stoplossTarget_dic['para_name']))\n try:\n os.mkdir(dslFolderName) # 创建文件夹\n except:\n # print 'folder already exist'\n pass\n print (\"stoplossTarget:%s\" % stoplossTarget_dic['para_name'])\n\n resultdf = pd.DataFrame(columns=allresultdf_cols)\n setnum = 0\n numlist = range(0, paranum, 100)\n numlist.append(paranum)\n for n in range(1, len(numlist)):\n pool = multiprocessing.Pool(multiprocessing.cpu_count() - 1)\n l = []\n for a in range(numlist[n - 1], numlist[n]):\n setname = parasetlist.ix[a, 'Setname']\n if not progress:\n # l.append(dsl.dslCal(strategyName, symbolInfo, bar_type, setname, bar1mdic, barxmdic, result_para_dic, stoplossTarget_dic,\n # dslFolderName + '\\\\', indexcols))\n l.append(pool.apply_async(dsl.dslCal, (\n strategyName, symbolInfo, bar_type, setname, bar1mdic, barxmdic, result_para_dic,\n stoplossTarget_dic,\n dslFolderName + '\\\\', indexcols)))\n else:\n # l.append(dsl.progressDslCal(strategyName,symbolInfo, K_MIN, setname, bar1m, barxm, pricetick,\n # positionRatio, initialCash, stoplossTarget,\n # dslFolderName + '\\\\'))\n l.append(pool.apply_async(dsl.progressDslCal, (strategyName,\n symbolInfo, bar_type, setname, bar1mdic, barxmdic,\n result_para_dic, stoplossTarget_dic,\n dslFolderName + '\\\\', indexcols)))\n pool.close()\n pool.join()\n\n for res in l:\n resultdf.loc[setnum] = res.get()\n allresultdf.loc[allnum] = resultdf.loc[setnum]\n setnum += 1\n allnum += 1\n resultdf.to_csv(dslFolderName + '\\\\' + strategyName + ' ' + symbol + str(bar_type) + ' finalresult_dsl%s.csv' %\n stoplossTarget_dic['para_name'], index=False)\n timeend = time.time()\n timecost = timeend - timestart\n print (u\"dsl_%s 计算完毕,共%d组数据,总耗时%.3f秒,平均%.3f秒/组\" % (\n stoplossTarget_dic['para_name'], paranum, timecost, timecost / paranum))\n allresultdf.to_csv(strategyName + ' ' + symbol + str(bar_type) + ' finalresult_dsl.csv', index=False)\n\n\ndef getOwnl(strategyName, symbolInfo, bar_type, ownl_para_dic_list, parasetlist, bar1mdic, barxmdic, result_para_dic,\n indexcols, progress=False):\n symbol = symbolInfo.domain_symbol\n new_indexcols = []\n for i in indexcols:\n new_indexcols.append('new_' + i)\n allresultdf_cols = ['setname', 'winSwitch', 'worknum'] + indexcols + new_indexcols\n ownlallresultdf = pd.DataFrame(columns=allresultdf_cols)\n allnum = 0\n paranum = parasetlist.shape[0]\n for winSwitchDic in ownl_para_dic_list:\n timestart = time.time()\n ownlFolderName = \"OnceWinNoLoss%s\" % winSwitchDic['para_name']\n try:\n os.mkdir(ownlFolderName) # 创建文件夹\n except:\n # print \"dir already exist!\"\n pass\n print (\"OnceWinNoLoss WinSwitch:%s\" % winSwitchDic['para_name'])\n\n ownlresultdf = pd.DataFrame(columns=allresultdf_cols)\n\n setnum = 0\n numlist = range(0, paranum, 100)\n numlist.append(paranum)\n for n in range(1, len(numlist)):\n pool = multiprocessing.Pool(multiprocessing.cpu_count() - 1)\n l = []\n for a in range(numlist[n - 1], numlist[n]):\n setname = parasetlist.ix[a, 'Setname']\n if not progress:\n l.append(pool.apply_async(ownl.ownlCal,\n (strategyName, symbolInfo, bar_type, setname, bar1mdic, barxmdic,\n winSwitchDic, result_para_dic,\n ownlFolderName + '\\\\', indexcols)))\n else:\n # l.append(ownl.progressOwnlCal(strategyName, symbolInfo, K_MIN, setname, bar1m, barxm, winSwitch,\n # nolossThreshhold, positionRatio, initialCash,\n # ownlFolderName + '\\\\'))\n l.append(pool.apply_async(ownl.progressOwnlCal,\n (strategyName, symbolInfo, bar_type, setname, bar1mdic, barxmdic,\n winSwitchDic, result_para_dic,\n ownlFolderName + '\\\\', indexcols)))\n pool.close()\n pool.join()\n\n for res in l:\n ownlresultdf.loc[setnum] = res.get()\n ownlallresultdf.loc[allnum] = ownlresultdf.loc[setnum]\n setnum += 1\n allnum += 1\n # ownlresultdf['cashDelta'] = ownlresultdf['new_endcash'] - ownlresultdf['old_endcash']\n ownlresultdf.to_csv(\n ownlFolderName + '\\\\' + strategyName + ' ' + symbol + str(bar_type) + ' finalresult_ownl%s.csv' %\n winSwitchDic['para_name'], index=False)\n timeend = time.time()\n timecost = timeend - timestart\n print (\n u\"ownl_%s 计算完毕,共%d组数据,总耗时%.3f秒,平均%.3f秒/组\" % (\n winSwitchDic['para_name'], paranum, timecost, timecost / paranum))\n # ownlallresultdf['cashDelta'] = ownlallresultdf['new_endcash'] - ownlallresultdf['old_endcash']\n ownlallresultdf.to_csv(strategyName + ' ' + symbol + str(bar_type) + ' finalresult_ownl.csv', index=False)\n\n\ndef getFRSL(strategyName, symbolInfo, K_MIN, fixRateDicList, parasetlist, bar1mdic, barxmdic, result_para_dic,\n indexcols, progress=False):\n symbol = symbolInfo.domain_symbol\n new_indexcols = []\n for i in indexcols:\n new_indexcols.append('new_' + i)\n allresultdf = pd.DataFrame(columns=['setname', 'fixRate', 'worknum'] + indexcols + new_indexcols)\n allnum = 0\n paranum = parasetlist.shape[0]\n for fixRateTarget in fixRateDicList:\n timestart = time.time()\n folderName = \"FixRateStopLoss%s\" % fixRateTarget['para_name']\n try:\n os.mkdir(folderName) # 创建文件夹\n except:\n # print 'folder already exist'\n pass\n print (\"fixRateTarget:%s\" % fixRateTarget['para_name'])\n\n resultdf = pd.DataFrame(columns=['setname', 'fixRate', 'worknum'] + indexcols + new_indexcols)\n setnum = 0\n numlist = range(0, paranum, 100)\n numlist.append(paranum)\n for n in range(1, len(numlist)):\n pool = multiprocessing.Pool(multiprocessing.cpu_count() - 1)\n l = []\n for a in range(numlist[n - 1], numlist[n]):\n setname = parasetlist.ix[a, 'Setname']\n if not progress:\n # l.append(frsl.frslCal(strategyName,\n # symbolInfo, K_MIN, setname, bar1m, barxm, fixRateTarget, positionRatio,initialCash, folderName + '\\\\'))\n l.append(pool.apply_async(frsl.frslCal, (strategyName,\n symbolInfo, K_MIN, setname, bar1mdic, barxmdic,\n fixRateTarget, result_para_dic, folderName + '\\\\',\n indexcols)))\n else:\n l.append(pool.apply_async(frsl.progressFrslCal, (strategyName,\n symbolInfo, K_MIN, setname, bar1mdic, barxmdic,\n fixRateTarget, result_para_dic, folderName + '\\\\',\n indexcols)))\n pool.close()\n pool.join()\n\n for res in l:\n resultdf.loc[setnum] = res.get()\n allresultdf.loc[allnum] = resultdf.loc[setnum]\n setnum += 1\n allnum += 1\n # resultdf['cashDelta'] = resultdf['new_endcash'] - resultdf['old_endcash']\n resultdf.to_csv(\n folderName + '\\\\' + strategyName + ' ' + symbol + str(K_MIN) + ' finalresult_frsl%s.csv' % fixRateTarget[\n 'para_name'], index=False)\n timeend = time.time()\n timecost = timeend - timestart\n print (\n u\"frsl_%s 计算完毕,共%d组数据,总耗时%.3f秒,平均%.3f秒/组\" % (\n fixRateTarget['para_name'], paranum, timecost, timecost / paranum))\n # allresultdf['cashDelta'] = allresultdf['new_endcash'] - allresultdf['old_endcash']\n allresultdf.to_csv(strategyName + ' ' + symbol + str(K_MIN) + ' finalresult_frsl.csv', index=False)\n\n\ndef get_atr_sl(strategyName, symbolInfo, bar_type, atr_para_list, parasetlist, bar1mdic, barxmdic, result_para_dic,\n indexcols, progress=False):\n symbol = symbolInfo.domain_symbol\n new_indexcols = []\n for i in indexcols:\n new_indexcols.append('new_' + i)\n allresultdf = pd.DataFrame(columns=['setname', 'atr_sl_target', 'worknum'] + indexcols + new_indexcols)\n allnum = 0\n paranum = parasetlist.shape[0]\n for atr_para in atr_para_list:\n timestart = time.time()\n folderName = 'ATRSL%s' % atr_para['para_name']\n\n try:\n os.mkdir(folderName) # 创建文件夹\n except:\n # print 'folder already exist'\n pass\n\n resultdf = pd.DataFrame(columns=['setname', 'atr_sl_target', 'worknum'] + indexcols + new_indexcols)\n setnum = 0\n numlist = range(0, paranum, 100)\n numlist.append(paranum)\n for n in range(1, len(numlist)):\n pool = multiprocessing.Pool(multiprocessing.cpu_count() - 1)\n l = []\n for a in range(numlist[n - 1], numlist[n]):\n setname = parasetlist.ix[a, 'Setname']\n if not progress:\n # l.append(atrsl.atrsl(strategyName, symbolInfo, bar_type, setname, bar1mdic, barxmdic, atr_para, result_para_dic, folderName + '\\\\',\n # indexcols, timestart))\n l.append(pool.apply_async(atrsl.atrsl, (strategyName,\n symbolInfo, bar_type, setname, bar1mdic, barxmdic, atr_para,\n result_para_dic, folderName + '\\\\',\n indexcols, timestart)))\n else:\n l.append(pool.apply_async(atrsl.progress_atrsl, (strategyName,\n symbolInfo, K_MIN, setname, bar1mdic, barxmdic,\n atr_para, result_para_dic, folderName + '\\\\',\n indexcols)))\n pool.close()\n pool.join()\n\n for res in l:\n resultdf.loc[setnum] = res.get()\n allresultdf.loc[allnum] = resultdf.loc[setnum]\n setnum += 1\n allnum += 1\n # resultdf['cashDelta'] = resultdf['new_endcash'] - resultdf['old_endcash']\n resultdf.to_csv(\n folderName + '\\\\' + strategyName + ' ' + symbol + str(K_MIN) + ' finalresult_atrsl%s.csv' % folderName,\n index=False)\n timeend = time.time()\n timecost = timeend - timestart\n print (u\"atr_%s 计算完毕,共%d组数据,总耗时%.3f秒,平均%.3f秒/组\" % (folderName, paranum, timecost, timecost / paranum))\n # allresultdf['cashDelta'] = allresultdf['new_endcash'] - allresultdf['old_endcash']\n allresultdf.to_csv(strategyName + ' ' + symbol + str(K_MIN) + ' finalresult_atrsl.csv', index=False)\n\n\ndef get_gownl(strategyName, symbolInfo, bar_type, gownl_para_list, parasetlist, bar1mdic, barxmdic, result_para_dic,\n indexcols, progress=False):\n symbol = symbolInfo.domain_symbol\n new_indexcols = []\n for i in indexcols:\n new_indexcols.append('new_' + i)\n allresultdf = pd.DataFrame(columns=['setname', 'atr_sl_target', 'worknum'] + indexcols + new_indexcols)\n allnum = 0\n paranum = parasetlist.shape[0]\n for gownl_para in gownl_para_list:\n timestart = time.time()\n folderName = 'GOWNL%s' % gownl_para['para_name']\n\n try:\n os.mkdir(folderName) # 创建文件夹\n except:\n # print 'folder already exist'\n pass\n\n resultdf = pd.DataFrame(columns=['setname', 'atr_sl_target', 'worknum'] + indexcols + new_indexcols)\n setnum = 0\n numlist = range(0, paranum, 100)\n numlist.append(paranum)\n for n in range(1, len(numlist)):\n pool = multiprocessing.Pool(multiprocessing.cpu_count() - 1)\n l = []\n for a in range(numlist[n - 1], numlist[n]):\n setname = parasetlist.ix[a, 'Setname']\n if not progress:\n # l.append(gownl.gownl(strategyName, symbolInfo, bar_type, setname, bar1mdic, barxmdic, gownl_para, result_para_dic, folderName + '\\\\',\n # indexcols, timestart))\n l.append(pool.apply_async(gownl.gownl, (strategyName,\n symbolInfo, bar_type, setname, bar1mdic, barxmdic,\n gownl_para, result_para_dic, folderName + '\\\\',\n indexcols, timestart)))\n else:\n l.append(pool.apply_async(gownl.progress_gownl, (strategyName,\n symbolInfo, bar_type, setname, bar1mdic, barxmdic,\n gownl_para, result_para_dic, folderName + '\\\\',\n indexcols)))\n pool.close()\n pool.join()\n\n for res in l:\n resultdf.loc[setnum] = res.get()\n allresultdf.loc[allnum] = resultdf.loc[setnum]\n setnum += 1\n allnum += 1\n # resultdf['cashDelta'] = resultdf['new_endcash'] - resultdf['old_endcash']\n resultdf.to_csv(\n folderName + '\\\\' + strategyName + ' ' + symbol + str(bar_type) + ' finalresult_gownl%s.csv' % folderName,\n index=False)\n timeend = time.time()\n timecost = timeend - timestart\n print (u\"gownl_%s 计算完毕,共%d组数据,总耗时%.3f秒,平均%.3f秒/组\" % (folderName, paranum, timecost, timecost / paranum))\n # allresultdf['cashDelta'] = allresultdf['new_endcash'] - allresultdf['old_endcash']\n allresultdf.to_csv(strategyName + ' ' + symbol + str(bar_type) + ' finalresult_gownl.csv', index=False)\n\n\ndef get_all_close(strategyName, symbolinfo, bar_type, all_close_para_dic, parasetlist, bar1mdic, barxmdic,\n result_para_dic, indexcols, progress):\n # 一次计算所有止损参数\n # 注:atrsl和fvsl暂不支持\n symbol = symbolinfo.domain_symbol\n new_indexcols = []\n for i in indexcols:\n new_indexcols.append('new_' + i)\n paranum = parasetlist.shape[0]\n all_result_dic = {} # 这个保存的是每个止损参数的结果\n for close_para_dic in all_close_para_dic:\n close_folder_prefix = close_para_dic['folderPrefix']\n paralist = close_para_dic['paralist']\n result_dic = {}\n for para in paralist:\n para_name = para['para_name']\n folderName = '%s%s' % (close_folder_prefix, para_name)\n try:\n os.mkdir(folderName) # 创建文件夹\n except:\n pass\n resultdf = pd.DataFrame(columns=['setname', close_para_dic['name'], 'worknum'] + indexcols + new_indexcols)\n result_dic[para_name] = resultdf\n all_result_dic[close_para_dic['name']] = result_dic\n timestart = time.time()\n setnum = 0\n numlist = range(0, paranum, 100)\n numlist.append(paranum)\n for n in range(1, len(numlist)):\n pool = multiprocessing.Pool(multiprocessing.cpu_count() - 1)\n l = []\n for a in range(numlist[n - 1], numlist[n]):\n setname = parasetlist.ix[a, 'Setname']\n l.append(pool.apply_async(all_close.all_close, (strategyName,\n symbolinfo, bar_type, setname, bar1mdic, barxmdic,\n all_close_para_dic, result_para_dic, indexcols, timestart)))\n pool.close()\n pool.join()\n\n for res in l:\n get_result_dic = res.get()\n for k, v in get_result_dic:\n result_dic = all_result_dic[k]\n for k1, v1 in v:\n result_dic[k1].loc[setnum] = v1\n setnum += 1\n for close_para_dic in all_close_para_dic:\n close_folder_prefix = close_para_dic['folderPrefix']\n paralist = close_para_dic['paralist']\n close_type = close_para_dic['name']\n result_dic = all_result_dic[close_type]\n all_result_list = []\n for para in paralist:\n para_name = para['para_name']\n folderName = '%s%s' % (close_folder_prefix, para_name)\n resultdf = result_dic[para_name]\n resultdf.to_csv(\n folderName + '\\\\' + strategyName + ' ' + symbol + str(bar_type) + ' finalresult_%s%s.csv' % (\n close_type, para_name),\n index=False)\n all_result_list.append(resultdf)\n all_final_result = pd.concat(all_result_list)\n all_final_result.to_csv(strategyName + ' ' + symbol + str(bar_type) + ' finalresult_%s.csv' % close_type,\n index=False)\n timeend = time.time()\n timecost = timeend - timestart\n print (u\"全部止损计算完毕,共%d组数据,总耗时%.3f秒,平均%.3f秒/组\" % (paranum, timecost, timecost / paranum))\n\n\ndef getDslOwnl(strategyName, symbolInfo, K_MIN, parasetlist, stoplossList, winSwitchList, result_para_dic, indexcols):\n symbol = symbolInfo.domain_symbol\n allresultdf = pd.DataFrame(\n columns=['setname', 'dslTarget', 'ownlWinSwtich', 'old_endcash', 'old_Annual', 'old_Sharpe', 'old_Drawback',\n 'old_SR', 'new_endcash', 'new_Annual', 'new_Sharpe', 'new_Drawback', 'new_SR',\n 'dslWorknum', 'ownlWorknum', 'dslRetDelta', 'ownlRetDelta'])\n allnum = 0\n paranum = parasetlist.shape[0]\n for stoplossTarget in stoplossList:\n for winSwitch in winSwitchList:\n dslFolderName = \"DynamicStopLoss%.1f\\\\\" % (stoplossTarget * 1000)\n ownlFolderName = \"OnceWinNoLoss%.1f\\\\\" % (winSwitch * 1000)\n newfolder = (\"dsl_%.3f_ownl_%.3f\" % (stoplossTarget, winSwitch))\n try:\n os.mkdir(newfolder) # 创建文件夹\n except:\n # print newfolder, ' already exist!'\n pass\n print (\"slTarget:%f ownlSwtich:%f\" % (stoplossTarget, winSwitch))\n pool = multiprocessing.Pool(multiprocessing.cpu_count() - 1)\n l = []\n for sn in range(0, paranum):\n setname = parasetlist.ix[sn, 'Setname']\n l.append(pool.apply_async(dslownl.dslAndownlCal,\n (strategyName, symbolInfo, K_MIN, setname, stoplossTarget, winSwitch,\n result_para_dic, dslFolderName,\n ownlFolderName, newfolder + '\\\\')))\n pool.close()\n pool.join()\n\n resultdf = pd.DataFrame(\n columns=['setname', 'dslTarget', 'ownlWinSwtich', 'old_endcash', 'old_Annual', 'old_Sharpe',\n 'old_Drawback',\n 'old_SR', 'new_endcash', 'new_Annual', 'new_Sharpe', 'new_Drawback', 'new_SR',\n 'dslWorknum', 'ownlWorknum', 'dslRetDelta', 'ownlRetDelta'])\n i = 0\n for res in l:\n resultdf.loc[i] = res.get()\n allresultdf.loc[allnum] = resultdf.loc[i]\n i += 1\n allnum += 1\n resultfilename = (\n \"%s %s%d finalresult_dsl%.3f_ownl%.3f.csv\" % (strategyName, symbol, K_MIN, stoplossTarget, winSwitch))\n resultdf.to_csv(newfolder + '\\\\' + resultfilename)\n\n # allresultdf['cashDelta'] = allresultdf['new_endcash'] - allresultdf['old_endcash']\n allresultdf.to_csv(strategyName + ' ' + symbol + str(K_MIN) + ' finalresult_dsl_ownl.csv')\n\n\ndef getMultiSLT(strategyName, symbolInfo, K_MIN, parasetlist, barxmdic, sltlist, result_para_dic, indexcols):\n \"\"\"\n 计算多个止损策略结合回测的结果\n :param strategyName:\n :param symbolInfo:\n :param K_MIN:\n :param parasetlist:\n :param sltlist:\n :param positionRatio:\n :param initialCash:\n :return:\n \"\"\"\n symbol = symbolInfo.domain_symbol\n new_indexcols = []\n for i in indexcols:\n new_indexcols.append('new_' + i)\n allresultdf_cols = ['setname', 'slt', 'slWorkNum'] + indexcols + new_indexcols\n allresultdf = pd.DataFrame(columns=allresultdf_cols)\n\n allnum = 0\n paranum = parasetlist.shape[0]\n\n # dailyK = DC.generatDailyClose(barxm)\n\n # 先生成参数列表\n allSltSetList = [] # 这是一个二维的参数列表,每一个元素是一个止损目标的参数dic列表\n for slt in sltlist:\n sltset = []\n for t in slt['paralist']:\n sltset.append({'name': slt['name'],\n 'sltValue': t, # t是一个参数字典\n 'folder': (\"%s%s\\\\\" % (slt['folderPrefix'], t['para_name'])),\n 'fileSuffix': slt['fileSuffix']\n })\n allSltSetList.append(sltset)\n finalSltSetList = [] # 二维数据,每个一元素是一个多个止损目标的参数dic组合\n for sltpara in allSltSetList[0]:\n finalSltSetList.append([sltpara])\n for i in range(1, len(allSltSetList)):\n tempset = allSltSetList[i]\n newset = []\n for o in finalSltSetList:\n for t in tempset:\n newset.append(o + [t])\n finalSltSetList = newset\n print finalSltSetList\n\n for sltset in finalSltSetList:\n newfolder = ''\n for sltp in sltset:\n # newfolder += (sltp['name'] + '_%.3f' % (sltp['sltValue']))\n v = sltp['sltValue']\n newfolder += \"{}_{}\".format(sltp['name'], v[\"para_name\"])\n try:\n os.mkdir(newfolder) # 创建文件夹\n except:\n pass\n print (newfolder)\n pool = multiprocessing.Pool(multiprocessing.cpu_count() - 1)\n l = []\n for sn in range(0, paranum):\n setname = parasetlist.ix[sn, 'Setname']\n # l.append(msl.multiStopLosslCal(strategyName, symbolInfo, K_MIN, setname, sltset, positionRatio, initialCash,\n # newfolder + '\\\\'))\n l.append(pool.apply_async(msl.multiStopLosslCal,\n (strategyName, symbolInfo, K_MIN, setname, sltset, barxmdic, result_para_dic,\n newfolder, indexcols)))\n pool.close()\n pool.join()\n\n resultdf = pd.DataFrame(columns=allresultdf_cols)\n i = 0\n for res in l:\n resultdf.loc[i] = res.get()\n allresultdf.loc[allnum] = resultdf.loc[i]\n i += 1\n allnum += 1\n resultfilename = (\"%s %s%d finalresult_multiSLT_%s.csv\" % (strategyName, symbol, K_MIN, newfolder))\n resultdf.to_csv(newfolder + '\\\\' + resultfilename, index=False)\n\n allresultname = ''\n for slt in sltlist:\n allresultname += slt['name']\n # allresultdf['cashDelta'] = allresultdf['new_endcash'] - allresultdf['old_endcash']\n allresultdf.to_csv(\"%s %s%d finalresult_multiSLT_%s.csv\" % (strategyName, symbol, K_MIN, allresultname),\n index=False)\n pass\n\n\nif __name__ == '__main__':\n # 文件路径\n upperpath = DC.getUpperPath(Parameter.folderLevel)\n resultpath = upperpath + Parameter.resultFolderName\n\n # 取参数集\n # parasetlist = pd.read_csv(resultpath + Parameter.parasetname)\n # paranum = parasetlist.shape[0]\n\n # indexcols\n indexcols = Parameter.ResultIndexDic\n\n # 参数设置\n strategyParameterSet = []\n if not Parameter.symbol_KMIN_opt_swtich:\n # 单品种单周期模式\n paradic = {\n 'strategyName': Parameter.strategyName,\n 'exchange_id': Parameter.exchange_id,\n 'sec_id': Parameter.sec_id,\n 'K_MIN': Parameter.K_MIN,\n 'startdate': Parameter.startdate,\n 'enddate': Parameter.enddate,\n 'result_para_dic': Parameter.result_para_dic,\n 'progress': Parameter.progress_close,\n 'calcDsl': Parameter.calcDsl_close,\n 'calcOwnl': Parameter.calcOwnl_close,\n 'calcFrsl': Parameter.calcFrsl_close,\n 'calcMultiSLT': Parameter.calcMultiSLT_close,\n 'calc_all_close': Parameter.calc_all_close,\n 'dsl_target_list': Parameter.dsl_target_list_close,\n 'ownl_protect_list': Parameter.ownl_protect_list_close,\n 'ownl_floor_list': Parameter.ownl_floor_list_close,\n 'frsl_target_list': Parameter.frsl_target_list_close,\n 'calcAtrsl': Parameter.calcAtrsl_close,\n 'atr_pendant_n_list': Parameter.atr_pendant_n_list_close,\n 'atr_pendant_rate_list': Parameter.atr_pendant_rate_list_close,\n 'atr_yoyo_n_list': Parameter.atr_yoyo_n_list_close,\n 'atr_yoyo_rate_list': Parameter.atr_yoyo_rate_list_close,\n 'calcGownl': Parameter.calcGownl_close,\n 'gownl_protect_list': Parameter.gownl_protect_list_close,\n 'gownl_floor_list': Parameter.gownl_floor_list_close,\n 'gownl_step_list': Parameter.gownl_step_list_close\n }\n strategyParameterSet.append(paradic)\n else:\n # 多品种多周期模式\n symbolset = pd.read_excel(resultpath + Parameter.stoploss_set_filename, index_col='No')\n symbolsetNum = symbolset.shape[0]\n for i in range(symbolsetNum):\n exchangeid = symbolset.ix[i, 'exchange_id']\n secid = symbolset.ix[i, 'sec_id']\n strategyParameterSet.append({\n 'strategyName': symbolset.ix[i, 'strategyName'],\n 'exchange_id': exchangeid,\n 'sec_id': secid,\n 'K_MIN': symbolset.ix[i, 'K_MIN'],\n 'startdate': symbolset.ix[i, 'startdate'],\n 'enddate': symbolset.ix[i, 'enddate'],\n 'result_para_dic': Parameter.result_para_dic,\n 'progress': symbolset.ix[i, 'progress'],\n 'calcDsl': symbolset.ix[i, 'calcDsl'],\n 'calcOwnl': symbolset.ix[i, 'calcOwnl'],\n 'calcFrsl': symbolset.ix[i, 'calcFrsl'],\n 'calcMultiSLT': symbolset.ix[i, 'calcMultiSLT'],\n 'calc_all_close': symbolset.ix[i, 'calcAllClose'],\n 'dsl_target_list': Parameter.para_str_to_float(symbolset.ix[i, 'dsl_target']),\n 'ownl_protect_list': Parameter.para_str_to_float(symbolset.ix[i, 'ownl_protect']),\n 'ownl_floor_list': Parameter.para_str_to_float(symbolset.ix[i, 'ownl_floor']),\n 'frsl_target_list': Parameter.para_str_to_float(symbolset.ix[i, 'frsl_target']),\n 'calcAtrsl': symbolset.ix[i, 'calcAtrsl'],\n 'atr_pendant_n_list': Parameter.para_str_to_float(symbolset.ix[i, 'atr_pendant_n']),\n 'atr_pendant_rate_list': Parameter.para_str_to_float(symbolset.ix[i, 'atr_pendant_rate']),\n 'atr_yoyo_n_list': Parameter.para_str_to_float(symbolset.ix[i, 'atr_yoyo_n']),\n 'atr_yoyo_rate_list': Parameter.para_str_to_float(symbolset.ix[i, 'atr_yoyo_n']),\n 'calcGownl': symbolset.ix[i, 'calcGownl'],\n 'gownl_protect_list': Parameter.para_str_to_float(symbolset.ix[i, 'gownl_protect']),\n 'gownl_floor_list': Parameter.para_str_to_float(symbolset.ix[i, 'gownl_floor']),\n 'gownl_step_list': Parameter.para_str_to_float(symbolset.ix[i, 'gownl_step'])\n }\n )\n\n for strategyParameter in strategyParameterSet:\n\n strategyName = strategyParameter['strategyName']\n exchange_id = strategyParameter['exchange_id']\n sec_id = strategyParameter['sec_id']\n K_MIN = strategyParameter['K_MIN']\n startdate = strategyParameter['startdate']\n enddate = strategyParameter['enddate']\n domain_symbol = '.'.join([exchange_id, sec_id])\n\n result_para_dic = strategyParameter['result_para_dic']\n\n symbolinfo = DC.SymbolInfo(domain_symbol, startdate, enddate)\n pricetick = symbolinfo.getPriceTick()\n\n # 计算控制开关\n progress = strategyParameter['progress']\n calc_all_close = strategyParameter['calc_all_close']\n calcDsl = strategyParameter['calcDsl']\n calcOwnl = strategyParameter['calcOwnl']\n calcFrsl = strategyParameter['calcFrsl']\n calcMultiSLT = strategyParameter['calcMultiSLT']\n calcAtrsl = strategyParameter['calcAtrsl']\n calcGownl = strategyParameter['calcGownl']\n\n # 优化参数\n dsl_para_dic_list = []\n if calcDsl:\n dsl_target_list = strategyParameter['dsl_target_list']\n for dsl_target in dsl_target_list:\n dsl_para_dic_list.append({\n 'para_name': str(dsl_target),\n 'dsl_target': dsl_target\n })\n\n ownl_para_dic_list = []\n if calcOwnl:\n # stoplossList=[-0.022]\n ownl_protect_list = strategyParameter['ownl_protect_list']\n # winSwitchList=[0.009]\n ownl_floor_list = strategyParameter['ownl_floor_list']\n for ownl_protect in ownl_protect_list:\n for ownl_floor in ownl_floor_list:\n ownl_para_dic_list.append(\n {\n 'para_name': \"%.3f_%d\" % (ownl_protect, ownl_floor),\n 'ownl_protect': ownl_protect,\n 'ownl_floor': ownl_floor * pricetick\n }\n )\n\n frsl_para_dic_list = []\n if calcFrsl:\n frsl_target_list = strategyParameter['frsl_target_list']\n for frsl_target in frsl_target_list:\n frsl_para_dic_list.append({\n 'para_name': str(frsl_target),\n 'frsl_target': frsl_target\n })\n\n atrsl_para_dic_list = []\n if calcAtrsl:\n atr_pendant_n_list = strategyParameter['atr_pendant_n_list']\n atr_pendan_rate_list = strategyParameter['atr_pendant_rate_list']\n atr_yoyo_n_list = strategyParameter['atr_yoyo_n_list']\n atr_yoyo_rate_list = strategyParameter['atr_yoyo_rate_list']\n for atr_pendant_n in atr_pendant_n_list:\n for atr_pendant_rate in atr_pendan_rate_list:\n for atr_yoyo_n in atr_yoyo_n_list:\n for atr_yoyo_rate in atr_yoyo_rate_list:\n atrsl_para_dic_list.append(\n {\n 'para_name': '%d_%.1f_%d_%.1f' % (\n atr_pendant_n, atr_pendant_rate, atr_yoyo_n, atr_yoyo_rate),\n 'atr_pendant_n': atr_pendant_n,\n 'atr_pendant_rate': atr_pendant_rate,\n 'atr_yoyo_n': atr_yoyo_n,\n 'atr_yoyo_rate': atr_yoyo_rate\n }\n )\n\n gownl_para_dic_list = []\n if calcGownl:\n gownl_protect_list = strategyParameter['gownl_protect_list']\n gownl_floor_list = strategyParameter['gownl_floor_list']\n gownl_step_list = strategyParameter['gownl_step_list']\n for gownl_protect in gownl_protect_list:\n for gownl_floor in gownl_floor_list:\n for gownl_step in gownl_step_list:\n gownl_para_dic_list.append(\n {\n 'para_name': '%.3f_%.1f_%.1f' % (gownl_protect, gownl_floor, gownl_step),\n 'gownl_protect': gownl_protect,\n 'gownl_floor': gownl_floor,\n 'gownl_step': gownl_step * pricetick\n }\n )\n\n # 文件路径\n foldername = ' '.join([strategyName, exchange_id, sec_id, str(K_MIN)])\n oprresultpath = resultpath + foldername + '\\\\'\n os.chdir(oprresultpath)\n\n # 原始数据处理\n # bar1m=DC.getBarData(symbol=symbol,K_MIN=60,starttime=startdate+' 00:00:00',endtime=enddate+' 23:59:59')\n # barxm=DC.getBarData(symbol=symbol,K_MIN=K_MIN,starttime=startdate+' 00:00:00',endtime=enddate+' 23:59:59')\n # bar1m计算longHigh,longLow,shortHigh,shortLow\n # bar1m=bar1mPrepare(bar1m)\n # bar1mdic = DC.getBarBySymbolList(domain_symbol, symbolinfo.getSymbolList(), 60, startdate, enddate)\n # barxmdic = DC.getBarBySymbolList(domain_symbol, symbolinfo.getSymbolList(), K_MIN, startdate, enddate)\n cols = ['open', 'high', 'low', 'close', 'strtime', 'utc_time', 'utc_endtime']\n # bar1mdic = DC.getBarDic(symbolinfo, 60, cols)\n # barxmdic = DC.getBarDic(symbolinfo, K_MIN, cols)\n bar1mdic = DC.getBarBySymbolList(domain_symbol, symbolinfo.getSymbolList(), 60, startdate, enddate, cols)\n barxmdic = DC.getBarBySymbolList(domain_symbol, symbolinfo.getSymbolList(), K_MIN, startdate, enddate, cols)\n\n # 取参数集\n parasetlist = pd.read_csv(\"%s %s %d %s\" % (exchange_id, sec_id, K_MIN, Parameter.parasetname))\n paranum = parasetlist.shape[0]\n\n if calcMultiSLT or calc_all_close:\n sltlist = []\n if calcDsl:\n sltlist.append({'name': 'dsl',\n 'paralist': dsl_para_dic_list,\n 'folderPrefix': 'DynamicStopLoss',\n 'fileSuffix': 'resultDSL_by_tick.csv'})\n if calcOwnl:\n sltlist.append({'name': 'ownl',\n 'paralist': ownl_para_dic_list,\n 'folderPrefix': 'OnceWinNoLoss',\n 'fileSuffix': 'resultOWNL_by_tick.csv'})\n if calcFrsl:\n sltlist.append({'name': 'frsl',\n 'paralist': frsl_para_dic_list,\n 'folderPrefix': 'FixRateStopLoss',\n 'fileSuffix': 'resultFRSL_by_tick.csv'})\n if calcAtrsl and not calc_all_close: # all_close模式不支持atrsl\n sltlist.append({'name': 'atrsl',\n 'paralist': atrsl_para_dic_list,\n 'folderPrefix': 'ATRSL',\n 'fileSuffix': 'resultATRSL_by_tick.csv'\n })\n if calcGownl:\n sltlist.append({'name': 'gownl',\n 'paralist': gownl_para_dic_list,\n 'folderPrefix': 'GOWNL',\n 'fileSuffix': 'resultGOWNL_by_tick.csv'\n })\n if calcMultiSLT:\n getMultiSLT(strategyName, symbolinfo, K_MIN, parasetlist, barxmdic, sltlist, result_para_dic, indexcols)\n else:\n pass\n else:\n if calcDsl:\n getDSL(strategyName, symbolinfo, K_MIN, dsl_para_dic_list, parasetlist, bar1mdic, barxmdic,\n result_para_dic, indexcols, progress)\n\n if calcOwnl:\n getOwnl(strategyName, symbolinfo, K_MIN, ownl_para_dic_list, parasetlist, bar1mdic, barxmdic,\n result_para_dic, indexcols, progress)\n\n if calcFrsl:\n getFRSL(strategyName, symbolinfo, K_MIN, frsl_para_dic_list, parasetlist, bar1mdic, barxmdic,\n result_para_dic, indexcols, progress)\n\n if calcAtrsl:\n get_atr_sl(strategyName, symbolinfo, K_MIN, atrsl_para_dic_list, parasetlist, bar1mdic, barxmdic,\n result_para_dic, indexcols, progress=False)\n\n if calcGownl:\n get_gownl(strategyName, symbolinfo, K_MIN, gownl_para_dic_list, parasetlist, bar1mdic, barxmdic,\n result_para_dic, indexcols)\n"
},
{
"alpha_fraction": 0.589451789855957,
"alphanum_fraction": 0.591485857963562,
"avg_line_length": 48.87439727783203,
"blob_id": "b3b61deed20554806f609f63a6ab7ce92d6042d1",
"content_id": "a92c771610afb8349c66c18f3d6059bb4cb5fa31",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 21040,
"license_type": "no_license",
"max_line_length": 181,
"num_lines": 414,
"path": "/HullRsiWin/HullRsiWin_Forward.py",
"repo_name": "smartgang/RsiWin",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nimport multiTargetForward as mtf\nfrom datetime import datetime\nimport pandas as pd\nimport DATA_CONSTANTS as DC\nimport os\nimport multiprocessing\nimport HullRsiWin_Parameter as Parameter\nimport numpy as np\n\n\ndef getForward(strategyName, symbolinfo, K_MIN, parasetlist, rawdatapath, startdate, enddate, nextmonth, windowsSet, colslist, result_para_dic, indexcolsFlag,\n resultfilesuffix):\n symbol = symbolinfo.domain_symbol\n forwordresultpath = rawdatapath + '\\\\ForwardResults\\\\'\n forwardrankpath = rawdatapath + '\\\\ForwardRank\\\\'\n monthlist = [datetime.strftime(x, '%Y-%m') for x in list(pd.date_range(start=startdate, end=enddate, freq='M'))]\n monthlist.append(nextmonth)\n os.chdir(rawdatapath)\n try:\n os.mkdir('ForwardResults')\n except:\n print 'ForwardResults already exist!'\n try:\n os.mkdir('ForwardRank')\n except:\n print 'ForwardRank already exist!'\n try:\n os.mkdir('ForwardOprAnalyze')\n except:\n print 'ForwardOprAnalyze already exist!'\n\n starttime = datetime.now()\n print starttime\n # 多进程优化,启动一个对应CPU核心数量的进程池\n\n initialCash = result_para_dic['initialCash']\n positionRatio = result_para_dic['positionRatio']\n\n pool = multiprocessing.Pool(multiprocessing.cpu_count() - 1)\n l = []\n for whiteWindows in windowsSet:\n # l.append(mtf.runPara(strategyName,whiteWindows, symbolinfo, K_MIN, parasetlist, monthlist, rawdatapath, forwordresultpath, forwardrankpath, colslist, resultfilesuffix))\n l.append(pool.apply_async(mtf.runPara, (\n strategyName, whiteWindows, symbolinfo, K_MIN, parasetlist, monthlist, rawdatapath, forwordresultpath, forwardrankpath, colslist, resultfilesuffix)))\n pool.close()\n pool.join()\n mtf.calGrayResult(strategyName, symbol, K_MIN, windowsSet, forwardrankpath, rawdatapath)\n indexcols = Parameter.ResultIndexDic\n\n # rawdata = DC.getBarData(symbol, K_MIN, monthlist[12] + '-01 00:00:00', enddate + ' 23:59:59').reset_index(drop=True)\n cols = ['open', 'high', 'low', 'close', 'strtime', 'utc_time', 'utc_endtime']\n barxmdic = DC.getBarDic(symbolinfo, K_MIN, cols)\n\n mtf.calOprResult(strategyName, rawdatapath, symbolinfo, K_MIN, nextmonth, colslist, barxmdic, positionRatio, initialCash, indexcols, indexcolsFlag, resultfilesuffix)\n endtime = datetime.now()\n print starttime\n print endtime\n\n\ndef getDslForward(strategyName, dsl_para_dic_list, symbolinfo, K_MIN, parasetlist, folderpath, startdate, enddate, nextmonth, windowsSet, result_para_dic):\n print ('DSL forward start!')\n colslist = mtf.getColumnsName(True)\n resultfilesuffix = 'resultDSL_by_tick.csv'\n indexcolsFlag = True\n for dsl_para in dsl_para_dic_list:\n rawdatapath = folderpath + \"DynamicStopLoss%s\\\\\" % dsl_para['para_name']\n getForward(strategyName, symbolinfo, K_MIN, parasetlist, rawdatapath, startdate, enddate, nextmonth, windowsSet, colslist, result_para_dic, indexcolsFlag,\n resultfilesuffix)\n print ('DSL forward finished!')\n\n\ndef getownlForward(strategyName, ownl_para_dic_list, symbolinfo, K_MIN, parasetlist, folderpath, startdate, enddate, nextmonth, windowsSet, result_para_dic):\n print ('OWNL forward start!')\n colslist = mtf.getColumnsName(True)\n resultfilesuffix = 'resultOWNL_by_tick.csv'\n indexcolsFlag = True\n for ownl_para_dic in ownl_para_dic_list:\n rawdatapath = folderpath + \"OnceWinNoLoss%s\\\\\" % ownl_para_dic['para_name']\n getForward(strategyName, symbolinfo, K_MIN, parasetlist, rawdatapath, startdate, enddate, nextmonth, windowsSet, colslist, result_para_dic, indexcolsFlag,\n resultfilesuffix)\n print ('OWNL forward finished!')\n\n\ndef frsl_forward(strategyName, para_dic_list, symbolinfo, K_MIN, parasetlist, folderpath, startdate, enddate, nextmonth, windowsSet, result_para_dic):\n print ('FRSL forward start!')\n colslist = mtf.getColumnsName(True)\n resultfilesuffix = 'resultFRSL_by_tick.csv'\n indexcolsFlag = True\n for para_dic in para_dic_list:\n rawdatapath = folderpath + \"FixRateStopLoss%s\\\\\" % para_dic['para_name']\n getForward(strategyName, symbolinfo, K_MIN, parasetlist, rawdatapath, startdate, enddate, nextmonth, windowsSet, colslist, result_para_dic, indexcolsFlag,\n resultfilesuffix)\n print ('FRSL forward finished!')\n\n\ndef atrsl_forward(strategyName, atrsl_para_dic_list, symbolinfo, K_MIN, parasetlist, folderpath, startdate, enddate, nextmonth, windowsSet, result_para_dic):\n print ('ATRSL forward start!')\n colslist = mtf.getColumnsName(True)\n resultfilesuffix = 'resultATRSL_by_tick.csv'\n indexcolsFlag = True\n for atrsl_para_dic in atrsl_para_dic_list:\n rawdatapath = folderpath + \"ATRSL%s\\\\\" % atrsl_para_dic['para_name']\n getForward(strategyName, symbolinfo, K_MIN, parasetlist, rawdatapath, startdate, enddate, nextmonth, windowsSet, colslist, result_para_dic, indexcolsFlag,\n resultfilesuffix)\n print ('ATRSL forward finished!')\n\n\ndef gownl_forward(strategyName, para_dic_list, symbolinfo, K_MIN, parasetlist, folderpath, startdate, enddate, nextmonth, windowsSet, result_para_dic):\n print ('GOWNL forward start!')\n colslist = mtf.getColumnsName(True)\n resultfilesuffix = 'resultGOWNL_by_tick.csv'\n indexcolsFlag = True\n for para_dic in para_dic_list:\n rawdatapath = folderpath + \"GOWNL%s\\\\\" % para_dic['para_name']\n getForward(strategyName, symbolinfo, K_MIN, parasetlist, rawdatapath, startdate, enddate, nextmonth, windowsSet, colslist, result_para_dic, indexcolsFlag,\n resultfilesuffix)\n print ('GOWNL forward finished!')\n\n\ndef getdsl_ownlForward(strategyName, dsl_ownl_list, symbolinfo, K_MIN, parasetlist, folderpath, startdate, enddate, nextmonth, windowsSet, result_para_dic):\n print ('DSL_OWNL forward start!')\n colslist = mtf.getColumnsName(True)\n resultfilesuffix = 'result_dsl_ownl.csv'\n indexcolsFlag = True\n for dsl_ownl in dsl_ownl_list:\n newfolder = (\"dsl_%.3f_ownl_%.3f\\\\\" % (dsl_ownl[0], dsl_ownl[1]))\n rawdatapath = folderpath + newfolder # !!正常:'\\\\',双止损:填上'\\\\+双止损目标文件夹\\\\'\n getForward(strategyName, symbolinfo, K_MIN, parasetlist, rawdatapath, startdate, enddate, nextmonth, windowsSet, colslist, result_para_dic, indexcolsFlag,\n resultfilesuffix)\n print ('DSL_OWNL forward finished!')\n\n\ndef getMultiSltForward(strategyName, sltlist, symbolinfo, K_MIN, parasetlist, folderpath, startdate, enddate, nextmonth, windowsSet, result_para_dic):\n '''\n 混合止损推进\n '''\n print ('multiSLT forward start!')\n colslist = mtf.getColumnsName(True)\n resultfilesuffix = 'result_multiSLT.csv'\n indexcolsFlag = True\n # 先生成参数列表\n allSltSetList = [] # 这是一个二维的参数列表,每一个元素是一个止损目标的参数dic列表\n for slt in sltlist:\n sltset = []\n for t in slt['paralist']:\n sltset.append({'name': slt['name'],\n 'sltValue': t, # t是一个参数字典\n 'folder': (\"%s%s\\\\\" % (slt['folderPrefix'], t['para_name'])),\n 'fileSuffix': slt['fileSuffix']\n })\n allSltSetList.append(sltset)\n finalSltSetList = [] # 二维数据,每个一元素是一个多个止损目标的参数dic组合\n for sltpara in allSltSetList[0]:\n finalSltSetList.append([sltpara])\n for i in range(1, len(allSltSetList)):\n tempset = allSltSetList[i]\n newset = []\n for o in finalSltSetList:\n for t in tempset:\n newset.append(o + [t])\n finalSltSetList = newset\n print finalSltSetList\n for sltset in finalSltSetList:\n newfolder = ''\n for sltp in sltset:\n v = sltp['sltValue']\n newfolder += \"{}_{} \".format(sltp['name'], v[\"para_name\"])\n rawdatapath = folderpath + newfolder + '\\\\'\n print (\"multiSTL Target:%s\" % newfolder)\n getForward(strategyName, symbolinfo, K_MIN, parasetlist, rawdatapath, startdate, enddate, nextmonth, windowsSet, colslist, result_para_dic, indexcolsFlag, resultfilesuffix)\n print ('multiSTL forward finished!')\n\n\nif __name__ == '__main__':\n # 文件路径\n upperpath = DC.getUpperPath(Parameter.folderLevel)\n resultpath = upperpath + Parameter.resultFolderName\n\n # 取参数集\n parasetlist = pd.read_csv(resultpath + Parameter.parasetname)\n paranum = parasetlist.shape[0]\n windowsSet = range(Parameter.forwardWinStart, Parameter.forwardWinEnd + 1) # 白区窗口值\n # ======================================参数配置===================================================\n strategyParameterSet = []\n if not Parameter.symbol_KMIN_opt_swtich:\n # 单品种单周期模式\n paradic = {\n 'strategyName': Parameter.strategyName,\n 'exchange_id': Parameter.exchange_id,\n 'sec_id': Parameter.sec_id,\n 'K_MIN': Parameter.K_MIN,\n 'startdate': Parameter.startdate,\n 'enddate': Parameter.enddate,\n 'result_para_dic': Parameter.result_para_dic,\n # 'nextmonth':Parameter.nextMonthName,\n 'commonForward': Parameter.common_forward,\n 'calcDsl': Parameter.calcDsl_forward,\n 'calcOwnl': Parameter.calcOwnl_forward,\n 'calcFrsl': Parameter.calcFrsl_forward,\n 'dsl_target_list': Parameter.dsl_target_list_forward,\n 'ownl_protect_list': Parameter.ownl_protect_list_forward,\n 'ownl_floor_list': Parameter.ownl_floor_list_forward,\n 'frsl_target_list': Parameter.frsl_target_list_forward,\n 'calcAtrsl': Parameter.calcAtrsl_forward,\n 'atr_pendant_n_list': Parameter.atr_pendant_n_list_forward,\n 'atr_pendant_rate_list': Parameter.atr_pendant_rate_list_forward,\n 'atr_yoyo_n_list': Parameter.atr_yoyo_n_list_forward,\n 'atr_yoyo_rate_list': Parameter.atr_yoyo_rate_list_forward,\n 'calcGownl': Parameter.calcGownl_forward,\n 'gownl_protect_list': Parameter.gownl_protect_list_forward,\n 'gownl_floor_list': Parameter.gownl_floor_list_forward,\n 'gownl_step_list': Parameter.gownl_step_list_forward,\n 'multiSTL': Parameter.multiSTL_forward # 混合止损推进开关\n }\n strategyParameterSet.append(paradic)\n else:\n # 多品种多周期模式\n symbolset = pd.read_excel(resultpath + Parameter.forward_set_filename, index_col='No')\n symbolsetNum = symbolset.shape[0]\n for i in range(symbolsetNum):\n exchangeid = symbolset.ix[i, 'exchange_id']\n secid = symbolset.ix[i, 'sec_id']\n strategyParameterSet.append({\n 'strategyName': symbolset.ix[i, 'strategyName'],\n 'exchange_id': exchangeid,\n 'sec_id': secid,\n 'K_MIN': symbolset.ix[i, 'K_MIN'],\n 'startdate': symbolset.ix[i, 'startdate'],\n 'enddate': symbolset.ix[i, 'enddate'],\n 'result_para_dic': Parameter.result_para_dic,\n # 'nextmonth':symbolset.ix[i,'nextmonth'],\n 'commonForward': symbolset.ix[i, 'commonForward'],\n 'calcDsl': symbolset.ix[i, 'calcDsl'],\n 'calcOwnl': symbolset.ix[i, 'calcOwnl'],\n 'calcFrsl': symbolset.ix[i, 'calcFrsl'],\n 'calcDslOwnl': symbolset.ix[i, 'calcDslOwnl'],\n 'multiSLT': symbolset.ix[i, 'multiSLT'], # 混合止损推进开关\n 'dsl_target_list': Parameter.para_str_to_float(symbolset.ix[i, 'dsl_target']),\n 'ownl_protect_list': Parameter.para_str_to_float(symbolset.ix[i, 'ownl_protect']),\n 'ownl_floor_list': Parameter.para_str_to_float(symbolset.ix[i, 'ownl_floor']),\n 'frsl_target_list': Parameter.para_str_to_float(symbolset.ix[i, 'frsl_target']),\n 'calcAtrsl': symbolset.ix[i, 'calcAtrsl'],\n 'atr_pendant_n_list': Parameter.para_str_to_float(symbolset.ix[i, 'atr_pendant_n']),\n 'atr_pendant_rate_list': Parameter.para_str_to_float(symbolset.ix[i, 'atr_pendant_rate']),\n 'atr_yoyo_n_list': Parameter.para_str_to_float(symbolset.ix[i, 'atr_yoyo_n']),\n 'atr_yoyo_rate_list': Parameter.para_str_to_float(symbolset.ix[i, 'atr_yoyo_n']),\n 'calcGownl': symbolset.ix[i, 'calcGownl'],\n 'gownl_protect_list': Parameter.para_str_to_float(symbolset.ix[i, 'gownl_protect']),\n 'gownl_floor_list': Parameter.para_str_to_float(symbolset.ix[i, 'gownl_floor']),\n 'gownl_step_list': Parameter.para_str_to_float(symbolset.ix[i, 'gownl_step'])\n }\n )\n\n for strategyParameter in strategyParameterSet:\n\n strategyName = strategyParameter['strategyName']\n exchange_id = strategyParameter['exchange_id']\n sec_id = strategyParameter['sec_id']\n K_MIN = strategyParameter['K_MIN']\n startdate = strategyParameter['startdate']\n enddate = strategyParameter['enddate']\n # nextmonth = strategyParameter['nextmonth']\n nextmonth = enddate[:7]\n symbol = '.'.join([exchange_id, sec_id])\n\n result_para_dic = strategyParameter['result_para_dic']\n\n symbolinfo = DC.SymbolInfo(symbol, startdate, enddate)\n slip = DC.getSlip(symbol)\n pricetick = DC.getPriceTick(symbol)\n\n # 计算控制开关\n progress = strategyParameter['progress']\n calcCommon = strategyParameter['commonForward']\n calcDsl = strategyParameter['calcDsl']\n calcOwnl = strategyParameter['calcOwnl']\n calcFrsl = strategyParameter['calcFrsl']\n calcMultiSLT = strategyParameter['multiSLT']\n calcAtrsl = strategyParameter['calcAtrsl']\n calcGownl = strategyParameter['calcGownl']\n # 优化参数\n dsl_para_dic_list = []\n if calcDsl:\n dsl_target_list = strategyParameter['dsl_target_list']\n for dsl_target in dsl_target_list:\n dsl_para_dic_list.append({\n 'para_name': str(dsl_target),\n 'dsl_target': dsl_target\n })\n\n ownl_para_dic_list = []\n if calcOwnl:\n # stoplossList=[-0.022]\n ownl_protect_list = strategyParameter['ownl_protect_list']\n # winSwitchList=[0.009]\n ownl_floor_list = strategyParameter['ownl_floor_list']\n for ownl_protect in ownl_protect_list:\n for ownl_floor in ownl_floor_list:\n ownl_para_dic_list.append(\n {\n 'para_name': \"%.3f_%d\" % (ownl_protect, ownl_floor),\n 'ownl_protect': ownl_protect,\n 'ownl_floor': ownl_floor * pricetick\n }\n )\n\n frsl_para_dic_list = []\n if calcFrsl:\n frsl_target_list = strategyParameter['frsl_target_list']\n for frsl_target in frsl_target_list:\n frsl_para_dic_list.append({\n 'para_name': str(frsl_target),\n 'frsl_target': frsl_target\n })\n\n atrsl_para_dic_list = []\n if calcAtrsl:\n atr_pendant_n_list = strategyParameter['atr_pendant_n_list']\n atr_pendan_rate_list = strategyParameter['atr_pendant_rate_list']\n atr_yoyo_n_list = strategyParameter['atr_yoyo_n_list']\n atr_yoyo_rate_list = strategyParameter['atr_yoyo_rate_list']\n for atr_pendant_n in atr_pendant_n_list:\n for atr_pendant_rate in atr_pendan_rate_list:\n for atr_yoyo_n in atr_yoyo_n_list:\n for atr_yoyo_rate in atr_yoyo_rate_list:\n atrsl_para_dic_list.append(\n {\n 'para_name': '%d_%.1f_%d_%.1f' % (\n atr_pendant_n, atr_pendant_rate, atr_yoyo_n, atr_yoyo_rate),\n 'atr_pendant_n': atr_pendant_n,\n 'atr_pendant_rate': atr_pendant_rate,\n 'atr_yoyo_n': atr_yoyo_n,\n 'atr_yoyo_rate': atr_yoyo_rate\n }\n )\n\n gownl_para_dic_list = []\n if calcGownl:\n gownl_protect_list = strategyParameter['gownl_protect_list']\n gownl_floor_list = strategyParameter['gownl_floor_list']\n gownl_step_list = strategyParameter['gownl_step_list']\n for gownl_protect in gownl_protect_list:\n for gownl_floor in gownl_floor_list:\n for gownl_step in gownl_step_list:\n gownl_para_dic_list.append(\n {\n 'para_name': '%.3f_%.1f_%.1f' % (gownl_protect, gownl_floor, gownl_step),\n 'gownl_protect': gownl_protect,\n 'gownl_floor': gownl_floor,\n 'gownl_step': gownl_step * pricetick\n }\n )\n\n # 文件路径\n foldername = ' '.join([strategyName, exchange_id, sec_id, str(K_MIN)])\n folderpath = resultpath + foldername + '\\\\'\n os.chdir(folderpath)\n\n parasetlist = pd.read_csv(resultpath + Parameter.parasetname)\n\n if calcMultiSLT:\n # 混合止损推进打开的情况下,只做混合止损推进\n sltlist = []\n if calcDsl:\n sltlist.append({'name': 'dsl',\n 'paralist': dsl_para_dic_list,\n 'folderPrefix': 'DynamicStopLoss',\n 'fileSuffix': 'resultDSL_by_tick.csv'})\n if calcOwnl:\n sltlist.append({'name': 'ownl',\n 'paralist': ownl_para_dic_list,\n 'folderPrefix': 'OnceWinNoLoss',\n 'fileSuffix': 'resultOWNL_by_tick.csv'})\n if calcFrsl:\n sltlist.append({'name': 'frsl',\n 'paralist': frsl_para_dic_list,\n 'folderPrefix': 'FixRateStopLoss',\n 'fileSuffix': 'resultFRSL_by_tick.csv'})\n if calcAtrsl:\n sltlist.append({'name': 'atrsl',\n 'paralist': atrsl_para_dic_list,\n 'folderPrefix': 'ATRSL',\n 'fileSuffix': 'resultATRSL_by_tick.csv'\n })\n if calcGownl:\n sltlist.append({'name': 'gownl',\n 'paralist': gownl_para_dic_list,\n 'folderPrefix': 'GOWNL',\n 'fileSuffix': 'resultGOWNL_by_tick.csv'\n })\n getMultiSltForward(strategyName, sltlist, symbolinfo, K_MIN, parasetlist, folderpath, startdate, enddate, nextmonth, windowsSet, result_para_dic)\n pass\n else:\n if calcCommon:\n colslist = mtf.getColumnsName(False)\n resultfilesuffix = 'result.csv'\n indexcolsFlag = False\n bt_folder = \"%s %d backtesting\\\\\" % (symbol, K_MIN)\n getForward(strategyName, symbolinfo, K_MIN, parasetlist, folderpath + bt_folder, startdate, enddate, nextmonth, windowsSet, colslist, result_para_dic, indexcolsFlag,\n resultfilesuffix)\n if calcDsl:\n getDslForward(strategyName, dsl_para_dic_list, symbolinfo, K_MIN, parasetlist, folderpath, startdate, enddate, nextmonth, windowsSet, result_para_dic)\n if calcOwnl:\n getownlForward(strategyName, ownl_para_dic_list, symbolinfo, K_MIN, parasetlist, folderpath, startdate, enddate, nextmonth, windowsSet, result_para_dic)\n if calcFrsl:\n frsl_forward(strategyName, frsl_para_dic_list, symbolinfo, K_MIN, parasetlist, folderpath, startdate,\n enddate, nextmonth, windowsSet, result_para_dic)\n if calcAtrsl:\n atrsl_forward(strategyName, atrsl_para_dic_list, symbolinfo, K_MIN, parasetlist, folderpath, startdate,\n enddate, nextmonth, windowsSet, result_para_dic)\n if calcGownl:\n gownl_forward(strategyName, gownl_para_dic_list, symbolinfo, K_MIN, parasetlist, folderpath, startdate,\n enddate, nextmonth, windowsSet, result_para_dic)\n"
},
{
"alpha_fraction": 0.5796396732330322,
"alphanum_fraction": 0.5856448411941528,
"avg_line_length": 41.47368240356445,
"blob_id": "0d0c3c47f8ffb1b55bd770e596f78698859d71d2",
"content_id": "a6115f8487beee846ee3523446b604aaec94287f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11045,
"license_type": "no_license",
"max_line_length": 148,
"num_lines": 247,
"path": "/HullRsiWin/HullRsiWin_Parallel.py",
"repo_name": "smartgang/RsiWin",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n'''\n'''\nfrom HullRsiWin import HullRsiWin\nimport pandas as pd\nimport os\nimport DATA_CONSTANTS as DC\nimport multiprocessing\nimport HullRsiWin_Parameter as Parameter\nimport ResultStatistics as RS\nimport time\n\n\ndef getResult(strategyName, symbolinfo, K_MIN, setname, rawdataDic, para, result_para_dic, indexcols, timestart):\n time1 = time.time()\n print (\"%s Enter %.3f\" % (setname, time1 - timestart))\n\n initialCash = result_para_dic['initialCash']\n positionRatio = result_para_dic['positionRatio']\n remove_polar_switch = result_para_dic['remove_polar_switch']\n remove_polar_rate = result_para_dic['remove_polar_rate']\n\n symbollist = symbolinfo.getSymbolList()\n symbolDomainDic = symbolinfo.getSymbolDomainDic()\n result = pd.DataFrame()\n last_domain_utc = None\n # print para['Setname']\n for symbol in symbollist:\n if last_domain_utc:\n # 如果上一个合约的最后一次平仓时间超过其主力合约结束时间,则要修改本次合约的开始时间为上一次平仓后\n symbol_domain_start = last_domain_utc\n symbolDomainDic[symbol][0] = last_domain_utc\n else:\n symbol_domain_start = symbolDomainDic[symbol][0]\n symbol_domain_end = symbolDomainDic[symbol][1]\n rawdata = rawdataDic[symbol]\n r = HullRsiWin(symbolinfo, rawdata, para)\n r['symbol'] = symbol # 增加主力全约列\n r = r.loc[(r['openutc'] >= symbol_domain_start) & (r['openutc'] <= symbol_domain_end)]\n last_domain_utc = None\n if r.shape[0] > 0:\n last_close_utc = r.iloc[-1]['closeutc']\n if last_close_utc > symbol_domain_end:\n # 如果本合约最后一次平仓时间超过其主力合约结束时间,则要修改本合约的主力结束时间为平仓后\n symbolDomainDic[symbol][1] = last_close_utc\n last_domain_utc = last_close_utc\n result = pd.concat([result, r])\n result.reset_index(drop=True, inplace=True)\n\n # 去极值操作\n if remove_polar_switch:\n result = RS.opr_result_remove_polar(result, remove_polar_rate)\n\n # 全部操作结束后,要根据修改完的主力时间重新接出一份主连来计算dailyK\n domain_bar = pd.DataFrame()\n for symbol in symbollist[:-1]:\n symbol_domain_start = symbolDomainDic[symbol][0]\n symbol_domain_end = symbolDomainDic[symbol][1]\n rbar = rawdataDic[symbol]\n bars = rbar.loc[(rbar['utc_time'] >= symbol_domain_start) & (rbar['utc_endtime'] < symbol_domain_end)]\n domain_bar = pd.concat([domain_bar, bars])\n # 最后一个合约只截前不截后\n symbol = symbollist[-1]\n symbol_domain_start = symbolDomainDic[symbol][0]\n rbar = rawdataDic[symbol]\n bars = rbar.loc[rbar['utc_time'] >= symbol_domain_start]\n domain_bar = pd.concat([domain_bar, bars])\n\n dailyK = DC.generatDailyClose(domain_bar)\n result['commission_fee'], result['per earn'], result['own cash'], result['hands'] = RS.calcResult(result,\n symbolinfo,\n initialCash,\n positionRatio)\n bt_folder = \"%s %d backtesting\\\\\" % (symbolinfo.domain_symbol, K_MIN)\n\n result.to_csv(bt_folder + strategyName + ' ' + symbolinfo.domain_symbol + str(K_MIN) + ' ' + setname + ' result.csv', index=False)\n dR = RS.dailyReturn(symbolinfo, result, dailyK, initialCash) # 计算生成每日结果\n dR.calDailyResult()\n dR.dailyClose.to_csv((bt_folder + strategyName + ' ' + symbolinfo.domain_symbol + str(K_MIN) + ' ' + setname + ' dailyresult.csv'))\n results = RS.getStatisticsResult(result, False, indexcols, dR.dailyClose)\n del result\n print results\n return [setname] + results # 在这里附上setname\n\n\ndef getParallelResult(strategyParameter, resultpath, parasetlist, paranum, indexcols):\n strategyName = strategyParameter['strategyName']\n exchange_id = strategyParameter['exchange_id']\n sec_id = strategyParameter['sec_id']\n K_MIN = strategyParameter['K_MIN']\n startdate = strategyParameter['startdate']\n enddate = strategyParameter['enddate']\n domain_symbol = '.'.join([exchange_id, sec_id])\n result_para_dic = strategyParameter['result_para_dic']\n # ======================数据准备==============================================\n # 取合约信息\n symbolInfo = DC.SymbolInfo(domain_symbol, startdate, enddate)\n # 取跨合约数据\n # contractswaplist = DC.getContractSwaplist(domain_symbol)\n # swaplist = np.array(contractswaplist.swaputc)\n\n # 取K线数据\n # rawdata = DC.getBarData(symbol, K_MIN, startdate + ' 00:00:00', enddate + ' 23:59:59').reset_index(drop=True)\n rawdataDic = DC.getBarBySymbolList(domain_symbol, symbolInfo.getSymbolList(), K_MIN, startdate, enddate)\n # dailyK数据改到getResult中根据结果来重新取\n # dailyK = DC.generatDailyClose(rawdata) #生成按日的K线\n foldername = ' '.join([strategyName, exchange_id, sec_id, str(K_MIN)])\n try:\n os.chdir(resultpath)\n os.mkdir(foldername)\n except:\n print (\"%s folder already exsist!\" % foldername)\n os.chdir(foldername)\n timestart = time.time()\n # 多进程优化,启动一个对应CPU核心数量的进程池\n pool = multiprocessing.Pool(multiprocessing.cpu_count() - 1)\n l = []\n resultlist = pd.DataFrame(columns=['Setname'] + indexcols)\n for i in range(0, paranum):\n setname = parasetlist.ix[i, 'Setname']\n n1 = parasetlist.ix[i, 'N1']\n m1 = parasetlist.ix[i, 'M1']\n m2 = parasetlist.ix[i, 'M2']\n n = parasetlist.ix[i, 'N']\n ma_n = parasetlist.ix[i, 'MaN']\n #rsi_up = parasetlist.ix[i, 'RSI1_UP']\n #rsi_down = parasetlist.ix[i, 'RSI1_DOWN']\n paraset = {\n 'Setname': setname,\n 'N1': n1,\n 'M1': m1,\n 'M2': m2,\n 'N': n,\n #'RSI1_UP': rsi_up,\n #'RSI1_DOWN': rsi_down\n 'MaN': ma_n\n }\n #l.append(getResult(strategyName, symbolInfo, K_MIN, setname, rawdataDic, paraset, result_para_dic, indexcols, timestart))\n l.append(pool.apply_async(getResult, (strategyName, symbolInfo, K_MIN, setname, rawdataDic, paraset, result_para_dic, indexcols,timestart)))\n pool.close()\n pool.join()\n timeend = time.time()\n print (\"total time %.2f\" % (timeend - timestart))\n # 显示结果\n i = 0\n for res in l:\n resultlist.loc[i] = res.get()\n i += 1\n # print resultlist\n finalresults = (\"%s %s %d finalresults.csv\" % (strategyName, domain_symbol, K_MIN))\n resultlist.to_csv(finalresults)\n return resultlist\n\n\nif __name__ == '__main__':\n # ====================参数和文件夹设置======================================\n # 文件路径\n upperpath = DC.getUpperPath(Parameter.folderLevel)\n resultpath = upperpath + Parameter.resultFolderName\n\n # indexcols\n indexcols = Parameter.ResultIndexDic\n\n # 参数设置\n strategyParameterSet = []\n if not Parameter.symbol_KMIN_opt_swtich:\n # 单品种单周期模式\n paradic = {\n 'strategyName': Parameter.strategyName,\n 'exchange_id': Parameter.exchange_id,\n 'sec_id': Parameter.sec_id,\n 'K_MIN': Parameter.K_MIN,\n 'startdate': Parameter.startdate,\n 'enddate': Parameter.enddate,\n 'result_para_dic': Parameter.result_para_dic\n }\n strategyParameterSet.append(paradic)\n else:\n # 多品种多周期模式\n symbolset = pd.read_excel(resultpath + Parameter.symbol_KMIN_set_filename)\n symbolsetNum = symbolset.shape[0]\n for i in range(symbolsetNum):\n exchangeid = symbolset.ix[i, 'exchange_id']\n secid = symbolset.ix[i, 'sec_id']\n strategyParameterSet.append({\n 'strategyName': symbolset.ix[i, 'strategyName'],\n 'exchange_id': exchangeid,\n 'sec_id': secid,\n 'K_MIN': int(symbolset.ix[i, 'K_MIN']),\n 'startdate': symbolset.ix[i, 'startdate'],\n 'enddate': symbolset.ix[i, 'enddate'],\n 'result_para_dic': Parameter.result_para_dic,\n 'para_N': symbolset.ix[i, 'N'],\n 'para_N1': symbolset.ix[i, 'N1'],\n 'para_M1': symbolset.ix[i, 'M1'],\n 'para_M2': symbolset.ix[i, 'M2'],\n 'para_MaN': symbolset.ix[i, 'MaN']\n }\n )\n allsymbolresult_cols = ['Setname'] + indexcols + ['strategyName', 'exchange_id', 'sec_id', 'K_MIN']\n allsymbolresult = pd.DataFrame(columns=allsymbolresult_cols)\n for strategyParameter in strategyParameterSet:\n strategy_name = strategyParameter['strategyName']\n exchange_id = strategyParameter['exchange_id']\n sec_id = strategyParameter['sec_id']\n bar_type = strategyParameter['K_MIN']\n foldername = ' '.join([strategy_name, exchange_id, sec_id, str(bar_type)])\n try:\n os.chdir(resultpath)\n os.mkdir(foldername)\n except:\n print (\"%s folder already exsist!\" % foldername)\n finally:\n os.chdir(foldername)\n try:\n os.mkdir(\"%s.%s %d backtesting\" % (exchange_id, sec_id, bar_type))\n except:\n pass\n\n try:\n # 取参数集\n parasetlist = pd.read_csv(\"%s %s %d %s\" % (exchange_id, sec_id, bar_type, Parameter.parasetname))\n except:\n if not Parameter.symbol_KMIN_opt_swtich:\n para_list_dic = None # 单品种模式使用默认参数\n else:\n # 如果没有,则直接生成\n para_list_dic = {\n 'N':strategyParameter['para_N'],\n 'N1':strategyParameter['para_N1'],\n 'M1':strategyParameter['para_M1'],\n 'M2': strategyParameter['para_M2'],\n 'MaN':strategyParameter['para_MaN']\n }\n parasetlist = Parameter.generat_para_file(para_list_dic)\n parasetlist.to_csv(\"%s %s %d %s\" % (exchange_id, sec_id, bar_type, Parameter.parasetname))\n paranum = parasetlist.shape[0]\n\n r = getParallelResult(strategyParameter, resultpath, parasetlist, paranum, indexcols)\n r['strategyName'] = strategyParameter['strategyName']\n r['exchange_id'] = strategyParameter['exchange_id']\n r['sec_id'] = strategyParameter['sec_id']\n r['K_MIN'] = strategyParameter['K_MIN']\n allsymbolresult = pd.concat([allsymbolresult, r])\n allsymbolresult.reset_index(drop=False, inplace=True)\n os.chdir(resultpath)\n allsymbolresult.to_csv(Parameter.strategyName + \"_symbol_KMIN_results.csv\")\n"
},
{
"alpha_fraction": 0.6111017465591431,
"alphanum_fraction": 0.6231492161750793,
"avg_line_length": 44.08375549316406,
"blob_id": "d721e6bd67f1a1cfaf6d5a160afe14b25e682774",
"content_id": "135416fc77acc1f7729ccff05e1626fae2ba89d9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 18659,
"license_type": "no_license",
"max_line_length": 161,
"num_lines": 394,
"path": "/HullRsiWin/HullRsiWin_Function.py",
"repo_name": "smartgang/RsiWin",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nimport pandas as pd\nimport DATA_CONSTANTS as DC\nimport HullRsiWin_Parameter as Parameter\nimport os\nimport numpy as np\nimport ResultStatistics as RS\nfrom datetime import datetime\nimport time\nimport matplotlib.pyplot as plt\n\ndef calc_single_backtest_final_result(domain_symbol, bar_type):\n \"\"\"\n 计算单个品种回测结果的汇总finalresult文件\n :param domain_symbol: 主力合约编号\n :param bar_type: 周期\n :return:\n \"\"\"\n upperpath = DC.getUpperPath(Parameter.folderLevel)\n resultpath = upperpath + Parameter.resultFolderName\n symbol_folder = domain_symbol.replace('.', ' ') + ' ' + str(bar_type)\n os.chdir(resultpath + symbol_folder)\n bt_folder = \"%s %d backtesting\\\\\" % (domain_symbol, bar_type)\n parasetlist = pd.read_csv(\"%s %d %s\" % (domain_symbol.replace('.', ' '), bar_type, Parameter.parasetname))['Setname'].tolist()\n indexcols = Parameter.ResultIndexDic\n strategy_name = Parameter.strategyName\n resultlist = pd.DataFrame(columns=['Setname'] + indexcols)\n i = 0\n for setname in parasetlist:\n print setname\n result = pd.read_csv((bt_folder + strategy_name + ' ' + domain_symbol + str(bar_type) + ' ' + setname + ' result.csv'))\n dailyClose= pd.read_csv((bt_folder + strategy_name + ' ' + domain_symbol + str(bar_type) + ' ' + setname + ' dailyresult.csv'))\n results = RS.getStatisticsResult(result, False, indexcols, dailyClose)\n resultlist.loc[i] = [setname]+results #在这里附上setname\n i += 1\n finalresults = (\"%s %s %d finalresults.csv\" % (strategy_name, domain_symbol, bar_type))\n resultlist.to_csv(finalresults)\n\n\ndef calc_singal_close_final_result(domain_symbol, bar_type, sl_type, folder_name):\n \"\"\"\n 计算单个品种单个止损结果的汇总finalresult文件\n :param domain_symbol: 主力合约编号\n :param bar_type: 周期\n :param sl_type: 止损类型 'DSL', 'OWNL', 'FRSL', 'ATR', 'GOWNL'\n :param folder_name: 结果文件存放文件夹名\n :return:\n \"\"\"\n upperpath = DC.getUpperPath(Parameter.folderLevel)\n resultpath = upperpath + Parameter.resultFolderName\n symbol_folder = domain_symbol.replace('.', ' ') + ' ' + str(bar_type)\n os.chdir(resultpath + symbol_folder)\n bt_folder = \"%s %d backtesting\\\\\" % (domain_symbol, bar_type)\n parasetlist = pd.read_csv(resultpath + Parameter.parasetname)['Setname'].tolist()\n strategy_name = Parameter.strategyName\n indexcols = Parameter.ResultIndexDic\n file_name_suffix = '%s_by_tick.csv' % sl_type\n new_indexcols = []\n for i in indexcols:\n new_indexcols.append('new_' + i)\n resultdf = pd.DataFrame(columns=['setname', 'sl_target', 'worknum'] + indexcols + new_indexcols)\n i = 0\n for setname in parasetlist:\n print setname\n worknum = 0\n olddailydf = pd.read_csv(bt_folder + strategy_name + ' ' + domain_symbol + str(bar_type) + ' ' + setname + ' dailyresult.csv',\n index_col='date')\n opr_file_name = \"\\\\%s %s%d %s result%s\" % (strategy_name, domain_symbol, bar_type, setname, file_name_suffix)\n oprdf = pd.read_csv(folder_name + opr_file_name)\n oldr = RS.getStatisticsResult(oprdf, False, indexcols, olddailydf)\n opr_dialy_k_file_name = \"\\\\%s %s%d %s dailyresult%s\" % (strategy_name, domain_symbol, bar_type, setname, file_name_suffix)\n dailyClose = pd.read_csv(folder_name + opr_dialy_k_file_name)\n newr = RS.getStatisticsResult(oprdf, True, indexcols, dailyClose)\n resultdf.loc[i] = [setname, folder_name, worknum] + oldr + newr\n i += 1\n resultdf.to_csv(\"%s\\\\%s %s%d finalresult_%s.csv\" % (folder_name, strategy_name, domain_symbol, bar_type, folder_name))\n\n\ndef re_concat_close_all_final_result(domain_symbol, bar_type, sl_type):\n \"\"\"\n 重新汇总某一止损类型所有参数的final_result, 止损的参数自动从Parameter中读\n :param domain_symbol: 主力合约编号\n :param bar_type: 周期\n :param sl_type: 止损类型 'DSL', 'OWNL', 'FRSL', 'ATR', 'GOWNL'\n :return:\n \"\"\"\n upperpath = DC.getUpperPath(Parameter.folderLevel)\n resultpath = upperpath + Parameter.resultFolderName\n symbol_folder = domain_symbol.replace('.', ' ') + ' ' + str(bar_type)\n os.chdir(resultpath + symbol_folder)\n close_para_name_list = []\n if sl_type == 'DSL':\n folder_prefix = 'DynamicStopLoss'\n final_result_file_suffix = 'dsl'\n dsl_target_list = Parameter.dsl_target_list_close\n for dsl_target in dsl_target_list:\n close_para_name_list.append(str(dsl_target))\n elif sl_type == 'OWNL':\n folder_prefix = 'OnceWinNoLoss'\n final_result_file_suffix = 'ownl'\n ownl_protect_list = Parameter.ownl_protect_list_close\n ownl_floor_list = Parameter.ownl_floor_list_close\n for ownl_protect in ownl_protect_list:\n for ownl_floor in ownl_floor_list:\n close_para_name_list.append(\"%.3f_%d\" % (ownl_protect, ownl_floor))\n elif sl_type == 'FRSL':\n folder_prefix = 'FixRateStopLoss'\n final_result_file_suffix = 'frsl'\n frsl_target_list = Parameter.frsl_target_list_close\n for frsl_target in frsl_target_list:\n close_para_name_list.append(str(frsl_target))\n elif sl_type == 'ATR':\n folder_prefix = 'ATRSL'\n final_result_file_suffix = 'atrsl'\n atr_pendant_n_list = Parameter.atr_pendant_n_list_close\n atr_pendan_rate_list = Parameter.atr_pendant_rate_list_close\n atr_yoyo_n_list = Parameter.atr_yoyo_n_list_close\n atr_yoyo_rate_list = Parameter.atr_yoyo_rate_list_close\n for atr_pendant_n in atr_pendant_n_list:\n for atr_pendant_rate in atr_pendan_rate_list:\n for atr_yoyo_n in atr_yoyo_n_list:\n for atr_yoyo_rate in atr_yoyo_rate_list:\n close_para_name_list.append('%d_%.1f_%d_%.1f' % (\n atr_pendant_n, atr_pendant_rate, atr_yoyo_n, atr_yoyo_rate))\n elif sl_type == 'GOWNL':\n folder_prefix = 'GOWNL'\n final_result_file_suffix = 'gownl'\n gownl_protect_list = Parameter.gownl_protect_list_close\n gownl_floor_list = Parameter.gownl_floor_list_close\n gownl_step_list = Parameter.gownl_step_list_close\n for gownl_protect in gownl_protect_list:\n for gownl_floor in gownl_floor_list:\n for gownl_step in gownl_step_list:\n close_para_name_list.append('%.3f_%.1f_%.1f' % (gownl_protect, gownl_floor, gownl_step))\n else:\n print \"close name error\"\n return\n final_result_name_0 = \"%s %s%d finalresult_%s%s.csv\" % (\n Parameter.strategyName, domain_symbol, bar_type, final_result_file_suffix, close_para_name_list[0])\n final_result_file = pd.read_csv(\"%s%s\\\\%s\" % (folder_prefix, close_para_name_list[0], final_result_name_0))\n for para_name in close_para_name_list[1:]:\n final_result_name = \"%s %s%d finalresult_%s%s.csv\" % (\n Parameter.strategyName, domain_symbol, bar_type, final_result_file_suffix, para_name)\n final_result_file = pd.concat([final_result_file, pd.read_csv(\"%s%s\\\\%s\" % (folder_prefix, para_name, final_result_name))])\n\n final_result_file.to_csv(\"%s %s%d finalresult_%s_reconcat.csv\" % (\n Parameter.strategyName, domain_symbol, bar_type, final_result_file_suffix))\n\n\ndef re_concat_multi_symbol_final_result():\n \"\"\"\n 重新汇总多品种回测的final_result结果,自动从symbol_KMIN_set.xlsx文件读取品种列表\n :return:\n \"\"\"\n upperpath = DC.getUpperPath(Parameter.folderLevel)\n resultpath = upperpath + Parameter.resultFolderName\n os.chdir(resultpath)\n multi_symbol_df = pd.read_excel('%s_symbol_KMIN_set.xlsx' % Parameter.strategyName)\n all_final_result_list = []\n for n, row in multi_symbol_df.iterrows():\n strategy_name = row['strategyName']\n exchange_id = row['exchange_id']\n sec_id = row['sec_id']\n bar_type = row['K_MIN']\n symbol_folder_name = \"%s %s %s %d\\\\\" % (strategy_name, exchange_id, sec_id, bar_type)\n bt_folder = \"%s.%s %d backtesting\\\\\" % (exchange_id, sec_id, bar_type)\n result_file_name = \"%s %s.%s %d finalresults.csv\" % (strategy_name, exchange_id, sec_id, bar_type)\n print result_file_name\n final_result_df = pd.read_csv(symbol_folder_name + result_file_name)\n final_result_df['strategy_name'] = strategy_name\n final_result_df['exchange_id'] = exchange_id\n final_result_df['sec_id'] = sec_id\n final_result_df['ba_type'] = bar_type\n all_final_result_list.append(final_result_df)\n\n multi_symbol_result_df = pd.concat(all_final_result_list)\n multi_symbol_result_df.to_csv('%s_symbol_KMIN_set_result.csv' % Parameter.strategyName)\n\n\n\ndef calResultByPeriod():\n '''\n 按时间分段统计结果:\n 1.设定开始和结束时间\n 2.选择时间周期\n 3.设定文件夹、买卖操作文件名、日结果文件名和要生成的新文件名\n :return:\n '''\n #设定开始和结束时间\n startdate = '2011-04-01'\n enddate = '2018-07-01'\n\n #2.选择时间周期\n #freq='YS' #按年统计\n #freq='2QS' #按半年统计\n #freq='QS' #按季度统计\n freq='MS' #按月统计,如需多个月,可以加上数据,比如2个月:2MS\n\n #3.设文件和文件夹状态\n filedir='D:\\\\002 MakeLive\\myquant\\HopeWin\\Results\\HopeMacdMaWin DCE J 3600\\dsl_-0.022ownl_0.012\\ForwardOprAnalyze\\\\' #文件所在文件夹\n oprfilename = 'HopeMacdMaWin DCE.J3600_Rank3_win9_oprResult.csv' #买卖操作文件名\n dailyResultFileName = 'HopeMacdMaWin DCE.J3600_Rank3_win9_oprdailyResult.csv' #日结果文件名\n newFileName = 'HopeMacdMaWin DCE.J3600_Rank3_win9_result_by_Period_M.csv' #要生成的新文件名\n os.chdir(filedir)\n oprdf = pd.read_csv(oprfilename)\n dailyResultdf = pd.read_csv(dailyResultFileName)\n\n oprdfcols = oprdf.columns.tolist()\n if 'new_closeprice' in oprdfcols:\n newFlag = True\n else:\n newFlag = False\n\n monthlist = [datetime.strftime(x, '%Y-%m-%d %H:%M:%S') for x in list(pd.date_range(start=startdate, end=enddate, freq=freq, normalize=True, closed='right'))]\n\n if not startdate in monthlist[0]:\n monthlist.insert(0,startdate+\" 00:00:00\")\n if not enddate in monthlist[-1]:\n monthlist.append(enddate+\" 23:59:59\")\n else:\n monthlist[-1]=enddate+\" 23:59:59\"\n rlist=[]\n for i in range(1,len(monthlist)):\n starttime=monthlist[i-1]\n endtime = monthlist[i]\n startutc = float(time.mktime(time.strptime(starttime, \"%Y-%m-%d %H:%M:%S\")))\n endutc = float(time.mktime(time.strptime(endtime, \"%Y-%m-%d %H:%M:%S\")))\n\n resultdata = oprdf.loc[(oprdf['openutc'] >= startutc) & (oprdf['openutc'] < endutc)]\n dailydata = dailyResultdf.loc[(dailyResultdf['utc_time'] >= startutc) & (dailyResultdf['utc_time'] < endutc)]\n resultdata.reset_index(drop=True,inplace=True)\n if resultdata.shape[0]>0:\n rlist.append([starttime,endtime]+RS.getStatisticsResult(resultdata, newFlag, Parameter.ResultIndexDic, dailydata))\n else:\n rlist.append([0]*len(Parameter.ResultIndexDic))\n rdf = pd.DataFrame(rlist,columns=['StartTime','EndTime']+Parameter.ResultIndexDic)\n rdf.to_csv(newFileName)\n\n\ndef set_generator():\n setlist = []\n i = 0\n for n1 in range(15, 36, 5):\n for m1 in range(6, 17, 4):\n # for m2 in range(3, 15, 3):\n for m2 in [3, 6, 9]:\n # for n in range(3, 16, 3):\n for n in [6, 10, 14, 18]:\n # for ma_n in range(20, 51, 10):\n for ma_n in [20, 30, 40, 50]:\n setname = \"Set%d N1_%d M1_%d M2_%d N_%d MaN_%d\" % (i, n1, m1, m2, n, ma_n)\n l = [setname, n1, m1, m2, n, ma_n]\n setlist.append(l)\n i += 1\n\n setpd = pd.DataFrame(setlist, columns=['Setname', 'N1', 'M1', 'M2', 'N', 'MaN'])\n # setpd['RSI1_UP'] = 70\n # setpd['RSI1_DOWN'] = 30\n\n upperpath = DC.getUpperPath(Parameter.folderLevel)\n resultpath = upperpath + Parameter.resultFolderName\n setpd.to_csv(resultpath + Parameter.parasetname)\n\n\ndef stat_multi_symbol_result():\n upperpath = DC.getUpperPath(Parameter.folderLevel)\n resultpath = upperpath + Parameter.resultFolderName\n os.chdir(resultpath)\n multi_symbol_df = pd.read_excel('HullRsiWin_symbol_KMIN_set.xlsx')\n for n, row in multi_symbol_df.iterrows():\n strategy_name = row['strategyName']\n exchange_id = row['exchange_id']\n sec_id = row['sec_id']\n bar_type = row['K_MIN']\n folder_name = \"%s %s %s %d\\\\\" % (strategy_name, exchange_id, sec_id, bar_type)\n result_file_name = \"%s %s.%s %d finalresults.csv\" % (strategy_name, exchange_id, sec_id, bar_type)\n print result_file_name\n result_df = pd.read_csv(folder_name + result_file_name)\n multi_symbol_df.ix[n, 'OprTimes'] = result_df['OprTimes'].mean()\n multi_symbol_df.ix[n, 'Annual_max'] = result_df['Annual'].max()\n multi_symbol_df.ix[n, 'Annual_avg'] = result_df['Annual'].mean()\n multi_symbol_df.ix[n, 'EndCash_avg'] = result_df['EndCash'].mean()\n multi_symbol_df.ix[n, 'EndCash_max'] = result_df['EndCash'].max()\n multi_symbol_df.ix[n, 'own_cash_max_max'] = result_df['max_own_cash'].max()\n multi_symbol_df.ix[n, 'own_cash_max_avg'] = result_df['max_own_cash'].mean()\n multi_symbol_df.ix[n, 'Sharpe_max'] = result_df['Sharpe'].max()\n multi_symbol_df.ix[n, 'SR_avg'] = result_df['SR'].mean()\n multi_symbol_df.ix[n, 'DR_avg'] = result_df['DrawBack'].mean()\n multi_symbol_df.ix[n, 'SingleEarn_avg'] = result_df['MaxSingleEarnRate'].mean()\n multi_symbol_df.ix[n, 'SingleLoss_avg'] = result_df['MaxSingleLossRate'].mean()\n multi_symbol_df.ix[n, 'ProfitLossRate_avg'] = result_df['ProfitLossRate'].mean()\n multi_symbol_df.to_csv('HullRsiWin_symbol_KMIN_set2_result.csv')\n\n\ndef add_max_period_cash_to_finalresult():\n upperpath = DC.getUpperPath(Parameter.folderLevel)\n resultpath = upperpath + Parameter.resultFolderName\n os.chdir(resultpath)\n para_set_list = pd.read_csv('ParameterSet_HullRsi.csv')['Setname'].tolist()\n multi_symbol_df = pd.read_excel('HullRsiWin_symbol_KMIN_set.xlsx')\n for n, row in multi_symbol_df.iterrows():\n strategy_name = row['strategyName']\n exchange_id = row['exchange_id']\n sec_id = row['sec_id']\n bar_type = row['K_MIN']\n folder_name = \"%s %s %s %d\\\\\" % (strategy_name, exchange_id, sec_id, bar_type)\n result_file_name = \"%s %s.%s %d finalresults.csv\" % (strategy_name, exchange_id, sec_id, bar_type)\n # print result_file_name\n result_df = pd.read_csv(folder_name + result_file_name, index_col='Setname')\n for setname in para_set_list:\n set_file_name = \"%s %s.%s%d %s result.csv\" % (strategy_name, exchange_id, sec_id, bar_type, setname)\n print set_file_name\n set_result = pd.read_csv(folder_name + set_file_name)\n max_own_cash = set_result['own cash'].max()\n result_df.ix[setname, 'max_own_cash'] = max_own_cash\n result_df.to_csv(folder_name + result_file_name)\n pass\n\n\ndef plot_parameter_result_pic():\n \"\"\"绘制finalresult结果中参数对应的end cash和max own cash的分布柱状图\"\"\"\n upperpath = DC.getUpperPath(Parameter.folderLevel)\n resultpath = upperpath + Parameter.resultFolderName\n os.chdir(resultpath)\n symbol_sellected = pd.read_excel(\"multi_symbol_1st_xu.xlsx\")\n for n , rows in symbol_sellected.iterrows():\n fig = plt.figure(figsize=(6, 12))\n exchange = rows['exchange']\n sec = rows['sec']\n bar_type = rows['bar_type']\n folder_name = \"%s %s %s %d\\\\\" % (Parameter.strategyName, exchange, sec, bar_type)\n final_result_file = pd.read_csv(folder_name + \"%s %s.%s %d finalresults.csv\" % (Parameter.strategyName, exchange, sec, bar_type))\n para_file = pd.read_csv(folder_name + \"%s %s %d ParameterSet_HullRsi.csv\" % (exchange, sec, bar_type))\n para_name_list = ['N', 'N1', 'M1', 'M2', 'MaN']\n for i in range(len(para_name_list)):\n para_name = para_name_list[i]\n final_result_file[para_name_list] = para_file[para_name_list]\n grouped = final_result_file.groupby(para_name)\n end_cash_grouped = grouped['EndCash'].mean()\n p = plt.subplot(len(para_name_list), 1, i+1)\n p.set_title(para_name)\n p.bar(end_cash_grouped.index.tolist(), end_cash_grouped.values)\n print end_cash_grouped\n fig.savefig('%s %s %s %d_para_distribute.png' % (Parameter.strategyName, exchange, sec, bar_type), dip=500)\n \"\"\"\n for i in range(1, len(test_data) + 2):\n p = plt.subplot(2, 5, i)\n p.set_title(str(i))\n p.bar([1, 2, 3, 4], test_data_2)\n\n for i in range(1, len(test_data) + 2):\n p = plt.subplot(2, 5, i + 5)\n p.set_title(str(i))\n p.bar([1, 2, 3, 4], test_data_2)\n \"\"\"\n\nif __name__ == \"__main__\":\n \"\"\"\n 计算单个品种回测结果的汇总finalresult文件\n :param domain_symbol: 主力合约编号\n :param bar_type: 周期\n \"\"\"\n # calc_single_backtest_final_result(domain_symbol='SHFE.RB', bar_type=3600)\n\n \"\"\"\n 计算单个品种单个止损结果的汇总finalresult文件\n :param domain_symbol: 主力合约编号\n :param bar_type: 周期\n :param sl_type: 止损类型 'DSL', 'OWNL', 'FRSL', 'ATR', 'GOWNL'\n :param folder_name: 结果文件存放文件夹名\n \"\"\"\n # calc_singal_close_final_result(domain_symbol='SHFE.RB', bar_type=3600, sl_type='DSL', folder_name=\"DynamicStopLoss-0.018\")\n\n \"\"\"\n 重新汇总某一止损类型所有参数的final_result, 止损的参数自动从Parameter中读\n :param domain_symbol: 主力合约编号\n :param bar_type: 周期\n :param sl_type: 止损类型 'DSL', 'OWNL', 'FRSL', 'ATR', 'GOWNL'\n \"\"\"\n # re_concat_close_all_final_result(domain_symbol='SHFE.RB', bar_type=3600, sl_type='DSL')\n\n \"\"\"\n 重新汇总多品种回测的final_result结果,自动从symbol_KMIN_set.xlsx文件读取品种列表\n \"\"\"\n # re_concat_multi_symbol_final_result()\n\n \"\"\"\n 分时间段统计结果,需要到函数中修改相关参数\n \"\"\"\n # calResultByPeriod()\n\n \"\"\"绘制finalresult结果中参数对应的end cash分布柱状图\"\"\"\n #plot_parameter_result_pic()\n pass\n"
},
{
"alpha_fraction": 0.5830026268959045,
"alphanum_fraction": 0.6352513432502747,
"avg_line_length": 25.068965911865234,
"blob_id": "bd383aab0ed47bff7a2cb22583610fd0b2cc02ee",
"content_id": "fdacf5aa449771d3ca6a658907bd9e0117e0f220",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3704,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 116,
"path": "/HullRsiTunenlWin/HullRsiTunnelWin_Parameter.py",
"repo_name": "smartgang/RsiWin",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n策略参数设置\n\"\"\"\n# 参数设置\nstrategyName = 'HullRsiTunnelWin'\nexchange_id = 'SHFE'\nsec_id = 'RB'\nK_MIN = 3600\nstartdate = '2010-01-01'\nenddate = '2018-07-01'\nparasetname = 'ParameterSet_HullRsiTunnel.csv'\nresult_para_dic = { # 结果计算相关参数\n 'positionRatio': 0.5, # 持仓比例\n 'initialCash': 2000000, # 起始资金\n 'remove_polar_switch': False,\n 'remove_polaar_rate': 0.01\n}\n\n# =============止损控制开关===================\nprogress_close = False\ncalcDsl_close = False\ncalcOwnl_close = False\ncalcFrsl_close = False\ncalcAtrsl_close = True\ncalcMultiSLT_close = False\ncalcDslOwnl_close = False\n# dsl参数\ndslStep_close = -0.002\ndslTargetStart_close = -0.018\ndslTargetEnd_close = -0.020\n# ownl参数\nownlStep_close = 0.001\nownlTargetStart_close = 0.008\nownltargetEnd_close = 0.010\nnolossThreshhold_close = 3\n# frsl参数\nfrslStep_close = -0.001\nfrslTargetStart_close = -0.010\nfrslTragetEnd_close = -0.011\n# atr止损参数\natr_pendant_n_list = [5, 8]\natr_pendant_rate_list = [1.0, 1.5, 2.0]\natr_yoyo_n_list = [8, 16, 30]\natr_yoyo_rate_list = [1, 1.2, 1.5]\n\n# =============推进控制开关===================\n# nextMonthName='18-05'\nforwardWinStart = 1\nforwardWinEnd = 12\n\n# 止损类型开关\nmultiSTL_forward = True # 多止损混合推进开关(忽略common模式)\ncommon_forward = False # 普通回测结果推进\ncalcDsl_forward = True\ncalcOwnl_forward = True\ncalsFrsl_forward = False\ncalcDslOwnl_forward = False\n# dsl参数\ndslStep_forward = -0.002\ndslTargetStart_forward = -0.018\ndslTargetEnd_forward = -0.020\n# ownl参数\nownlStep_forward = 0.001\nownlTargetStart_forward = 0.008\nownltargetEnd_forward = 0.010\n# frsl参数\nfrslStep_forward = -0.001\nfrslTargetStart_forward = -0.010\nfrslTragetEnd_forward = -0.011\n# dsl_ownl set:dsl在前,ownl在后\ndsl_ownl_set = [[-0.020, 0.009], [-0.018, 0.009]]\n\n# ==================每月参数计算=====================\n# newmonth='2018-05'#要生成参数的新月份\nmonth_n = 7 # n+x的n值,即往前推多少个月\n\n# =================结果指标开关====================\nResultIndexDic = [\n \"OprTimes\", # 操作次数\n \"LongOprTimes\", # 多操作次数\n \"ShortOprTimes\", # 空操作次数\n \"EndCash\", # 最终资金\n \"MaxOwnCash\", # 最大期间资金\n \"LongOprRate\", # 多操作占比\n \"ShortOprRate\", # 空操作占比\n \"Annual\", # 年化收益\n \"Sharpe\", # 夏普\n \"SR\", # 成功率\n \"LongSR\", # 多操作成功率\n \"ShortSR\", # 空操作成功率\n \"DrawBack\", # 资金最大回撤\n \"MaxSingleEarnRate\", # 单次最大盈利率\n \"MaxSingleLossRate\", # 单次最大亏损率\n \"ProfitLossRate\", # 盈亏比\n \"LongProfitLossRate\", # 多操作盈亏比\n \"ShoartProfitLossRate\", # 空操作盈亏比\n \"MaxSuccessiveEarn\", # 最大连续盈利次数\n \"MaxSuccessiveLoss\", # 最大连续亏损次数\n \"AvgSuccessiveEarn\", # 平均连续盈利次数\n \"AveSuccessiveLoss\" # 平均连续亏损次数'\n]\n# ===============多品种多周期优化参数=============================\n# 多品种多周期优化开关,打开后代码会从下面标识的文件中导入参数\nsymbol_KMIN_opt_swtich = False\n\n# 1.品种和周期组合文件\nsymbol_KMIN_set_filename = strategyName + '_symbol_KMIN_set.xlsx'\n# 2.第一步的结果中挑出满足要求的项,做成双止损组合文件\nstoploss_set_filename = strategyName + '_stoploss_set.xlsx'\n# 3.从第二步的结果中挑出满足要求的项,做推进\nforward_set_filename = strategyName + '_forward_set.xlsx'\n\n# ====================系统参数==================================\nfolderLevel = 2\nresultFolderName = '\\\\Results\\\\'\n"
},
{
"alpha_fraction": 0.5431644916534424,
"alphanum_fraction": 0.5825163125991821,
"avg_line_length": 30.930435180664062,
"blob_id": "903c9d5d72af73e78d825b76108bc566f3df23b4",
"content_id": "aaf53d7150eec1bb9263cf4d2f3ef9add5ffa7eb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8910,
"license_type": "no_license",
"max_line_length": 159,
"num_lines": 230,
"path": "/HullRsiWin/HullRsiWin_Parameter.py",
"repo_name": "smartgang/RsiWin",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n策略参数设置\n\"\"\"\n# 参数设置\nstrategyName = 'HullRsiWin'\nexchange_id = 'SHFE'\nsec_id = 'RB'\nK_MIN = 3600\nstartdate = '2010-01-01'\nenddate = '2018-07-01'\nparasetname = 'ParameterSet_HullRsi.csv'\nresult_para_dic = { # 结果计算相关参数\n 'positionRatio': 0.3, # 持仓比例\n 'initialCash': 1000000, # 起始资金\n 'remove_polar_switch': False,\n 'remove_polar_rate': 0.01\n}\n\nstrategy_para_dic = {\n \"N1\": [15, 20, 25, 30, 35],\n \"M1\": [6, 10, 14],\n \"M2\": [3, 6, 9],\n \"N\": [6, 10, 14, 18],\n \"MaN\": [20, 30, 40, 50]\n}\n# ====================止损控制开关======================\nprogress_close = False # 增量模式开关\ncalc_all_close = False # 一次全部计算模式,该模式不能与混合止损同时打开\ncalcMultiSLT_close = True # 混合止损开关\n\n\ncalcDsl_close = True # dsl动态止损开关\ndsl_target_list_close = [-0.018, -0.02, -0.022]\n\ncalcOwnl_close = True # ownl有赚不亏开关\nownl_protect_list_close = [0.008, 0.009, 0.010, 0.011] # ownl保护触发门限\nownl_floor_list_close = [3] # ownl地板价:止损线(PT数量)\n\ncalcGownl_close = True # gownl递进式有赚不亏开关\ngownl_protect_list_close = [0.007, 0.009, 0.011] # gownl保护触发门限\ngownl_floor_list_close = [-4, -1, 2, 5] # gownl地板价起始点\ngownl_step_list_close = [1, 2] # gownl地板价递进步伐\n\ncalcFrsl_close = False # frsl固定比例止损开关\nfrsl_target_list_close = [-0.01, -0.011, -0.012] # 固定止损比例\n\ncalcAtrsl_close = False # atrsl ATR吊灯和yoyo止损开关\natr_pendant_n_list_close = [5, 8] # 吊灯atr的n值\natr_pendant_rate_list_close = [1.0, 1.5, 2.0] # 吊灯atr的最大回撤止损atr比例\natr_yoyo_n_list_close = [8, 16, 30] # yoyo的atr n值\natr_yoyo_rate_list_close = [1, 1.2, 1.5] # yoyo的止损atr比例\n\n# =============推进控制开关===================\n# nextMonthName='18-05'\nforwardWinStart = 1\nforwardWinEnd = 12\n\n# 止损类型开关\nmultiSTL_forward = True # 多止损混合推进开关(忽略common模式)\ncommon_forward = False # 普通回测结果推进\ncalcDsl_forward = False # dsl动态止损开关\ndsl_target_list_forward = [-0.018, -0.02, -0.022]\n\ncalcOwnl_forward = False # ownl有赚不亏开关\nownl_protect_list_forward = [0.008, 0.009, 0.010, 0,011] # ownl保护触发门限\nownl_floor_list_forward = [3] # ownl地板价:止损线(PT数量)\n\ncalcGownl_forward = True # gownl递进式有赚不亏开关\ngownl_protect_list_forward = [0.007, 0.009, 0.011] # gownl保护触发门限\ngownl_floor_list_forward = [-4, -1, 2, 5] # gownl地板价起始点\ngownl_step_list_forward = [1, 2] # gownl地板价递进步伐\n\ncalcFrsl_forward = False # frsl固定比例止损开关\nfrsl_target_list_forward = [-0.01, -0.011, -0.012] # 固定止损比例\n\ncalcAtrsl_forward = False # atrsl ATR吊灯和yoyo止损开关\natr_pendant_n_list_forward = [5, 8] # 吊灯atr的n值\natr_pendant_rate_list_forward = [1.0, 1.5, 2.0] # 吊灯atr的最大回撤止损atr比例\natr_yoyo_n_list_forward = [8, 16, 30] # yoyo的atr n值\natr_yoyo_rate_list_forward = [1, 1.2, 1.5] # yoyo的止损atr比例\n\nprogress_forward = False # 增量模式开关\ncalcMultiSLT_forward = False # 混合止损开关\n\n# ==================每月参数计算=====================\n# newmonth='2018-05'#要生成参数的新月份\nmonth_n = 7 # n+x的n值,即往前推多少个月\n\n# =================结果指标开关====================\nResultIndexDic = [\n \"OprTimes\", # 操作次数\n \"LongOprTimes\", # 多操作次数\n \"ShortOprTimes\", # 空操作次数\n \"EndCash\", # 最终资金\n \"MaxOwnCash\", # 最大期间资金\n \"LongOprRate\", # 多操作占比\n \"ShortOprRate\", # 空操作占比\n \"Annual\", # 年化收益\n \"Sharpe\", # 夏普\n \"SR\", # 成功率\n \"LongSR\", # 多操作成功率\n \"ShortSR\", # 空操作成功率\n \"DrawBack\", # 资金最大回撤\n \"MaxSingleEarnRate\", # 单次最大盈利率\n \"MaxSingleLossRate\", # 单次最大亏损率\n \"ProfitLossRate\", # 盈亏比\n \"LongProfitLossRate\", # 多操作盈亏比\n \"ShoartProfitLossRate\", # 空操作盈亏比\n \"MaxSuccessiveEarn\", # 最大连续盈利次数\n \"MaxSuccessiveLoss\", # 最大连续亏损次数\n \"AvgSuccessiveEarn\", # 平均连续盈利次数\n \"AveSuccessiveLoss\" # 平均连续亏损次数'\n]\n'''\n#下面这个是指标全量,要加减从里面挑\nResultIndexDic=[\n \"OprTimes\", #操作次数\n \"LongOprTimes\",#多操作次数\n \"ShortOprTimes\",#空操作次数\n \"EndCash\", # 最终资金\n \"LongOprRate\",#多操作占比\n \"ShortOprRate\",#空操作占比\n \"Annual\",#年化收益\n \"Sharpe\",#夏普\n \"SR\",#成功率\n \"LongSR\",#多操作成功率\n \"ShortSR\",#空操作成功率\n \"DrawBack\",#资金最大回撤\n \"MaxSingleEarnRate\",#单次最大盈利率\n \"MaxSingleLossRate\",#单次最大亏损率\n \"ProfitLossRate\",#盈亏比\n \"LongProfitLossRate\",#多操作盈亏比\n \"ShoartProfitLossRate\",#空操作盈亏比\n \"MaxSuccessiveEarn\",#最大连续盈利次数\n \"MaxSuccessiveLoss\",#最大连续亏损次数\n \"AvgSuccessiveEarn\",#平均连续盈利次数\n \"AveSuccessiveLoss\" #平均连续亏损次数'\n]\n'''\n# ===============多品种多周期优化参数=============================\n# 多品种多周期优化开关,打开后代码会从下面标识的文件中导入参数\nsymbol_KMIN_opt_swtich = True\n\n# 1.品种和周期组合文件\nsymbol_KMIN_set_filename = strategyName + '_symbol_KMIN_set.xlsx'\n# 2.第一步的结果中挑出满足要求的项,做成双止损组合文件\nstoploss_set_filename = strategyName + '_stoploss_set.xlsx'\n# 3.从第二步的结果中挑出满足要求的项,做推进\nforward_set_filename = strategyName + '_forward_set.xlsx'\n\n# ====================系统参数==================================\nfolderLevel = 2\nresultFolderName = '\\\\Results\\\\'\n\n\n# ===================== 通用功能函数 =========================================\ndef para_str_to_float(para_str):\n # 功能函数:用于将从多品种多周期文件读取进来的字符串格式的参数列表转换为符点型列表\n para_float_list = []\n if type(para_str) != 'str':\n para_float_list.append(float(para_str))\n else:\n for x in para_str.split(','):\n para_float_list.append(float(x))\n return para_float_list\n\n\ndef para_str_to_int(para_str):\n # 功能函数:用于将从多品种多周期文件读取进来的字符串格式的参数列表转换为符点型列表\n para_float_list = []\n if type(para_str) == 'int':\n para_float_list.append(int(para_str))\n else:\n for x in para_str.split(','):\n para_float_list.append(int(x))\n return para_float_list\n\ndef generat_para_file(para_list_dic = None):\n import pandas as pd\n \"\"\"\n para_dic = strategy_para_dic\n keys = para_dic.keys()\n parasetlist = pd.DataFrame(columns=['Setname'] + keys)\n total_num = 1\n for v in para_dic.values():\n total_num *= len(v)\n parasetlist['No.'] = range(total_num)\n for i in range(total_num):\n parasetlist.ix[i, 'Setname'] = \"Set%d\" % i\n multipliter = total_num\n v_num = 1\n for k, v in para_dic.items():\n v_num = v_num * len(v)\n for i in range(v_num):\n v_value = v[i]\n multipliter = multipliter/v_num\n parasetlist.loc[i*multipliter: (i+1)*multipliter, k] = v_value\n parasetlist.loc[i*multipliter:(i+1)*multipliter, 'Setname'] = parasetlist.loc[i*multipliter:(i+1)*multipliter, 'Setname'] + \" %s_%d\" % (k, v_value)\n return parasetlist\n \"\"\"\n if para_list_dic:\n n_list = para_str_to_int(para_list_dic['N'])\n m1_list = para_str_to_int(para_list_dic['M1'])\n m2_list = para_str_to_int(para_list_dic['M2'])\n n1_list= para_str_to_int(para_list_dic['N1'])\n man_list = para_str_to_int(para_list_dic['MaN'])\n else:\n n_list = strategy_para_dic['N']\n m1_list = strategy_para_dic['M1']\n m2_list = strategy_para_dic['M2']\n n1_list = strategy_para_dic['N1']\n man_list = strategy_para_dic['MaN']\n setlist = []\n i = 0\n for n1 in n1_list:\n for m1 in m1_list:\n # for m2 in range(3, 15, 3):\n for m2 in m2_list:\n # for n in range(3, 16, 3):\n for n in n_list:\n # for ma_n in range(20, 51, 10):\n for ma_n in man_list:\n setname = \"Set%d N1_%d M1_%d M2_%d N_%d MaN_%d\" % (i, n1, m1, m2, n, ma_n)\n l = [setname, n1, m1, m2, n, ma_n]\n setlist.append(l)\n i += 1\n\n setpd = pd.DataFrame(setlist, columns=['Setname', 'N1', 'M1', 'M2', 'N', 'MaN'])\n return setpd\n"
},
{
"alpha_fraction": 0.5698357820510864,
"alphanum_fraction": 0.5891215801239014,
"avg_line_length": 42.96026611328125,
"blob_id": "ddba084a993b7f28d3fbcee28f927d8813b96ed5",
"content_id": "6da2abda1d60c553cfafa760da540deaabb0bf19",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7297,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 151,
"path": "/HullRsiTunenlWin/HullRsiTunnelWin.py",
"repo_name": "smartgang/RsiWin",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n对RSI相对强弱指标进行三重平滑,其计算步骤如下:\n ⒈计算21日RSI指标;\n ⒉计算21日RSI指标的10日ema平均得出 RSI1;\n ⒊将第2步计算结果求5日ema平均得出 RSI2;\n ⒋求第2步、第3步计算结果的差额 NEWRSI;\n 5.对第4步的结果进行hull运算,得出HULLRSI;\n\n开仓条件和平仓条件:\n--------------------------------------------------------------------------------\n HULLRSI>0 同时 RSI1<70 做多 HULLRSI<0 平仓\n HULLRSI<0 同时 RSI1 >30 做空 HULLRSI>0 平仓\n HULLRSI=0 延续上根K线的状态\n\"\"\"\nimport MA\nimport Indexer.RSI as RSI\nimport pandas as pd\nimport os\nimport DATA_CONSTANTS as DC\nimport numpy as np\nimport multiprocessing\nimport ResultStatistics as RS\n\n\ndef HullRsiTunnelWin(symbolinfo, rawdata, para_set):\n setname = para_set['Setname']\n para_n1 = para_set['N1']\n para_m1 = para_set['M1']\n para_m2 = para_set['M2']\n para_n = para_set['N']\n para_tunnel_n = para_set['Tunnel_N']\n #para_rsi1_up = para_set['RSI1_UP']\n #para_rsi1_down = para_set['RSI1_DOWN']\n # print setname\n \"\"\"\n LC := REF(CLOSE,1);\n BACKGROUNDSTYLE(1);\n RSI1:SMA(MAX(CLOSE-LC,0),N1,1)/SMA(ABS(CLOSE-LC),N1,1)*100;\n RMA1:EMA(RSI1,M1);\n RMA2:EMA(RMA1,M2);\n RSINEW:=RMA1-RMA2;\n X:= 2*EMA2(RSINEW,ROUND(N/2,0))-EMA2(RSINEW,N);\n HURSI:10*EMA2(X,ROUND(SQRT(N),0)),COLORSTICK;\n \"\"\"\n rsi1 = pd.Series(RSI.rsi(rawdata['close'], para_n1))\n rsi_ema1 = MA.calEMA(rsi1, para_m1)\n rsi_ema2 = MA.calEMA(rsi_ema1, para_m2)\n rsi_new = rsi_ema1 - rsi_ema2\n hull_rsi = MA.hull_ma(rsi_new, para_n)\n #rawdata['RSI1'] = rsi1\n rawdata['RSI_EMA1'] = rsi_ema1\n #rawdata['RSI_EMA2'] = rsi_ema2\n #rawdata['RSI_NEW'] = rsi_new\n rawdata['HullRsi'] = hull_rsi\n rawdata['TOP_EMA'] = MA.calEMA(rawdata['high'], para_tunnel_n)\n rawdata['BOTTOM_EMA'] = MA.calEMA(rawdata['low'], para_tunnel_n)\n rawdata['zero'] = 0\n rawdata['Unnamed: 0'] = range(rawdata.shape[0])\n # 计算M金叉和死叉\n rawdata['HullRsi_True'], rawdata['HullRsi_Cross'] = MA.dfCross(rawdata, 'HullRsi', 'zero')\n\n # ================================ 找出买卖点================================================\n # 1.先找出SAR金叉的买卖点\n # 2.找到结合判决条件的买点\n # 3.从MA买点中滤出真实买卖点\n # 取出金叉点\n goldcrosslist = pd.DataFrame({'goldcrosstime': rawdata.loc[rawdata['HullRsi_Cross'] == 1, 'strtime']})\n goldcrosslist['goldcrossutc'] = rawdata.loc[rawdata['HullRsi_Cross'] == 1, 'utc_time']\n goldcrosslist['goldcrossindex'] = rawdata.loc[rawdata['HullRsi_Cross'] == 1, 'Unnamed: 0']\n goldcrosslist['goldcrossprice'] = rawdata.loc[rawdata['HullRsi_Cross'] == 1, 'close']\n goldcrosslist['goldcrossrsi'] = rawdata.loc[rawdata['HullRsi_Cross'] == 1, 'RSI_EMA1']\n\n # 取出死叉点\n deathcrosslist = pd.DataFrame({'deathcrosstime': rawdata.loc[rawdata['HullRsi_Cross'] == -1, 'strtime']})\n deathcrosslist['deathcrossutc'] = rawdata.loc[rawdata['HullRsi_Cross'] == -1, 'utc_time']\n deathcrosslist['deathcrossindex'] = rawdata.loc[rawdata['HullRsi_Cross'] == -1, 'Unnamed: 0']\n deathcrosslist['deathcrossprice'] = rawdata.loc[rawdata['HullRsi_Cross'] == -1, 'close']\n deathcrosslist['deathcrossrsi'] = rawdata.loc[rawdata['HullRsi_Cross'] == -1, 'RSI_EMA1']\n\n goldcrosslist = goldcrosslist.reset_index(drop=True)\n deathcrosslist = deathcrosslist.reset_index(drop=True)\n\n # 生成多仓序列(金叉在前,死叉在后)\n if goldcrosslist.ix[0, 'goldcrossindex'] < deathcrosslist.ix[0, 'deathcrossindex']:\n longcrosslist = pd.concat([goldcrosslist, deathcrosslist], axis=1)\n else: # 如果第一个死叉的序号在金叉前,则要将死叉往上移1格\n longcrosslist = pd.concat([goldcrosslist, deathcrosslist.shift(-1)], axis=1)\n longcrosslist = longcrosslist.set_index(pd.Index(longcrosslist['goldcrossindex']), drop=True)\n\n # 生成空仓序列(死叉在前,金叉在后)\n if deathcrosslist.ix[0, 'deathcrossindex'] < goldcrosslist.ix[0, 'goldcrossindex']:\n shortcrosslist = pd.concat([deathcrosslist, goldcrosslist], axis=1)\n else: # 如果第一个金叉的序号在死叉前,则要将金叉往上移1格\n shortcrosslist = pd.concat([deathcrosslist, goldcrosslist.shift(-1)], axis=1)\n shortcrosslist = shortcrosslist.set_index(pd.Index(shortcrosslist['deathcrossindex']), drop=True)\n\n # 取出开多序号和开空序号\n #openlongindex = rawdata.loc[\n # (rawdata['HullRsi_Cross'] == 1) & (rawdata['RSI_EMA1'] < para_rsi1_up)].index\n #openshortindex = rawdata.loc[\n # (rawdata['HullRsi_Cross'] == -1) & (rawdata['RSI_EMA1'] > para_rsi1_down)].index\n openlongindex = rawdata.loc[(rawdata['HullRsi_Cross'] == 1) & (rawdata['close'] > rawdata['TOP_EMA'])].index\n openshortindex = rawdata.loc[(rawdata['HullRsi_Cross'] == -1) & (rawdata['close'] < rawdata['BOTTOM_EMA'])].index\n # 从多仓序列中取出开多序号的内容,即为开多操作\n longopr = longcrosslist.loc[openlongindex]\n longopr['tradetype'] = 1\n longopr.rename(columns={'goldcrosstime': 'opentime',\n 'goldcrossutc': 'openutc',\n 'goldcrossindex': 'openindex',\n 'goldcrossprice': 'openprice',\n 'goldcrossrsi': 'open_rsi',\n 'deathcrosstime': 'closetime',\n 'deathcrossutc': 'closeutc',\n 'deathcrossindex': 'closeindex',\n 'deathcrossprice': 'closeprice',\n 'deathcrossrsi': 'close_rsi'}, inplace=True)\n\n # 从空仓序列中取出开空序号的内容,即为开空操作\n shortopr = shortcrosslist.loc[openshortindex]\n shortopr['tradetype'] = -1\n shortopr.rename(columns={'deathcrosstime': 'opentime',\n 'deathcrossutc': 'openutc',\n 'deathcrossindex': 'openindex',\n 'deathcrossprice': 'openprice',\n 'deathcrossrsi': 'open_rsi',\n 'goldcrosstime': 'closetime',\n 'goldcrossutc': 'closeutc',\n 'goldcrossindex': 'closeindex',\n 'goldcrossprice': 'closeprice',\n 'goldcrossrsi': 'close_rsi'}, inplace=True)\n\n # 结果分析\n result = pd.concat([longopr, shortopr])\n result = result.sort_index()\n result = result.reset_index(drop=True)\n # result.drop(result.shape[0] - 1, inplace=True)\n result = result.dropna()\n # 去掉跨合约的操作\n # 使用单合约,不用再去掉跨合约\n # result = removeContractSwap(result, contractswaplist)\n\n #rawdata.to_csv('%s_rawdata.csv' % setname)\n slip = symbolinfo.getSlip()\n result['ret'] = ((result['closeprice'] - result['openprice']) * result['tradetype']) - slip\n result['ret_r'] = result['ret'] / result['openprice']\n return result\n\n\nif __name__ == '__main__':\n pass"
},
{
"alpha_fraction": 0.5763465762138367,
"alphanum_fraction": 0.591803252696991,
"avg_line_length": 45.41304397583008,
"blob_id": "6be255ad48570b67d900dddcb81f897b9e192287",
"content_id": "14ebad591b8ee50a6e9e284cf007d1a455f0b7aa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4270,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 92,
"path": "/HullRsiTunenlWin/HullRsiTunnelWin_Function.py",
"repo_name": "smartgang/RsiWin",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nimport pandas as pd\nimport DATA_CONSTANTS as DC\nimport HullRsiTunnelWin_Parameter as Parameter\nimport os\n\n\ndef set_generator():\n setlist = []\n i = 0\n for n1 in range(15, 36, 5):\n for m1 in range(6, 17, 4):\n # for m2 in range(3, 15, 3):\n for m2 in [3, 6, 9]:\n #for n in range(3, 16, 3):\n for n in [6, 10, 14, 18]:\n #for ma_n in range(20, 51, 10):\n for tunnel_n in [8, 14, 20, 26]:\n setname = \"Set%d N1_%d M1_%d M2_%d N_%d Tunnel_N_%d\" % (i, n1, m1, m2, n, tunnel_n)\n l = [setname, n1, m1, m2, n, tunnel_n]\n setlist.append(l)\n i += 1\n\n setpd = pd.DataFrame(setlist, columns=['Setname', 'N1', 'M1', 'M2', 'N', 'Tunnel_N'])\n #setpd['RSI1_UP'] = 70\n #setpd['RSI1_DOWN'] = 30\n\n upperpath = DC.getUpperPath(Parameter.folderLevel)\n resultpath = upperpath + Parameter.resultFolderName\n setpd.to_csv(resultpath + Parameter.parasetname)\n\n\ndef stat_multi_symbol_result():\n upperpath = DC.getUpperPath(Parameter.folderLevel)\n resultpath = upperpath + Parameter.resultFolderName\n os.chdir(resultpath)\n multi_symbol_df = pd.read_excel('HullRsiWin_symbol_KMIN_set.xlsx')\n for n,row in multi_symbol_df.iterrows():\n strategy_name = row['strategyName']\n exchange_id = row['exchange_id']\n sec_id = row['sec_id']\n bar_type = row['K_MIN']\n folder_name = \"%s %s %s %d\\\\\" % (strategy_name, exchange_id, sec_id, bar_type)\n result_file_name = \"%s %s.%s %d finalresults.csv\" % (strategy_name, exchange_id, sec_id, bar_type)\n print result_file_name\n result_df = pd.read_csv(folder_name+result_file_name)\n multi_symbol_df.ix[n, 'OprTimes'] = result_df['OprTimes'].mean()\n multi_symbol_df.ix[n, 'Annual_max'] = result_df['Annual'].max()\n multi_symbol_df.ix[n, 'Annual_avg'] = result_df['Annual'].mean()\n multi_symbol_df.ix[n, 'EndCash_avg'] = result_df['EndCash'].mean()\n multi_symbol_df.ix[n, 'EndCash_max'] = result_df['EndCash'].max()\n multi_symbol_df.ix[n, 'own_cash_max_max'] = result_df['max_own_cash'].max()\n multi_symbol_df.ix[n, 'own_cash_max_avg'] = result_df['max_own_cash'].mean()\n multi_symbol_df.ix[n, 'Sharpe_max'] = result_df['Sharpe'].max()\n multi_symbol_df.ix[n, 'SR_avg'] = result_df['SR'].mean()\n multi_symbol_df.ix[n, 'DR_avg'] = result_df['DrawBack'].mean()\n multi_symbol_df.ix[n, 'SingleEarn_avg'] = result_df['MaxSingleEarnRate'].mean()\n multi_symbol_df.ix[n, 'SingleLoss_avg'] = result_df['MaxSingleLossRate'].mean()\n multi_symbol_df.ix[n, 'ProfitLossRate_avg'] = result_df['ProfitLossRate'].mean()\n multi_symbol_df.to_csv('HullRsiWin_symbol_KMIN_set2_result.csv')\n\n\ndef add_max_period_cash_to_finalresult():\n upperpath = DC.getUpperPath(Parameter.folderLevel)\n resultpath = upperpath + Parameter.resultFolderName\n os.chdir(resultpath)\n para_set_list = pd.read_csv('ParameterSet_HullRsi.csv')['Setname'].tolist()\n multi_symbol_df = pd.read_excel('HullRsiWin_symbol_KMIN_set.xlsx')\n for n, row in multi_symbol_df.iterrows():\n strategy_name = row['strategyName']\n exchange_id = row['exchange_id']\n sec_id = row['sec_id']\n bar_type = row['K_MIN']\n folder_name = \"%s %s %s %d\\\\\" % (strategy_name, exchange_id, sec_id, bar_type)\n result_file_name = \"%s %s.%s %d finalresults.csv\" % (strategy_name, exchange_id, sec_id, bar_type)\n #print result_file_name\n result_df = pd.read_csv(folder_name+result_file_name, index_col='Setname')\n for setname in para_set_list:\n set_file_name = \"%s %s.%s%d %s result.csv\" % (strategy_name, exchange_id, sec_id, bar_type, setname)\n print set_file_name\n set_result = pd.read_csv(folder_name + set_file_name)\n max_own_cash = set_result['own cash'].max()\n result_df.ix[setname, 'max_own_cash'] = max_own_cash\n result_df.to_csv(folder_name + result_file_name)\n pass\n\n\nif __name__ == \"__main__\":\n set_generator()\n #stat_multi_symbol_result()\n #add_max_period_cash_to_finalresult()\n pass\n"
},
{
"alpha_fraction": 0.5314095616340637,
"alphanum_fraction": 0.5546846985816956,
"avg_line_length": 40.2843132019043,
"blob_id": "9e83e0bc1aa7cc3f36eb9ccc0aade221824a2f21",
"content_id": "57366989d2ee9fffdc8cc81fbe5f467193255a78",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9159,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 204,
"path": "/HullRsiWin/HullRsiWin.py",
"repo_name": "smartgang/RsiWin",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\n对RSI相对强弱指标进行三重平滑,其计算步骤如下:\n ⒈计算21日RSI指标;\n ⒉计算21日RSI指标的10日ema平均得出 RSI1;\n ⒊将第2步计算结果求5日ema平均得出 RSI2;\n ⒋求第2步、第3步计算结果的差额 NEWRSI;\n 5.对第4步的结果进行hull运算,得出HULLRSI;\n\n开仓条件和平仓条件:\n--------------------------------------------------------------------------------\n HULLRSI>0 同时 RSI1<70 做多 HULLRSI<0 平仓\n HULLRSI<0 同时 RSI1 >30 做空 HULLRSI>0 平仓\n HULLRSI=0 延续上根K线的状态\n\"\"\"\nimport MA\nimport Indexer.RSI as RSI\nimport pandas as pd\nimport os\nimport DATA_CONSTANTS as DC\nimport numpy as np\nimport multiprocessing\nimport ResultStatistics as RS\n\n\ndef HullRsiWin(symbolinfo, rawdata, para_set):\n setname = para_set['Setname']\n para_n1 = para_set['N1']\n para_m1 = para_set['M1']\n para_m2 = para_set['M2']\n para_n = para_set['N']\n para_ema_n = para_set['MaN']\n #para_rsi1_up = para_set['RSI1_UP']\n #para_rsi1_down = para_set['RSI1_DOWN']\n # print setname\n \"\"\"\n LC := REF(CLOSE,1);\n BACKGROUNDSTYLE(1);\n RSI1:SMA(MAX(CLOSE-LC,0),N1,1)/SMA(ABS(CLOSE-LC),N1,1)*100;\n RMA1:EMA(RSI1,M1);\n RMA2:EMA(RMA1,M2);\n RSINEW:=RMA1-RMA2;\n X:= 2*EMA2(RSINEW,ROUND(N/2,0))-EMA2(RSINEW,N);\n HURSI:10*EMA2(X,ROUND(SQRT(N),0)),COLORSTICK;\n \"\"\"\n rsi1 = pd.Series(RSI.rsi(rawdata['close'], para_n1))\n rsi_ema1 = MA.calEMA(rsi1, para_m1)\n rsi_ema2 = MA.calEMA(rsi_ema1, para_m2)\n rsi_new = rsi_ema1 - rsi_ema2\n hull_rsi = MA.hull_ma(rsi_new, para_n)\n #rawdata['RSI1'] = rsi1\n rawdata['RSI_EMA1'] = rsi_ema1\n #rawdata['RSI_EMA2'] = rsi_ema2\n #rawdata['RSI_NEW'] = rsi_new\n rawdata['HullRsi'] = hull_rsi\n rawdata['EMA'] = MA.calEMA(rawdata['close'], para_ema_n)\n rawdata['zero'] = 0\n rawdata['Unnamed: 0'] = range(rawdata.shape[0])\n # 计算M金叉和死叉\n rawdata['HullRsi_True'], rawdata['HullRsi_Cross'] = MA.dfCross(rawdata, 'HullRsi', 'zero')\n\n # ================================ 找出买卖点================================================\n # 1.先找出SAR金叉的买卖点\n # 2.找到结合判决条件的买点\n # 3.从MA买点中滤出真实买卖点\n # 取出金叉点\n goldcrosslist = pd.DataFrame({'goldcrosstime': rawdata.loc[rawdata['HullRsi_Cross'] == 1, 'strtime']})\n goldcrosslist['goldcrossutc'] = rawdata.loc[rawdata['HullRsi_Cross'] == 1, 'utc_time']\n goldcrosslist['goldcrossindex'] = rawdata.loc[rawdata['HullRsi_Cross'] == 1, 'Unnamed: 0']\n goldcrosslist['goldcrossprice'] = rawdata.loc[rawdata['HullRsi_Cross'] == 1, 'close']\n goldcrosslist['goldcrossrsi'] = rawdata.loc[rawdata['HullRsi_Cross'] == 1, 'RSI_EMA1']\n\n # 取出死叉点\n deathcrosslist = pd.DataFrame({'deathcrosstime': rawdata.loc[rawdata['HullRsi_Cross'] == -1, 'strtime']})\n deathcrosslist['deathcrossutc'] = rawdata.loc[rawdata['HullRsi_Cross'] == -1, 'utc_time']\n deathcrosslist['deathcrossindex'] = rawdata.loc[rawdata['HullRsi_Cross'] == -1, 'Unnamed: 0']\n deathcrosslist['deathcrossprice'] = rawdata.loc[rawdata['HullRsi_Cross'] == -1, 'close']\n deathcrosslist['deathcrossrsi'] = rawdata.loc[rawdata['HullRsi_Cross'] == -1, 'RSI_EMA1']\n\n goldcrosslist = goldcrosslist.reset_index(drop=True)\n deathcrosslist = deathcrosslist.reset_index(drop=True)\n\n # 生成多仓序列(金叉在前,死叉在后)\n if goldcrosslist.ix[0, 'goldcrossindex'] < deathcrosslist.ix[0, 'deathcrossindex']:\n longcrosslist = pd.concat([goldcrosslist, deathcrosslist], axis=1)\n else: # 如果第一个死叉的序号在金叉前,则要将死叉往上移1格\n longcrosslist = pd.concat([goldcrosslist, deathcrosslist.shift(-1)], axis=1)\n longcrosslist = longcrosslist.set_index(pd.Index(longcrosslist['goldcrossindex']), drop=True)\n\n # 生成空仓序列(死叉在前,金叉在后)\n if deathcrosslist.ix[0, 'deathcrossindex'] < goldcrosslist.ix[0, 'goldcrossindex']:\n shortcrosslist = pd.concat([deathcrosslist, goldcrosslist], axis=1)\n else: # 如果第一个金叉的序号在死叉前,则要将金叉往上移1格\n shortcrosslist = pd.concat([deathcrosslist, goldcrosslist.shift(-1)], axis=1)\n shortcrosslist = shortcrosslist.set_index(pd.Index(shortcrosslist['deathcrossindex']), drop=True)\n\n # 取出开多序号和开空序号\n #openlongindex = rawdata.loc[\n # (rawdata['HullRsi_Cross'] == 1) & (rawdata['RSI_EMA1'] < para_rsi1_up)].index\n #openshortindex = rawdata.loc[\n # (rawdata['HullRsi_Cross'] == -1) & (rawdata['RSI_EMA1'] > para_rsi1_down)].index\n openlongindex = rawdata.loc[(rawdata['HullRsi_Cross'] == 1) & (rawdata['close'] > rawdata['EMA'])].index\n openshortindex = rawdata.loc[(rawdata['HullRsi_Cross'] == -1) & (rawdata['close'] < rawdata['EMA'])].index\n # 从多仓序列中取出开多序号的内容,即为开多操作\n longopr = longcrosslist.loc[openlongindex]\n longopr['tradetype'] = 1\n longopr.rename(columns={'goldcrosstime': 'opentime',\n 'goldcrossutc': 'openutc',\n 'goldcrossindex': 'openindex',\n 'goldcrossprice': 'openprice',\n 'goldcrossrsi': 'open_rsi',\n 'deathcrosstime': 'closetime',\n 'deathcrossutc': 'closeutc',\n 'deathcrossindex': 'closeindex',\n 'deathcrossprice': 'closeprice',\n 'deathcrossrsi': 'close_rsi'}, inplace=True)\n\n # 从空仓序列中取出开空序号的内容,即为开空操作\n shortopr = shortcrosslist.loc[openshortindex]\n shortopr['tradetype'] = -1\n shortopr.rename(columns={'deathcrosstime': 'opentime',\n 'deathcrossutc': 'openutc',\n 'deathcrossindex': 'openindex',\n 'deathcrossprice': 'openprice',\n 'deathcrossrsi': 'open_rsi',\n 'goldcrosstime': 'closetime',\n 'goldcrossutc': 'closeutc',\n 'goldcrossindex': 'closeindex',\n 'goldcrossprice': 'closeprice',\n 'goldcrossrsi': 'close_rsi'}, inplace=True)\n\n # 结果分析\n result = pd.concat([longopr, shortopr])\n result = result.sort_index()\n result = result.reset_index(drop=True)\n # result.drop(result.shape[0] - 1, inplace=True)\n result = result.dropna()\n # 去掉跨合约的操作\n # 使用单合约,不用再去掉跨合约\n # result = removeContractSwap(result, contractswaplist)\n\n #rawdata.to_csv('%s_rawdata.csv' % setname)\n slip = symbolinfo.getSlip()\n result['ret'] = ((result['closeprice'] - result['openprice']) * result['tradetype']) - slip\n result['ret_r'] = result['ret'] / result['openprice']\n return result\n\n\nif __name__ == '__main__':\n # ====================参数和文件夹设置======================================\n # 参数设置\n strategyName = 'HullRsiWin'\n exchange_id = 'SHFE'\n sec_id = 'RB'\n bar_type = 3600\n domain_symbol = '.'.join([exchange_id, sec_id])\n startdate = '2010-01-01'\n enddate = '2018-08-01'\n\n # MACD参数\n N1 = 21\n M1 = 12\n M2 = 5\n N = 20\n RSI_UP = 70\n RSI_DOWN = 30\n\n # 文件路径\n upperpath = DC.getUpperPath(2)\n foldername = ' '.join([strategyName, exchange_id, sec_id, str(bar_type)])\n resultpath = upperpath + \"\\\\Results\\\\\"\n os.chdir(resultpath)\n try:\n os.mkdir(foldername)\n except:\n print (\"%s folder already exsist!\" % foldername)\n os.chdir(foldername)\n\n # ======================数据准备==============================================\n # 取参数集\n #parasetlist = pd.read_csv(resultpath + 'MACDParameterSet2.csv')\n #paranum = parasetlist.shape[0]\n # 取合约信息\n symbolinfo = DC.SymbolInfo(domain_symbol)\n # 取源数据\n rawdata = DC.getBarBySymbol(domain_symbol, 'RB1810', bar_type, startdate + \" 00:00:00\", enddate + \" 23:59:59\")\n\n paraSet = {\n 'Setname': 'test',\n 'N1': N1,\n 'M1': M1,\n 'M2': M2,\n 'N': N,\n 'RSI1_UP': RSI_UP,\n 'RSI1_DOWN': RSI_DOWN\n }\n result = HullRsiWin(symbolinfo, rawdata, paraSet)\n # 显示结果\n result['commission_fee'], result['per earn'], result['own cash'], result['hands'] = RS.calcResult(result,\n symbolinfo,\n 200000,\n 1)\n\n result.to_csv(strategyName + ' ' + symbolinfo.domain_symbol + str(bar_type) + ' ' + 'test' + ' result.csv', index=False)"
}
] | 9 |
kaiwk/forum-wechat | https://github.com/kaiwk/forum-wechat | f8e78b03786e8fd27ef1774c5cacf83d2816bcfd | bdd5439b7d243c1678de522a63f36469423044ce | 667bf1d4802030d16d62dc27fcbd0196944e63b3 | refs/heads/master | 2022-12-24T08:54:25.539142 | 2018-12-19T15:20:26 | 2018-12-19T15:20:26 | 159,819,534 | 0 | 0 | MIT | 2018-11-30T12:19:18 | 2018-12-19T15:20:42 | 2022-12-08T01:28:24 | Python | [
{
"alpha_fraction": 0.4886474311351776,
"alphanum_fraction": 0.5042484998703003,
"avg_line_length": 22.85049819946289,
"blob_id": "8ea2f4825223a077933742a11edc6badad539863",
"content_id": "f9cd181df964d995e7f885b5ae3e63214c6b6807",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7179,
"license_type": "permissive",
"max_line_length": 80,
"num_lines": 301,
"path": "/app/user.py",
"repo_name": "kaiwk/forum-wechat",
"src_encoding": "UTF-8",
"text": "from flask import Blueprint, jsonify\n\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom sqlalchemy.exc import IntegrityError\n\nfrom app.database import User, Question, Answer\nfrom . import get_logger\n\n\nlog = get_logger()\n\n\nbp = Blueprint('user', __name__)\n\n\[email protected]('/<int:user_id>', methods=['GET'])\ndef get_user(user_id):\n try:\n user = User.query.get(user_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no user found'\n })\n return jsonify({\n 'status': 200,\n 'code': 0,\n 'msg': 'get user info success',\n 'user': {\n 'id': user.id,\n 'avatar': user.avatar,\n 'nickname': user.nickname,\n 'self_intro': user.self_intro\n }\n })\n\n\[email protected]('/<int:user_id>/follow/<int:following_id>', methods=['PUT'])\ndef follow_user(user_id, following_id):\n try:\n user = User.query.get(user_id)\n following_user = User.query.get(following_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no user found'\n })\n\n try:\n user.follow(following_user)\n except IntegrityError as e:\n log.error(e)\n return jsonify({\n 'status': 409,\n 'code': 2,\n 'msg': 'user has been followed'\n })\n\n return jsonify({\n 'status': 201,\n 'code': 0,\n 'msg': 'following success'\n })\n\n\[email protected]('/<int:user_id>/unfollow/<int:following_id>', methods=['PUT'])\ndef unfollow_user(user_id, following_id):\n try:\n user = User.query.get(user_id)\n following_user = User.query.get(following_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no user found'\n })\n\n try:\n user.unfollow(following_user)\n except IntegrityError as e:\n log.error(e)\n return jsonify({\n 'status': 409,\n 'code': 2,\n 'msg': 'this user has not been followed'\n })\n\n return jsonify({\n 'status': 201,\n 'code': 0,\n 'msg': 'unfollow success'\n })\n\n\[email protected]('/<int:user_id>/followings', methods=['GET'])\ndef get_followings(user_id):\n try:\n user = User.query.get(user_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no user found'\n })\n\n return jsonify({\n 'status': 200,\n 'code': 0,\n 'msg': 'get success',\n 'data': [u.as_dict() for u in user.followings.all()]\n })\n\n\[email protected]('/<int:user_id>/follow_question/<int:question_id>', methods=['PUT'])\ndef follow_question(user_id, question_id):\n try:\n user = User.query.get(user_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no user found'\n })\n\n try:\n question = Question.query.get(question_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no question found'\n })\n\n try:\n user.follow_question(question)\n except IntegrityError as e:\n log.error(e)\n return jsonify({\n 'status': 409,\n 'code': 2,\n 'msg': 'question has been followed'\n })\n\n return jsonify({\n 'status': 201,\n 'code': 0,\n 'msg': 'follow question success'\n })\n\n\[email protected]('/<int:user_id>/unfollow_question/<int:question_id>', methods=['PUT'])\ndef unfollow_question(user_id, question_id):\n try:\n user = User.query.get(user_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no user found'\n })\n\n try:\n question = Question.query.get(question_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no question found'\n })\n\n try:\n user.unfollow_question(question)\n except IntegrityError as e:\n log.error(e)\n return jsonify({\n 'status': 409,\n 'code': 2,\n 'msg': 'this question has not been followed'\n })\n\n return jsonify({\n 'status': 201,\n 'code': 0,\n 'msg': 'follow question success'\n })\n\n\[email protected]('/<int:user_id>/questions', methods=['GET'])\ndef get_questions(user_id):\n try:\n user = User.query.get(user_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no user found'\n })\n\n return jsonify({\n 'status': 200,\n 'code': 0,\n 'msg': 'get success',\n 'data': [q.as_dict() for q in user.questions.all()]\n })\n\n\[email protected]('/<int:user_id>/answers', methods=['GET'])\ndef get_answers(user_id):\n try:\n user = User.query.get(user_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no user found'\n })\n\n return jsonify({\n 'status': 200,\n 'code': 0,\n 'msg': 'get success',\n 'data': [a.as_dict() for a in user.answers.all()]\n })\n\n\[email protected]('/<int:user_id>/comments', methods=['GET'])\ndef get_comments(user_id):\n try:\n user = User.query.get(user_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no user found'\n })\n return jsonify({\n 'status': 200,\n 'code': 0,\n 'msg': 'get success',\n 'data': [c.as_dict() for c in user.comments.all()]\n })\n\n\[email protected]('/<int:user_id>/following_questions', methods=['GET'])\ndef get_following_questions(user_id):\n try:\n user = User.query.get(user_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no user found'\n })\n\n return jsonify({\n 'status': 200,\n 'code': 0,\n 'msg': 'get success',\n 'data': [q.as_dict() for q in user.following_questions.all()]\n })\n\n\[email protected]('/<int:user_id>/following_questions/answers', methods=['GET'])\ndef get_following_questions_answers(user_id):\n try:\n user = User.query.get(user_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no user found'\n })\n\n flw_qst_ans = []\n answers = Answer.query.all()\n\n for a in answers:\n if a.question in user.following_questions:\n flw_qst_ans.append(a)\n\n return jsonify({\n 'status': 200,\n 'code': 0,\n 'msg': 'get success',\n 'data': [a.as_dict() for a in flw_qst_ans]\n })\n"
},
{
"alpha_fraction": 0.4502435624599457,
"alphanum_fraction": 0.48086291551589966,
"avg_line_length": 26.634614944458008,
"blob_id": "94e57fbd1146404d37f4c708313d29ff0e47344f",
"content_id": "66f1d435dd12ab44f9d78bb8779fa72c95c27714",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "YAML",
"length_bytes": 1437,
"license_type": "permissive",
"max_line_length": 68,
"num_lines": 52,
"path": "/docker-compose.yml",
"repo_name": "kaiwk/forum-wechat",
"src_encoding": "UTF-8",
"text": "version: '3'\nservices:\n web:\n build: .\n image: forum-wechat\n restart: always\n ports:\n - 5000:5000\n volumes:\n - ./app:/home/forum-wechat/app\n - ./instance:/home/forum-wechat/instance\n - ./migrations:/home/forum-wechat/migrations\n env_file:\n - ./.docker-env/web\n depends_on:\n - mysql\n container_name: forum-wechat\n caddy:\n image: kaiwk/caddy\n restart: always\n volumes:\n - ./:/root/forum-wechat/\n - ./docker/conf/caddy/Caddyfile:/etc/caddy/Caddyfile\n depends_on:\n - web\n ports:\n - 80:80\n - 443:443\n container_name: forum-webserver\n mysql:\n image: mysql:5.7\n restart: always\n volumes:\n - ./data:/var/lib/mysql\n ports:\n - 3306:3306\n env_file:\n - ./.docker-env/mysql\n command: ['mysqld', '--max-connections=200',\n '--character-set-server=utf8mb4',\n '--collation-server=utf8mb4_unicode_ci']\n container_name: forum-mysql\n webhook:\n image: kaiwk/webhook-github\n restart: always\n volumes:\n - ./:/project-repo\n ports:\n - 8000:8000\n env_file:\n - ./.docker-env/webhook-github\n container_name: webhook-github\n"
},
{
"alpha_fraction": 0.774193525314331,
"alphanum_fraction": 0.774193525314331,
"avg_line_length": 22.25,
"blob_id": "a10bdba9045f3ed08551d057caf8f2ab5a95403c",
"content_id": "809da7ea636f78c99be4a715223391bef0d3499f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 93,
"license_type": "permissive",
"max_line_length": 50,
"num_lines": 4,
"path": "/flask_env.sh",
"repo_name": "kaiwk/forum-wechat",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env bash\n\nexport FLASK_APP=app\nexport FLASK_ENV=local-devel # development/product\n"
},
{
"alpha_fraction": 0.510429859161377,
"alphanum_fraction": 0.519279420375824,
"avg_line_length": 22.962121963500977,
"blob_id": "1ddaa7ad4e089434f556c1dd2b5225985edb96ff",
"content_id": "07261b212af04f52f5f3b612963d80c42f78b5d4",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3164,
"license_type": "permissive",
"max_line_length": 76,
"num_lines": 132,
"path": "/app/page.py",
"repo_name": "kaiwk/forum-wechat",
"src_encoding": "UTF-8",
"text": "from flask import Blueprint, jsonify, request\n\nfrom sqlalchemy import func\nfrom sqlalchemy.orm.exc import NoResultFound\n\nfrom app.database import User, Answer, Question\nfrom . import get_logger\n\n\nlog = get_logger()\n\n\nbp = Blueprint('page', __name__)\n\n\[email protected]('/following_questions_update/user/<int:user_id>', methods=['GET'])\ndef following_questions_answers(user_id):\n try:\n user = User.query.get(user_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no user found'\n })\n\n data_list = []\n answers = Answer.query.all()\n\n for a in answers:\n if a.question in user.following_questions:\n # add question data\n d = a.as_dict()\n u = User.query.get(a.user_id)\n d['question_title'] = a.question.title\n d['nickname'] = u.nickname\n d['avatar'] = u.avatar\n d['answer_count'] = a.question.answers.count()\n data_list.append(d)\n\n return jsonify({\n 'status': 200,\n 'code': 0,\n 'msg': 'get success',\n 'data': data_list\n })\n\n\[email protected]('/comment_list/', methods=['GET'])\ndef get_comments():\n\n answer_id = request.args.get('answer_id')\n\n try:\n answer = Answer.query.get(answer_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no answer found'\n })\n\n data_list = []\n\n for a in answer.comments.all():\n d = a.as_dict()\n u = User.query.get(a.user_id)\n d['nickname'] = u.nickname\n d['avatar'] = u.avatar\n data_list.append(d)\n\n return jsonify({\n 'status': 200,\n 'code': 0,\n 'msg': \"get success\",\n 'data': data_list\n })\n\n\[email protected]('/index/', methods=['GET'])\ndef index():\n questions = Question.query.order_by(func.rand()).all()\n\n data_list = []\n for q in questions:\n answer = q.answers.first()\n if answer:\n d = q.as_dict()\n u = User.query.get(answer.user_id)\n d['answer_id'] = answer.id\n d['answer_content'] = answer.content\n d['answer_user_id'] = answer.user_id\n d['nickname'] = u.nickname\n d['avatar'] = u.avatar\n data_list.append(d)\n\n return jsonify({\n 'status': 200,\n 'code': 0,\n 'msg': 'get success',\n 'data': data_list\n })\n\n\[email protected]('/answer_list', methods=['GET'])\ndef answer_list():\n question_id = request.args.get('question_id')\n try:\n question = Question.query.get(question_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no question found'\n })\n\n data_list = []\n for a in question.answers.all():\n d = a.as_dict()\n u = User.query.get(a.user_id)\n d['nickname'] = u.nickname\n data_list.append(d)\n\n return jsonify({\n 'status': 200,\n 'code': 0,\n 'msg': 'get success',\n 'data': data_list\n })\n\n"
},
{
"alpha_fraction": 0.5131579041481018,
"alphanum_fraction": 0.5447368621826172,
"avg_line_length": 21.352941513061523,
"blob_id": "668dc1a46c758cd138171f010a051f379ee6e0c3",
"content_id": "ff15f4fad7a77e8a3456ae7fe80150c1f4165d62",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 380,
"license_type": "permissive",
"max_line_length": 64,
"num_lines": 17,
"path": "/docker/boot.sh",
"repo_name": "kaiwk/forum-wechat",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env bash\n\n. venv/bin/activate\n\nwhile true; do\n flask db upgrade\n if [[ \"$?\" == \"0\" ]]; then\n break\n fi\n echo Upgrade command failed, retrying in 5 secs...\n sleep 5\ndone\n\nexec gunicorn \"app:create_app()\" -w 4 -b 0.0.0.0:5000 \\\n --log-config ./docker/conf/gunicorn/logging.conf \\\n --log-level info \\\n --reload\n"
},
{
"alpha_fraction": 0.5999438762664795,
"alphanum_fraction": 0.6026090383529663,
"avg_line_length": 33.27404022216797,
"blob_id": "2797326d6f468fd7daa39e67dd42949e2025b3f5",
"content_id": "ede43b27a589922e43d8db0f41d1cd8d56fac007",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7129,
"license_type": "permissive",
"max_line_length": 97,
"num_lines": 208,
"path": "/app/database.py",
"repo_name": "kaiwk/forum-wechat",
"src_encoding": "UTF-8",
"text": "import datetime\n\nfrom flask_sqlalchemy import SQLAlchemy\nfrom flask_migrate import Migrate\n\ndb = SQLAlchemy()\nmigrate = Migrate()\n\nfollowings = db.Table('followings',\n db.Column('user_id', db.Integer,\n db.ForeignKey('user.id'), primary_key=True),\n db.Column('following_id', db.Integer,\n db.ForeignKey('user.id'), primary_key=True))\n\nfollowing_questions = db.Table('following_questions',\n db.Column('user_id', db.Integer,\n db.ForeignKey('user.id'), primary_key=True),\n db.Column('question_id', db.Integer,\n db.ForeignKey('question.id'), primary_key=True))\n\n\nclass CreateUpdateTimeMixin:\n created_on = db.Column(db.DateTime, server_default=db.func.now())\n updated_on = db.Column(db.DateTime, server_default=db.func.now(),\n server_onupdate=db.func.now())\n\n\nclass DictSerializable:\n def as_dict(self):\n result = dict()\n for key in self.__mapper__.c.keys():\n val = getattr(self, key)\n if type(val) == datetime.datetime:\n val = str(val)\n result[key] = val\n return result\n\n\nclass User(db.Model, CreateUpdateTimeMixin, DictSerializable):\n id = db.Column(db.Integer, primary_key=True)\n open_id = db.Column(db.String(128), nullable=False)\n avatar = db.Column(db.String(200))\n nickname = db.Column(db.String(30))\n self_intro = db.Column(db.String(200))\n questions = db.relationship('Question', backref='owner', lazy='dynamic')\n comments = db.relationship('Comment', backref='owner', lazy='dynamic')\n answers = db.relationship('Answer', backref='owner', lazy='dynamic')\n followings = db.relationship('User', secondary=followings,\n primaryjoin=(id == followings.c.user_id),\n secondaryjoin=(id == followings.c.following_id),\n backref=db.backref('followers', lazy='dynamic'), lazy='dynamic')\n following_questions = db.relationship('Question', secondary=following_questions,\n backref=db.backref('followers', lazy='dynamic'),\n lazy='dynamic')\n\n def __init__(self, open_id='', avatar='', nickname=''):\n self.open_id = open_id\n self.avatar = avatar\n self.nickname = nickname\n\n def __repr__(self):\n return '<User:{}, openid:{}>'.format(self.id, self.open_id)\n\n @staticmethod\n def save(open_id, avatar, nickname):\n user = User(open_id, avatar, nickname)\n db.session.add(user)\n db.session.commit()\n return user\n\n def follow(self, user):\n self.followings.append(user)\n db.session.commit()\n\n def unfollow(self, user):\n self.followings.remove(user)\n db.session.commit()\n\n def follow_question(self, question):\n self.following_questions.append(question)\n db.session.commit()\n\n def unfollow_question(self, question):\n self.following_questions.remove(question)\n db.session.commit()\n\n\nclass Comment(db.Model, CreateUpdateTimeMixin, DictSerializable):\n id = db.Column(db.Integer, primary_key=True)\n content = db.Column(db.Text, nullable=False)\n user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)\n answer_id = db.Column(db.Integer, db.ForeignKey('answer.id'), nullable=False)\n\n def __repr__(self):\n return '<Comment:{}>'.format(self.id)\n\n def __init__(self, content='', user_id=0, answser_id=0):\n self.content = content\n self.user_id = user_id\n self.answer_id = answser_id\n\n @staticmethod\n def save(content, user_id, answer_id):\n comment = Comment(content, user_id, answer_id)\n db.session.add(comment)\n db.session.commit()\n return comment\n\n @staticmethod\n def remove(comment_id):\n comment = Comment.query.get(comment_id)\n db.session.delete(comment)\n db.session.commit()\n\n @staticmethod\n def update(comment_id, content):\n comment = Comment.query.get(comment_id)\n comment.content = content\n db.session.commit()\n\n\nclass Answer(db.Model, CreateUpdateTimeMixin, DictSerializable):\n id = db.Column(db.Integer, primary_key=True)\n content = db.Column(db.Text, nullable=False)\n anonymous = db.Column(db.Boolean, default=False)\n user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)\n question_id = db.Column(db.Integer, db.ForeignKey('question.id'), nullable=False)\n comments = db.relationship('Comment', backref='answer', lazy='dynamic')\n\n def __init__(self, content='', anonymous=False, user_id=0, question_id=0):\n self.content = content\n self.anonymous = anonymous\n self.user_id = user_id\n self.question_id = question_id\n\n def __repr__(self):\n return '<Answer:{}>'.format(self.id)\n\n @staticmethod\n def save(content, anonymous, user_id, question_id):\n answer = Answer(content, anonymous, user_id, question_id)\n db.session.add(answer)\n db.session.commit()\n return answer\n\n @staticmethod\n def remove(answer_id):\n answer = Answer.query.get(answer_id)\n db.session.delete(answer)\n db.session.commit()\n\n @staticmethod\n def update(answer_id, content):\n answer = Answer.query.get(answer_id)\n answer.content = content\n db.session.commit()\n\n def add_comment(self, comment):\n self.comments.append(comment)\n db.session.commit()\n\n\nclass Question(db.Model, CreateUpdateTimeMixin, DictSerializable):\n id = db.Column(db.Integer, primary_key=True)\n title = db.Column(db.String(140), nullable=False)\n content = db.Column(db.Text, nullable=False)\n closed = db.Column(db.Boolean, default=False)\n user_id = db.Column(db.Integer, db.ForeignKey('user.id'), nullable=False)\n answers = db.relationship('Answer', backref='question', lazy='dynamic')\n\n def __init__(self, title='', content='', user_id=0):\n self.title = title\n self.content = content\n self.user_id = user_id\n\n def __repr__(self):\n return '<Question:{}>'.format(self.id)\n\n @staticmethod\n def save(title, content, user_id):\n question = Question(title, content, user_id)\n db.session.add(question)\n db.session.commit()\n return question\n\n @staticmethod\n def remove(question_id):\n question = Question.query.get(question_id)\n db.session.delete(question)\n db.session.commit()\n\n def update(self, title=None, content=None, closed=None):\n if title:\n self.title = title\n if content:\n self.content = content\n if closed:\n self.closed = closed\n db.session.commit()\n\n def add_answer(self, answer):\n self.answers.append(answer)\n db.session.commit()\n\n\ndef init_app(app):\n db.init_app(app)\n migrate.init_app(app, db)\n"
},
{
"alpha_fraction": 0.5658283829689026,
"alphanum_fraction": 0.6005917191505432,
"avg_line_length": 29.727272033691406,
"blob_id": "ec36384230a4bc611ecb8852e4d978e71728b278",
"content_id": "14c94005b4d978f13281f17058a93735cba0e5e4",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1352,
"license_type": "permissive",
"max_line_length": 88,
"num_lines": 44,
"path": "/migrations/versions/5a20064c47d9_.py",
"repo_name": "kaiwk/forum-wechat",
"src_encoding": "UTF-8",
"text": "\"\"\"empty message\n\nRevision ID: 5a20064c47d9\nRevises: d27d86884906\nCreate Date: 2018-12-14 19:22:53.836381\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\n\n\n# revision identifiers, used by Alembic.\nrevision = '5a20064c47d9'\ndown_revision = 'd27d86884906'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n op.alter_column('user', 'open_id',\n existing_type=sa.String(length=64),\n type_=sa.String(length=128),\n existing_nullable=True,\n nullable_=False)\n\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('question', sa.Column('title', sa.String(length=140), nullable=False))\n op.add_column('user', sa.Column('avatar', sa.String(length=200), nullable=True))\n op.add_column('user', sa.Column('nickname', sa.String(length=30), nullable=True))\n # ### end Alembic commands ###\n\n\ndef downgrade():\n op.alter_column('user', 'open_id',\n existing_type=sa.String(length=128),\n type_=sa.String(length=64),\n existing_nullable=False,\n nullable_=True)\n\n # ### commands auto generated by Alembic - please adjust! ###\n op.drop_column('user', 'nickname')\n op.drop_column('user', 'avatar')\n op.drop_column('question', 'title')\n # ### end Alembic commands ###\n"
},
{
"alpha_fraction": 0.6670570969581604,
"alphanum_fraction": 0.6682283878326416,
"avg_line_length": 31.836538314819336,
"blob_id": "e2ae0a26e62afb0426332bdb19e985860cac6fad",
"content_id": "912f673b79d7cd9a8e6cfbd8158c0cbae91aed34",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3415,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 104,
"path": "/app/__init__.py",
"repo_name": "kaiwk/forum-wechat",
"src_encoding": "UTF-8",
"text": "import os\nimport logging\nimport logging.config\n\nfrom werkzeug.exceptions import HTTPException\n\nfrom flask import Flask, redirect, Response\n\n\nclass AuthException(HTTPException):\n def __init__(self, message):\n super().__init__(message, Response(\n \"You could not be authenticated. Please refresh the page.\", 401,\n {'WWW-Authenticate': 'Basic realm=\"Login Required\"'}\n ))\n\n\ndef create_app(test_config=None):\n \"\"\"\n Create and configure an instance of the Flask application.\n\n Some config variable we need to specify in 'instance/config.py'\n\n DEBUG\n SECRET_KEY\n GITHUB_SECRET\n REPO_PATH\n \"\"\"\n fapp = Flask(__name__, instance_relative_config=True)\n\n # ensure the instance folder exists\n try:\n os.makedirs(fapp.instance_path)\n except OSError:\n pass\n\n # a default secret that should be overridden by instance config\n fapp.config.from_mapping(\n SECRET_KEY='this-is-a-secret-key'\n )\n\n if test_config is None:\n if fapp.config['ENV'] == 'local-devel':\n fapp.config.from_object('instance.config.LocalDevelConfig')\n elif fapp.config['ENV'] == 'development':\n fapp.config.from_object('instance.config.DevelConfig')\n else:\n fapp.config.from_object('instance.config.ProductionConfig')\n else:\n # load the test config if passed in\n fapp.config.update(test_config)\n\n logging.config.fileConfig(os.path.join(fapp.instance_path, 'logging.conf'))\n\n # register the database commands\n from app import database\n database.init_app(fapp)\n\n # apply the blueprints to the app\n from app import main, wx_auth, user, question, answer, comment, page\n fapp.register_blueprint(main.bp, url_prefix='/')\n fapp.register_blueprint(wx_auth.bp, url_prefix='/auth')\n fapp.register_blueprint(user.bp, url_prefix='/user')\n fapp.register_blueprint(question.bp, url_prefix='/question')\n fapp.register_blueprint(answer.bp, url_prefix='/answer')\n fapp.register_blueprint(comment.bp, url_prefix='/comment')\n fapp.register_blueprint(page.bp, url_prefix='/page')\n\n # admin\n # set optional bootswatch theme\n from app.database import db, User, Question, Answer, Comment\n from flask_admin import Admin\n from flask_admin.contrib import sqla\n\n # basic auth\n from flask_basicauth import BasicAuth\n basic_auth = BasicAuth(fapp)\n\n class ModelView(sqla.ModelView):\n def is_accessible(self):\n if not basic_auth.authenticate():\n raise AuthException('Not authenticated. Refresh the page.')\n else:\n return True\n\n def inaccessible_callback(self, name, **kwargs):\n return redirect(basic_auth.challenge())\n\n admin = Admin(fapp, name='Admin', template_mode='bootstrap3')\n admin.add_view(ModelView(User, db.session, endpoint='table_user'))\n admin.add_view(ModelView(Question, db.session, endpoint='table_question'))\n admin.add_view(ModelView(Answer, db.session, endpoint='table_answer'))\n admin.add_view(ModelView(Comment, db.session, endpoint='table_comment'))\n\n return fapp\n\n\ndef get_logger():\n flask_env = os.getenv('FLASK_ENV')\n if flask_env == 'local-devel':\n return logging.getLogger('wxforum_devel')\n elif flask_env == 'development':\n return logging.getLogger('wxforum_devel')\n return logging.getLogger('wxforum')\n"
},
{
"alpha_fraction": 0.5235655903816223,
"alphanum_fraction": 0.5348360538482666,
"avg_line_length": 24.019229888916016,
"blob_id": "b6590c6971055e61397d98096e90f65205552ec4",
"content_id": "85b9ba4f5a8143e26577040179177d1b58e821f6",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3904,
"license_type": "permissive",
"max_line_length": 90,
"num_lines": 156,
"path": "/app/question.py",
"repo_name": "kaiwk/forum-wechat",
"src_encoding": "UTF-8",
"text": "from flask import Blueprint, jsonify, request\n\nfrom sqlalchemy.orm.exc import NoResultFound\nfrom sqlalchemy.sql.expression import func\n\nfrom app.database import db, Question, Answer\nfrom . import get_logger\n\n\nlog = get_logger()\n\n\nbp = Blueprint('question', __name__)\n\n\[email protected]('/<int:question_id>', methods=['GET'])\ndef get_question(question_id):\n try:\n question = Question.query.get(question_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no question found'\n })\n\n return jsonify({\n 'status': 200,\n 'code': 0,\n 'msg': 'get success',\n 'question': {\n 'id': question.id,\n 'user_id': question.user_id,\n 'title': question.title,\n 'content': question.content,\n 'closed': question.closed\n }\n })\n\n\[email protected]('/', methods=['POST'])\ndef create_question():\n\n user_id = request.json['user_id']\n title = request.json['title']\n content = request.json['content']\n\n question = Question.save(title, content, user_id)\n\n return jsonify({\n 'status': 200,\n 'code': 0,\n 'msg': 'question created',\n 'question': {\n 'id': question.id,\n 'title': question.title,\n 'content': question.content,\n 'closed': question.closed\n }\n })\n\n\[email protected]('/<int:question_id>', methods=['PUT'])\ndef update_question(question_id):\n title = request.json['title']\n content = request.json['content']\n closed = request.json['closed']\n\n try:\n question = Question.query.get(question_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no question found'\n })\n\n question.update(title, content, closed)\n\n return jsonify({\n 'status': 201,\n 'code': 0,\n 'msg': 'question updated'\n })\n\n\[email protected]('/<int:question_id>/answers', methods=['GET'])\ndef get_answers(question_id):\n try:\n question = Question.query.get(question_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no question found'\n })\n return jsonify({\n 'status': 200,\n 'code': 0,\n 'msg': 'get success',\n 'data': [a.as_dict() for a in question.answers.all()]\n })\n\n\[email protected]('/search', methods=['GET'])\ndef search_question():\n\n fuzzy_match = request.args.get('fuzzy_match')\n\n questions = Question.query.filter(Question.content.contains(fuzzy_match)).all()\n\n if questions:\n return jsonify({\n 'status': 200,\n 'code': 0,\n 'msg': 'get success',\n 'data': [q.as_dict() for q in questions]\n })\n else:\n return jsonify({\n 'status': 204,\n 'code': 1,\n 'msg': 'no matched question'\n })\n\n\[email protected]('/<sort_type>', methods=['GET'])\ndef get_questions(sort_type):\n\n if sort_type == 'random':\n questions = Question.query.order_by(func.rand()).all()\n elif sort_type == 'hot':\n sbq = db.session.query(Answer.question_id, func.count('*').label('answer_count'))\\\n .group_by(Answer.question_id).subquery()\n\n questions = db.session.query(Question, sbq.c.answer_count)\\\n .outerjoin(sbq, Question.id == sbq.c.question_id)\\\n .order_by(sbq.c.answer_count.desc()).all()\n\n questions = [q for q, c in questions]\n else:\n return jsonify({\n 'status': 405,\n 'code': 1,\n 'msg': 'do not support sort type: {}'.format(sort_type)\n })\n\n return jsonify({\n 'status': 200,\n 'code': 0,\n 'msg': 'get success',\n 'data': [q.as_dict() for q in questions]\n })\n\n"
},
{
"alpha_fraction": 0.528938889503479,
"alphanum_fraction": 0.5385851860046387,
"avg_line_length": 21.214284896850586,
"blob_id": "938a6e062a45a449f28d85a8161fa23499ce611a",
"content_id": "7471050adc86a96ac417e1d04eb841f4b49f0595",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1244,
"license_type": "permissive",
"max_line_length": 55,
"num_lines": 56,
"path": "/app/comment.py",
"repo_name": "kaiwk/forum-wechat",
"src_encoding": "UTF-8",
"text": "from flask import Blueprint, jsonify, request\n\nfrom sqlalchemy.orm.exc import NoResultFound\n\nfrom app.database import Comment\nfrom . import get_logger\n\n\nlog = get_logger()\n\n\nbp = Blueprint('comment', __name__)\n\n\[email protected]('/', methods=['POST'])\ndef create_comment():\n user_id = request.json['user_id']\n answer_id = request.json['answer_id']\n content = request.json['content']\n\n comment = Comment.save(content, user_id, answer_id)\n\n return jsonify({\n 'status': 201,\n 'code': 0,\n 'msg': 'comment created',\n 'comment': {\n 'id': comment.id,\n 'content': comment.content\n }\n })\n\n\[email protected]('/<int:comment_id>', methods=['GET'])\ndef get_comment(comment_id):\n try:\n comment = Comment.query.get(comment_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no comment found'\n })\n\n return jsonify({\n 'status': 200,\n 'code': 0,\n 'msg': 'get success',\n 'comment': {\n 'id': comment.id,\n 'user_id': comment.user_id,\n 'answer_id': comment.answer_id,\n 'content': comment.content\n }\n })\n"
},
{
"alpha_fraction": 0.5110132098197937,
"alphanum_fraction": 0.700440526008606,
"avg_line_length": 16.461538314819336,
"blob_id": "f66b2cc0e71803f4252b5acd25da8eb50de71634",
"content_id": "df0c0c9e37846e04bafdce08f43c6872bf2fc2af",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 454,
"license_type": "permissive",
"max_line_length": 26,
"num_lines": 26,
"path": "/requirements.txt",
"repo_name": "kaiwk/forum-wechat",
"src_encoding": "UTF-8",
"text": "-i https://pypi.org/simple\nalembic==1.0.5\ncertifi==2018.11.29\nchardet==3.0.4\nclick==7.0\nflask-admin==1.5.2\nflask-basicauth==0.2.0\nflask-migrate==2.3.1\nflask-sqlalchemy==2.3.2\nflask==1.0.2\nidna==2.8\nitsdangerous==1.1.0\njinja2==2.10\nmako==1.0.7\nmarkupsafe==1.1.0\nmysqlclient==1.3.14\npycryptodome==3.7.2\npyjwt==1.7.1\npython-dateutil==2.7.5\npython-editor==1.0.3\nrequests==2.21.0\nsix==1.12.0\nsqlalchemy==1.2.15\nurllib3==1.24.1\nwerkzeug==0.14.1\nwtforms==2.2.1\n"
},
{
"alpha_fraction": 0.5199999809265137,
"alphanum_fraction": 0.5308108329772949,
"avg_line_length": 22.417720794677734,
"blob_id": "8b7502a2975dab74af3056b8712ffcf0fb3e4eb8",
"content_id": "628d7fe1dec6d853173cded4341794f1f6f36fcb",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1850,
"license_type": "permissive",
"max_line_length": 66,
"num_lines": 79,
"path": "/app/answer.py",
"repo_name": "kaiwk/forum-wechat",
"src_encoding": "UTF-8",
"text": "from flask import Blueprint, jsonify, request\n\nfrom sqlalchemy.orm.exc import NoResultFound\n\nfrom app.database import Answer\nfrom . import get_logger\n\n\nlog = get_logger()\n\n\nbp = Blueprint('answer', __name__)\n\n\[email protected]('/<int:answer_id>', methods=['GET'])\ndef get_answer(answer_id):\n try:\n answer = Answer.query.get(answer_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no answer found'\n })\n\n return jsonify({\n 'status': 200,\n 'code': 0,\n 'msg': 'get success',\n 'answer': {\n 'id': answer.id,\n 'user_id': answer.user_id,\n 'question_id': answer.question_id,\n 'content': answer.content,\n 'anonymous': answer.anonymous\n }\n })\n\n\[email protected]('/<int:answer_id>/comments', methods=['GET'])\ndef get_comments(answer_id):\n try:\n answer = Answer.query.get(answer_id)\n except NoResultFound as e:\n log.error(e)\n return jsonify({\n 'status': 404,\n 'code': 1,\n 'msg': 'no answer found'\n })\n\n return jsonify({\n 'status': 200,\n 'code': 0,\n 'msg': \"get success\",\n 'data': [a.as_dict() for a in answer.comments.all()]\n })\n\n\[email protected]('/', methods=['POST'])\ndef create_answer():\n user_id = request.json['user_id']\n question_id = request.json['question_id']\n anonymous = request.json['anonymous']\n content = request.json['content']\n\n answer = Answer.save(content, anonymous, user_id, question_id)\n\n return jsonify({\n 'status': 201,\n 'code': 0,\n 'msg': 'answer created',\n 'answer': {\n 'id': answer.id,\n 'content': answer.content,\n 'anonymous': answer.anonymous\n }\n })\n"
},
{
"alpha_fraction": 0.6228710412979126,
"alphanum_fraction": 0.6496350169181824,
"avg_line_length": 31.447368621826172,
"blob_id": "d73055e958315dd7602b3ac51e6e0aa2386940a4",
"content_id": "420e178ef577bb10775cb271a773077aaa9eec4e",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1233,
"license_type": "permissive",
"max_line_length": 88,
"num_lines": 38,
"path": "/migrations/versions/a9a574745f9c_.py",
"repo_name": "kaiwk/forum-wechat",
"src_encoding": "UTF-8",
"text": "\"\"\"empty message\n\nRevision ID: a9a574745f9c\nRevises: 5a20064c47d9\nCreate Date: 2018-12-15 00:34:15.012085\n\n\"\"\"\nfrom alembic import op\nimport sqlalchemy as sa\nfrom sqlalchemy.dialects import mysql\n\n# revision identifiers, used by Alembic.\nrevision = 'a9a574745f9c'\ndown_revision = '5a20064c47d9'\nbranch_labels = None\ndepends_on = None\n\n\ndef upgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.add_column('answer', sa.Column('anonymous', sa.Boolean(), nullable=True))\n op.add_column('question', sa.Column('closed', sa.Boolean(), nullable=True))\n op.add_column('user', sa.Column('self_intro', sa.String(length=200), nullable=True))\n op.alter_column('user', 'open_id',\n existing_type=mysql.VARCHAR(collation='utf8mb4_unicode_ci', length=128),\n nullable=False)\n # ### end Alembic commands ###\n\n\ndef downgrade():\n # ### commands auto generated by Alembic - please adjust! ###\n op.alter_column('user', 'open_id',\n existing_type=mysql.VARCHAR(collation='utf8mb4_unicode_ci', length=128),\n nullable=True)\n op.drop_column('user', 'self_intro')\n op.drop_column('question', 'closed')\n op.drop_column('answer', 'anonymous')\n # ### end Alembic commands ###\n"
},
{
"alpha_fraction": 0.7159880995750427,
"alphanum_fraction": 0.7229394316673279,
"avg_line_length": 28.617647171020508,
"blob_id": "05fc8502bdae8dcd842534ec43ace02ea0016759",
"content_id": "8660f28194f12f43f3683d19a23de32e0b27316b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 1007,
"license_type": "permissive",
"max_line_length": 93,
"num_lines": 34,
"path": "/Dockerfile",
"repo_name": "kaiwk/forum-wechat",
"src_encoding": "UTF-8",
"text": "FROM python:3.6.7\n\nRUN adduser --home /home/forum-wechat --shell /bin/bash --disabled-password forum-wechat\n\nWORKDIR /home/forum-wechat\n\nADD docker/apt/sources.list /etc/apt/\nCOPY requirements.txt requirements.txt\n\nRUN apt-get update -y && \\\n apt-get install -y mysql-client && \\\n # Python\n python -m venv venv && \\\n venv/bin/pip install -i https://pypi.tuna.tsinghua.edu.cn/simple pip -U && \\\n venv/bin/pip install -i https://pypi.tuna.tsinghua.edu.cn/simple -r requirements.txt && \\\n venv/bin/pip install -i https://pypi.tuna.tsinghua.edu.cn/simple gunicorn\n\nCOPY app app\nCOPY instance instance\nCOPY migrations migrations\nCOPY docker docker\nRUN chmod +x docker/boot.sh\n\nENV FLASK_APP=app \\\n FLASK_ENV=product\n\nRUN mkdir -p /var/log/flask && chown -R forum-wechat:forum-wechat /var/log/flask\nRUN mkdir -p /var/log/gunicorn && chown -R forum-wechat:forum-wechat /var/log/gunicorn\nRUN chown -R forum-wechat:forum-wechat ./\n\nUSER forum-wechat\n\nEXPOSE 5000\nENTRYPOINT [\"./docker/boot.sh\"]\n"
},
{
"alpha_fraction": 0.6092071533203125,
"alphanum_fraction": 0.6230179071426392,
"avg_line_length": 31.58333396911621,
"blob_id": "10a62fef2a0fbcab9e21d1d3a19e6a9884d9eeb2",
"content_id": "b4d85088435327a9bc4a3d51224899624ed0219f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1955,
"license_type": "permissive",
"max_line_length": 142,
"num_lines": 60,
"path": "/app/wx_auth.py",
"repo_name": "kaiwk/forum-wechat",
"src_encoding": "UTF-8",
"text": "import time\n\nimport requests\nimport jwt\n\nfrom flask import Blueprint, request, jsonify, current_app\nfrom sqlalchemy.orm.exc import NoResultFound, MultipleResultsFound\n\nfrom app.database import User\nfrom . import get_logger\n\n\nbp = Blueprint('wx_auth', __name__)\n\n\nAPI_CODE2SESSION = 'https://api.weixin.qq.com/sns/jscode2session?appid={appid}&secret={secret}&js_code={jscode}&grant_type=authorization_code'\n\n\nlog = get_logger()\n\n\[email protected]('/')\ndef wechat_auth():\n auth_code = request.args.get('auth_code')\n avatar = request.args.get('avatar')\n nickname = request.args.get('nickname')\n\n log.debug('auth_code: %s', auth_code)\n wx_auth_url = API_CODE2SESSION.format(appid=current_app.config['WECHAT_APP_ID'],\n secret=current_app.config['WECHAT_SECRET_KEY'],\n jscode=auth_code)\n res = requests.get(wx_auth_url).json()\n open_id = res['openid']\n log.debug('open_id: %s', open_id)\n try:\n user = User.query.filter_by(open_id=open_id).one()\n log.info('User<%s> already exists', open_id)\n except NoResultFound:\n log.info('User<%s> not exists, now save it', open_id)\n user = User.save(open_id, avatar, nickname)\n return jsonify({'status': 200, 'code': 0, 'msg': 'User has been saved', 'user_id': user.id})\n except MultipleResultsFound:\n return jsonify({'status': 200, 'code': 2, 'msg': 'User has been saved multiple times'})\n\n return jsonify({'status': 200, 'code': 1, 'msg': 'User already exists', 'user_id': user.id})\n\n\ndef create_token(open_id):\n payload = {\n 'iss': 'iss',\n 'iat': int(time.time()),\n 'exp': int(time.time()) + 86400 * 7,\n 'sub': open_id\n }\n token = jwt.encode(payload, current_app.config['JWT_SECRET_KEY'], algorithm='HS256')\n return token\n\n\ndef get_open_id(token):\n jwt.decode(token, current_app.config['JWT_SECRET_KEY'], algorithms='HS256')\n"
},
{
"alpha_fraction": 0.6065573692321777,
"alphanum_fraction": 0.6065573692321777,
"avg_line_length": 12.333333015441895,
"blob_id": "b7045e2a9fad84a12e7b7f39c45ed2d198486c38",
"content_id": "65adf76cdb756c520968b7ec8b41784dff3d5c3b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 122,
"license_type": "permissive",
"max_line_length": 32,
"num_lines": 9,
"path": "/app/main.py",
"repo_name": "kaiwk/forum-wechat",
"src_encoding": "UTF-8",
"text": "from flask import Blueprint\n\n\nbp = Blueprint('main', __name__)\n\n\[email protected]('/')\ndef hello():\n return 'Hello, World!'\n\n\n"
}
] | 16 |
dellius-alexander/Private-Container-Registry-Tool | https://github.com/dellius-alexander/Private-Container-Registry-Tool | 81cea9d4b01255c130c37eedd38cab2402b89e00 | d23a841c37a3ed511d394641d8d1a969dfc00211 | 8b1e2f314935d7d6bfde7ca618d733d6537e6a0e | refs/heads/master | 2023-07-20T13:53:55.437478 | 2021-08-29T23:40:20 | 2021-08-29T23:40:20 | 401,136,786 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.578061044216156,
"alphanum_fraction": 0.5810512900352478,
"avg_line_length": 45.043479919433594,
"blob_id": "9c006b651ac5f6485d0ff02be61db5fb3e5af9c8",
"content_id": "ea1c44dfc63e33d0bf38e2c803528fad813c341f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6354,
"license_type": "no_license",
"max_line_length": 150,
"num_lines": 138,
"path": "/registry.py",
"repo_name": "dellius-alexander/Private-Container-Registry-Tool",
"src_encoding": "UTF-8",
"text": "import os\nimport re\nimport base64\nimport subprocess as sp\nimport requests as req\nfrom pandas import DataFrame\nfrom getpass import getpass\n\n# import kivy\n# kivy.require('1.0.6') # replace with your current kivy version !\n# from kivy.app import App\n# from kivy.uix.label import Label\n\n\n# TODO: setup GUI to get input and display table of results; \n# See kivy for GUI: https://kivy.org/doc/stable/\n# TODO: install password store and configure client environment to use password store\n# TODO: install docker credentials helper in password store\n\n\nclass registry(object):\n #####################################################################\n def __init__(self, raw_url=None or str,username=None or str,passenv=None or str,passwd=None or str) -> None:\n \"\"\"\n ## Docker Private Registry Tool:\n\n Interact with your private docker registry using this tool. \n\n - access registry\n - print contents of private registry\n\n #### Create 3 environmentals in on your system for \n - the private registry url environment variable\n - the private registry username environment variable\n - the private registry password store token environment variable\n\n :param raw_url: the private registry url environment variable\n :param username: the private registry username environment variable\n :param passenv: the private registry password store token environment variable\n :param passwd: the base64 encoded password string\n \"\"\"\n try:\n raw_url = os.environ[raw_url]\n username = os.environ[username]\n passenv = os.environ[passenv]\n # print('URL: {}\\nUSER: {}\\nPASSENV: {}\\n'.format(raw_url,username,passenv))\n self.raw_url = raw_url\n self.username = username\n self.passenv = passenv\n self.passwd = passwd\n # print('password: {}'.format(passwd))\n # super().__init__()\n except OSError as err:\n print('\\nTheir was an error in your environment variable; parameter 2. \\n{}'.format(err))\n except Exception as err: # last line of defense\n print('\\nAn exception has occured.\\n{}'.format(err))\n\n ##################################################################### \n def get_registry(self,raw_url=None,username=None,passenv=None) -> DataFrame:\n \"\"\"\n Gets the contents of your private container registry and organizes them into a table.\n\n This function uses \"pass\" as its password store. It takes your password store path to user password and accesses your password store securely.\n \n :param raw_url: the private registry url environment variable\n :param username: the private registry username environment variable\n :param passenv: the private registry password store token environment variable\n \"\"\"\n tbl = []\n\n raw_url = self.raw_url if raw_url is None else os.environ[raw_url]\n username = self.username if username is None else os.environ[username]\n passenv = self.passenv if passenv is None else os.environ[passenv]\n try:\n ##############################################################\n url = raw_url if re.search('/v2', raw_url) else '{}/v2'.format(raw_url)\n # rauth = passenv if os.environ[passenv] is None else os.environ[passenv]\n rauth = passenv if re.search('docker-credential-helpers',passenv) else os.environ[passenv]\n # print('Docker Credential Token: {}\\n'.format(rauth))\n # we are using a password store to access passwords on needed\n passwd = sp.check_output([\"pass\", rauth])\n passwd = passwd.decode(\"utf-8\")\n # username = input(\"Enter Username: \")\n # passw = getpass(\"Enter Password: \")\n # print(passwd)\n uauth = (username,passwd)\n catelog = '{}/_catalog/'.format(url)\n # print(catelog)\n catelog = req.get(catelog, auth=uauth,timeout=(5, 10)) \n # print(catelog.json())\n for a in catelog.json()['repositories']:\n # print(a)\n item_details = '{0}/{1}/tags/list/'.format(url,a)\n rsp = req.get(item_details, auth=uauth)\n json_rsp = rsp.json()\n # print(json_rsp)\n tbl.append(json_rsp)\n # print('[{} => {}]'.format(json_rsp['name'], json_rsp['tags']))\n # print(tbl)\n df = DataFrame(data=tbl)\n print('\\n{}\\n'.format(df))\n return df\n except req.exceptions.TooManyRedirects as err:\n print('{}'.format(err))\n except req.exceptions.ConnectionError as err:\n print('\\nSorry, unable to connect to {}.\\n\\n{}'.format(raw_url,err)) \n except req.exceptions.URLRequired as err:\n print('{}'.format(err))\n except req.exceptions.StreamConsumedError as err:\n print('{}'.format(err))\n except req.exceptions.ConnectTimeout as err:\n print('{}'.format(err))\n except req.exceptions.HTTPError as err:\n print('{}'.format(err))\n except req.exceptions.RequestException as err:\n print('{}'.format(err))\n except req.exceptions.Timeout as err:\n print('\\nI\\'m so sorry but the server request timed out...\\n\\n{}'.format(err))\n except OSError as err:\n print('\\nTheir was an error in your environment variable; parameter 2. \\n{}'.format(err))\n except KeyError as err:\n print(f'\\nThe environment variable {err} does not match any found in our system.\\n')\n except Exception as err: # last line of defense\n print('\\nAn exception has occured.\\n\\n{}'.format(err))\n\n #####################################################################\n#########################################################################\nif __name__ == '__main__':\n # Create 3 environmentals in on your system for \n # - the private registry url\n # - the private registry username\n # - the private registry password store token\n # Gets a table of your private registry objects\n url = 'PRIVATE_REGISTRY_URL'\n usr = 'PRIVATE_REGISTRY_USER'\n envpass = 'PRIVATE_REGISTRY_AUTH'\n reg = registry(url,usr,envpass)\n reg.get_registry()\n"
}
] | 1 |
jannikluhn/beacon_chain | https://github.com/jannikluhn/beacon_chain | 3c3f00618a07fa2c1788f1380e3103ad0d37118a | dbc72f2119acf7e17757413b797f0a91b3897c79 | 3648c0a072bf07f688279c66eb578e1b33811772 | refs/heads/master | 2020-03-21T02:49:11.135934 | 2018-06-18T15:41:46 | 2018-06-18T15:41:46 | 138,021,751 | 0 | 0 | null | 2018-06-20T11:11:47 | 2018-06-20T05:10:05 | 2018-06-20T01:58:47 | null | [
{
"alpha_fraction": 0.5122548937797546,
"alphanum_fraction": 0.5661764740943909,
"avg_line_length": 23.979591369628906,
"blob_id": "a6dd8bdc7dc1f968882adc2ba303ae406d932626",
"content_id": "ff62b4d63af708ae1d62478ecb0d7d3c93f6be1d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1224,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 49,
"path": "/tests/utils/test_serialization.py",
"repo_name": "jannikluhn/beacon_chain",
"src_encoding": "UTF-8",
"text": "import pytest\n\nfrom beacon_chain.state.active_state import (\n ActiveState,\n)\nfrom beacon_chain.state.partial_crosslink_record import (\n PartialCrosslinkRecord,\n)\nfrom beacon_chain.utils.simpleserialize import (\n serialize,\n deserialize,\n eq,\n)\n\n\[email protected](\n 'value, typ, data',\n [\n (5, 'int8', b'\\x05'),\n (2**32-3, 'int40', b'\\x00\\xff\\xff\\xff\\xfd'),\n (b'\\x35'*20, 'address', b'\\x35'*20),\n (b'\\x35'*32, 'hash32', b'\\x35'*32),\n (b'cow', 'bytes', b'\\x00\\x00\\x00\\x03cow'),\n ]\n)\ndef test_basic_serialization(value, typ, data):\n assert serialize(value, typ) == data\n assert deserialize(data, typ) == value\n\n\ndef test_active_state_serialization():\n s = ActiveState()\n ds = deserialize(serialize(s, type(s)), type(s))\n assert eq(s, ds)\n\n s = ActiveState(\n partial_crosslinks=[\n PartialCrosslinkRecord(\n shard_id=42,\n shard_block_hash=b'\\x55'*32,\n voter_bitfield=b'31337dawg'\n )\n ],\n height=555,\n randao=b'\\x88'*32,\n balance_deltas=[5, 7, 9, 579] + [3] * 333\n )\n ds = deserialize(serialize(s, type(s)), type(s))\n assert eq(s, ds)\n"
}
] | 1 |
PotionSocial/python-twitter-example | https://github.com/PotionSocial/python-twitter-example | 706d7010ff31d45a4e56148e224301876ed5ee62 | 5aeb56d2caf71a9a4e73af01d4923e9055e561da | 90fc1ab9c6ba3bb90df9501f7ff4a9b80e0d066c | refs/heads/master | 2020-12-19T01:48:33.770634 | 2020-01-22T16:11:53 | 2020-01-31T10:25:13 | 235,584,135 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5963401794433594,
"alphanum_fraction": 0.5995694398880005,
"avg_line_length": 33.407405853271484,
"blob_id": "4151b5ff53fa3383dcc377764f2665341776cfef",
"content_id": "865957d2d4c732885dd25879a5f73cc59fcd2078",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 929,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 27,
"path": "/statuses/forms.py",
"repo_name": "PotionSocial/python-twitter-example",
"src_encoding": "UTF-8",
"text": "from django import forms\nfrom django.conf import settings\nimport requests\n\n\nclass StatusForm(forms.Form):\n message = forms.CharField(\n label='subject', widget=forms.Textarea(attrs={'class': \"form-control\", 'rows': 3, 'placeholder': \"What are you thinking?\"}))\n\n\nclass UserSelectorForm(forms.Form):\n url = settings.PROJECT_URL + '/public-api/v1/users'\n response = requests.get(url, headers={\n 'API-KEY': settings.API_KEY,\n 'API-SECRET': settings.API_SECRET,\n 'Content-Type': 'application/json',\n })\n json_response = response.json()\n user_choices = map(\n lambda u: [u['id'], u['nickname']], json_response['items'])\n\n user_id = forms.CharField(\n label='',\n max_length=3,\n widget=forms.Select(choices=user_choices, attrs={'onchange': 'user_selector_form.submit();',\n 'class': \"form-control\"}),\n )\n"
},
{
"alpha_fraction": 0.6721311211585999,
"alphanum_fraction": 0.6721311211585999,
"avg_line_length": 41.230770111083984,
"blob_id": "0c8b161965da58e5769f33ffec70c0656fa01311",
"content_id": "f093e4d622b30ba53d2667b2fd8ffe3f16ba3f2b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 549,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 13,
"path": "/statuses/urls.py",
"repo_name": "PotionSocial/python-twitter-example",
"src_encoding": "UTF-8",
"text": "from django.urls import path\nfrom . import views\n\nurlpatterns = [\n path(\"\", views.statuses_index, name=\"statuses_index\"),\n path(\"create-status/\", views.create_status, name=\"create_status\"),\n path(\"delete-status/<str:status_id>\",\n views.delete_status, name=\"delete_status\"),\n path(\"like-status/<str:status_id>\", views.like_status, name=\"like_status\"),\n path(\"unlike-status/<str:status_id>\",\n views.unlike_status, name=\"unlike_status\"),\n path(\"select-user/\", views.select_current_user, name=\"select_current_user\"),\n]\n"
},
{
"alpha_fraction": 0.6586049795150757,
"alphanum_fraction": 0.6610585451126099,
"avg_line_length": 30.700000762939453,
"blob_id": "315f8cfdc4aa69a48a001c0e2d5bea401ff9f463",
"content_id": "b18c65e7ff55a1d5589b55c9e87ec7ba4d8191d4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2853,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 90,
"path": "/statuses/views.py",
"repo_name": "PotionSocial/python-twitter-example",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render, redirect\nfrom django.conf import settings\nimport requests\nfrom .forms import StatusForm, UserSelectorForm\n\ndefault_headers = {\n 'API-KEY': settings.API_KEY,\n 'API-SECRET': settings.API_SECRET,\n 'Content-Type': 'application/json',\n}\n\n\ndef get_user_id(request):\n # Get current user id or sets it with latest available user\n if \"current_user_id\" in request.session:\n return request.session['current_user_id']\n else:\n url = settings.PROJECT_URL + '/public-api/v1/users'\n response = requests.get(url, headers=default_headers)\n json_response = response.json()\n users = json_response['items']\n request.session['current_user_id'] = users[0]['id']\n\n\ndef select_current_user(request):\n if request.POST:\n user_id = request.POST.get('user_id')\n request.session['current_user_id'] = user_id\n\n return redirect('statuses_index')\n\n\ndef statuses_index(request):\n get_user_id(request)\n url = settings.PROJECT_URL + '/public-api/v1/statuses'\n\n status_form = StatusForm(None)\n user_selector_form = UserSelectorForm(\n initial={'user_id': request.session['current_user_id']})\n\n response = requests.get(\n url + f\"?for_user_id={request.session['current_user_id']}\", headers=default_headers)\n json_response = response.json()\n statuses = json_response['items']\n print(statuses)\n\n return render(request, 'statuses_index.html', locals())\n\n\ndef create_status(request):\n get_user_id(request)\n\n url = settings.PROJECT_URL + '/public-api/v1/statuses'\n form = StatusForm(request.POST or None)\n if form.is_valid():\n message = form.cleaned_data['message']\n form_response = requests.post(url, headers=default_headers, json={\n 'message': message,\n 'user_id': request.session['current_user_id']\n })\n\n return redirect('statuses_index')\n\n\ndef delete_status(request, status_id):\n url = f'{settings.PROJECT_URL}/public-api/v1/statuses/{status_id}'\n response = requests.delete(url, headers=default_headers)\n json_response = response.json()\n\n return redirect('statuses_index')\n\n\ndef like_status(request, status_id):\n url = f'{settings.PROJECT_URL}/public-api/v1/statuses/{status_id}/like'\n response = requests.put(url, headers=default_headers, json={\n 'user_id': request.session['current_user_id']})\n json_response = response.json()\n\n print(json_response)\n\n return redirect('statuses_index')\n\n\ndef unlike_status(request, status_id):\n url = f'{settings.PROJECT_URL}/public-api/v1/statuses/{status_id}/unlike'\n response = requests.put(url, headers=default_headers, json={\n 'user_id': request.session['current_user_id']})\n json_response = response.json()\n\n return redirect('statuses_index')\n"
},
{
"alpha_fraction": 0.7452547550201416,
"alphanum_fraction": 0.7452547550201416,
"avg_line_length": 33.517242431640625,
"blob_id": "b0005d805a9eeba33b3ac0970eafe716a5b78653",
"content_id": "bf7017af21b5c76a1580bf40ec34e9d69179cfcd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1001,
"license_type": "no_license",
"max_line_length": 292,
"num_lines": 29,
"path": "/README.md",
"repo_name": "PotionSocial/python-twitter-example",
"src_encoding": "UTF-8",
"text": "# Potion Social NodeJS Twitter like\n\nThis example built with Django and Python, shows you how you can use [Potion Social API](https://potion.social/ \"Potion Social API\") to build a twitter like stream. It is a really basic app allowing you to post a status, list them, like them, delete them and change your current user session.\n\n## Install\n\n`python -m pip install`\n\n## Configure\n\nOpen `python_twitter_example/settings_local_template.py` and fill it with your Potion Social Credentials, if you do not own credentials, create a free account on [Potion Social API Builder](https://api.potion.social/ \"Potion Social API Builder\").\n\nFinal `settings_local.py` file should look a bit like this :\n\n```\nPROJECT_URL = \"https://mynetwork.potion.social\"\nAPI_KEY = \"wDKAcGDe5SDSqZPlSd4G6Q\"\nAPI_SECRET = \"cSJq56ZahNT_ZYOsUle43Q\"\n```\n\nOnce done, rename the file to `settings_local.py` and run the app.\n\n## Run\n\n`python manage.py runserver`\n\n## Extend\n\nDo not hesitate to extend this example or to send us your application using Potion Social API.\n"
},
{
"alpha_fraction": 0.7155172228813171,
"alphanum_fraction": 0.7155172228813171,
"avg_line_length": 37.66666793823242,
"blob_id": "b65f279fe4c8a4747895c1f450b9f3aae6e5805e",
"content_id": "0677c0bb5e1f0fa12576eb94b08751b1e46d83f9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 116,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 3,
"path": "/python_twitter_example/settings_local_template.py",
"repo_name": "PotionSocial/python-twitter-example",
"src_encoding": "UTF-8",
"text": "PROJECT_URL = \"https://YOUR_PROJECT_NAME.potion.social\"\nAPI_KEY = \"YOUR_API_KEY\"\nAPI_SECRET = \"YOUR_API_SECRET_KEY\"\n"
}
] | 5 |
kkshmz/python-utils | https://github.com/kkshmz/python-utils | 3b223925a30b4d724c1cc834e4a330694d1d84e4 | 7d2bb6be0b943b1f272c5587f7f1abee4325465c | 95731948a067ae1ed8f561a24557a09f016f2c12 | refs/heads/master | 2020-09-23T06:57:49.130175 | 2019-12-01T06:09:09 | 2019-12-01T06:09:09 | 205,132,335 | 0 | 0 | MIT | 2019-08-29T09:51:02 | 2019-08-29T06:12:50 | 2019-08-29T06:12:48 | null | [
{
"alpha_fraction": 0.5248697400093079,
"alphanum_fraction": 0.5409758687019348,
"avg_line_length": 29.38129425048828,
"blob_id": "9a947f7717a08887b314cdfd6533e7be956d37cf",
"content_id": "33ac10e22de02cfd124100ffdf32d9366f480590",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4222,
"license_type": "permissive",
"max_line_length": 123,
"num_lines": 139,
"path": "/ffmpeg.py",
"repo_name": "kkshmz/python-utils",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport subprocess as sp\nimport os\nimport time\nDEVNULL = open(os.devnull, 'w')\n\n# attempts to handle all float/integer conversions with and without normalizing\ndef convert_bit_depth(y, in_type, out_type, normalize=False):\n in_type = np.dtype(in_type).type\n out_type = np.dtype(out_type).type\n \n if normalize:\n peak = np.abs(y).max()\n if peak == 0:\n normalize = False\n \n if issubclass(in_type, np.floating):\n if normalize:\n y /= peak\n if issubclass(out_type, np.integer):\n y *= np.iinfo(out_type).max\n y = y.astype(out_type)\n elif issubclass(in_type, np.integer):\n if issubclass(out_type, np.floating):\n y = y.astype(out_type)\n if normalize:\n y /= peak\n elif issubclass(out_type, np.integer):\n in_max = peak if normalize else np.iinfo(in_type).max\n out_max = np.iinfo(out_type).max\n if out_max > in_max:\n y = y.astype(out_type)\n y *= (out_max / in_max)\n elif out_max < in_max:\n y /= (in_max / out_max)\n y = y.astype(out_type)\n return y\n\n# load_audio can not detect the input type\n# could use a command like this with sr=None or detect=True:\n# ffprobe -hide_banner \\\n# -loglevel fatal \\\n# -show_error \\\n# -show_format \\\n# -show_streams \\\n# -print_format json \\\n# -i fn\ndef auread(filename, sr=44100, mono=False, normalize=True, in_type=np.int16, out_type=np.float32):\n in_type = np.dtype(in_type).type\n out_type = np.dtype(out_type).type\n channels = 1 if mono else 2\n format_strings = {\n np.float64: 'f64le',\n np.float32: 'f32le',\n np.int16: 's16le',\n np.int32: 's32le',\n np.uint32: 'u32le'\n }\n format_string = format_strings[in_type]\n command = [\n 'ffmpeg',\n '-i', filename,\n '-f', format_string,\n '-acodec', 'pcm_' + format_string,\n '-ar', str(sr),\n '-ac', str(channels),\n '-']\n p = sp.Popen(command, stdout=sp.PIPE, stderr=DEVNULL)\n raw, err = p.communicate()\n audio = np.frombuffer(raw, dtype=in_type)\n \n if channels > 1:\n audio = audio.reshape((-1, channels)).transpose()\n\n if audio.size == 0:\n return audio.astype(out_type), sr\n \n audio = convert_bit_depth(audio, in_type, out_type, normalize)\n\n return audio, sr\n\ndef auwrite(fn, audio, sr, channels=1):\n format_strings = {\n 'float64': 'f64le',\n 'float32': 'f32le',\n 'int16': 's16le',\n 'int32': 's32le',\n 'uint32': 'u32le'\n }\n format_strings = {np.dtype(key): value for key,value in format_strings.items()}\n format_string = format_strings[audio.dtype]\n command = [\n 'ffmpeg',\n '-y',\n '-ar', str(sr),\n '-f', format_string,\n '-i', 'pipe:',\n fn]\n p = sp.Popen(command, stdin=sp.PIPE, stdout=None, stderr=None)\n raw, err = p.communicate(audio.tobytes())\n \nimport ffmpeg\n\nclass VideoWriter:\n def __init__(self, fn, vcodec='libx264', fps=60, in_pix_fmt='rgb24', out_pix_fmt='yuv420p'):\n self.fn = fn\n self.vcodec = vcodec\n self.fps = fps\n self.process = None\n self.in_pix_fmt = in_pix_fmt\n self.out_pix_fmt = out_pix_fmt\n \n def add(self, frame):\n if self.process is None:\n h,w = frame.shape[:2]\n self.process = (\n ffmpeg\n .input('pipe:', format='rawvideo', pix_fmt=self.in_pix_fmt, s='{}x{}'.format(w, h), framerate=self.fps)\n .output(self.fn, pix_fmt=self.out_pix_fmt, vcodec=self.vcodec)\n .overwrite_output()\n .run_async(pipe_stdin=True)\n )\n self.process.stdin.write(\n frame\n .astype(np.uint8)\n .tobytes()\n )\n\n def close(self):\n if self.process is None:\n return\n self.process.stdin.close()\n self.process.wait()\n\ndef vidwrite(fn, images, **kwargs):\n writer = VideoWriter(fn, **kwargs)\n for image in images:\n writer.add(image)\n writer.close()"
}
] | 1 |
thinkl33t/mb-ddns | https://github.com/thinkl33t/mb-ddns | f7c948ea639f6aeb5c17466e1ce629848e49df19 | c8e8631a34afa50ff90efcf0f0f5c194a6fdee90 | 38e44518739185907865814d0e999f1d45c70eab | refs/heads/master | 2020-04-08T15:52:22.864405 | 2018-11-29T16:08:54 | 2018-11-29T16:08:54 | 159,495,355 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5630252361297607,
"alphanum_fraction": 0.5770308375358582,
"avg_line_length": 24.5,
"blob_id": "dfa41cd59c06eaa0ab3f1b590164ea1b604149f9",
"content_id": "b95f6e570326000f5c79e31cc7e34f05efabf3f3",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 357,
"license_type": "permissive",
"max_line_length": 54,
"num_lines": 14,
"path": "/setup.py",
"repo_name": "thinkl33t/mb-ddns",
"src_encoding": "UTF-8",
"text": "from setuptools import setup\n\nsetup(name='mbddns',\n version='0.1.2',\n description='Mythic Beasts Dynamic DNS updater',\n url='https://github.com/thinkl33t/mb-ddns',\n author='Bob Clough',\n author_email='[email protected]',\n license='MIT',\n packages=['mbddns'],\n install_requires=[\n 'aiohttp',\n ],\n zip_safe=False)\n"
},
{
"alpha_fraction": 0.5477477312088013,
"alphanum_fraction": 0.5531531572341919,
"avg_line_length": 31.647058486938477,
"blob_id": "3263338bd81d0a132958f616920f4dd17c691c53",
"content_id": "8d9950ce2e305062ccde1fe90dfaf76a3b44e863",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1110,
"license_type": "permissive",
"max_line_length": 101,
"num_lines": 34,
"path": "/mbddns/__init__.py",
"repo_name": "thinkl33t/mb-ddns",
"src_encoding": "UTF-8",
"text": "import asyncio\nimport aiohttp\nimport logging\n\n_LOGGER = logging.getLogger(__name__)\n\nasync def update(domain, password, host, ttl=60, session=None):\n data = {\n 'domain': domain,\n 'password': password,\n 'command': \"REPLACE {} {} A DYNAMIC_IP\".format(host, ttl)\n }\n\n async with session or aiohttp.ClientSession() as session:\n try:\n resp = await asyncio.gather(session.post('https://dnsapi4.mythic-beasts.com/',data=data))\n body = await resp[0].text()\n\n if body.startswith(\"REPLACE\"):\n _LOGGER.debug(\"Updating Mythic Beasts successful: %s\", body)\n return True\n\n if body.startswith(\"ERR\"):\n _LOGGER.error(\"Updating Mythic Beasts failed: %s\",\n body.partition(' ')[2])\n\n if body.startswith(\"NREPLACE\"):\n _LOGGER.warning(\"Updating Mythic Beasts failed: %s\",\n body.partition(';')[2])\n\n except Exception as e:\n _LOGGER.error(\"Updating Mythic Beasts failed: %s\", e)\n\n return False\n"
},
{
"alpha_fraction": 0.7954545617103577,
"alphanum_fraction": 0.7954545617103577,
"avg_line_length": 21,
"blob_id": "318999ddc50356f99d224e2c5dd872b57f5a50bc",
"content_id": "2e8ca82e9fcaa9bf7d5afe25e124e5b190a98fda",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 44,
"license_type": "permissive",
"max_line_length": 33,
"num_lines": 2,
"path": "/README.md",
"repo_name": "thinkl33t/mb-ddns",
"src_encoding": "UTF-8",
"text": "# mb-ddns\nMythic Beasts Dynamic Dns Updater\n"
}
] | 3 |
zhuojg/style-cluster | https://github.com/zhuojg/style-cluster | 0b480680e21f82ed67e9f053bdf2670f7f4650c1 | 121c5d1900024c4b88103c4042bb2e588a35899b | a3e1ad41ad4ba8407296d559c5de514e375432ea | refs/heads/master | 2022-06-14T17:40:16.765914 | 2020-02-09T10:43:47 | 2020-02-09T10:43:47 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7906976938247681,
"alphanum_fraction": 0.7906976938247681,
"avg_line_length": 7.777777671813965,
"blob_id": "d5725e39483e306323106a666894210ca974ef05",
"content_id": "979897d9c80c7f61ef0386bcd5fb5873b5272651",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 86,
"license_type": "no_license",
"max_line_length": 12,
"num_lines": 9,
"path": "/requirements.txt",
"repo_name": "zhuojg/style-cluster",
"src_encoding": "UTF-8",
"text": "matplotlib\r\nPillow\r\njoblib\r\nfaiss-cpu\r\nscikit-learn\r\nconfig\r\ntorch\r\ntorchvision\r\nnumpy"
},
{
"alpha_fraction": 0.5629869103431702,
"alphanum_fraction": 0.584457516670227,
"avg_line_length": 32.3986930847168,
"blob_id": "6bfdc793e6da80007ecbb287f15b6c0f0d198e22",
"content_id": "f41923d70e78dbf6bf51198d26f8429bf389a1e5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5263,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 153,
"path": "/style_model.py",
"repo_name": "zhuojg/style-cluster",
"src_encoding": "UTF-8",
"text": "import torch.nn as nn\r\nimport torch.nn.functional as F\r\nfrom torchvision import models\r\nimport torch\r\nimport numpy as np\r\nfrom torchvision.transforms import transforms\r\nimport time\r\nfrom PIL import Image\r\nfrom PIL import ImageFile\r\nfrom sklearn.preprocessing import normalize as sknormalize\r\nfrom utils import rmac\r\n\r\n\r\nImageFile.LOAD_TRUNCATED_IMAGES = True\r\n\r\ndevice = torch.device(\"cuda:0\" if torch.cuda.is_available() else \"cpu\")\r\n\r\n\r\ndef image_loader(image_name):\r\n im = Image.open(image_name)\r\n im = im.convert('RGB')\r\n im_size_hw = np.array(im.size[::-1])\r\n\r\n max_side_lengths = [800]\r\n images = []\r\n for max_side_length in max_side_lengths:\r\n ratio = float(max_side_length) / np.max(im_size_hw)\r\n new_size = tuple(np.round(im_size_hw * ratio.astype(float)).astype(np.int32))\r\n # fake batch dimension required to fit network's input dimensions\r\n loader = transforms.Compose(\r\n [\r\n transforms.Resize(new_size),\r\n transforms.ToTensor(),\r\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\r\n ]\r\n )\r\n image = loader(im).unsqueeze(0)\r\n image_cuda = image.to(device, torch.float)\r\n images.append(image)\r\n return images\r\n\r\n\r\ndef image_loader_eval(image_name):\r\n im = Image.open(image_name)\r\n im = im.convert('RGB')\r\n im_size_hw = np.array(im.size[::-1])\r\n\r\n max_side_lengths = [550, 800, 1050]\r\n images = []\r\n for max_side_length in max_side_lengths:\r\n ratio = float(max_side_length) / np.max(im_size_hw)\r\n new_size = tuple(np.round(im_size_hw * ratio.astype(float)).astype(np.int32))\r\n # fake batch dimension required to fit network's input dimensions\r\n loader = transforms.Compose(\r\n [\r\n transforms.Resize(new_size),\r\n transforms.ToTensor(),\r\n transforms.Normalize([0.485, 0.456, 0.406], [0.229, 0.224, 0.225])\r\n ]\r\n )\r\n image = loader(im).unsqueeze(0)\r\n images.append(image)\r\n return images\r\n\r\n\r\nclass SiameseNetwork(nn.Module):\r\n def __init__(self, pretrained=True):\r\n super(SiameseNetwork, self).__init__()\r\n self.pretrained_model = models.resnet34(pretrained=pretrained)\r\n self.cnn1 = nn.Sequential(*list(self.pretrained_model.children())[:-2])\r\n self.pool = rmac\r\n self.normal = nn.functional.normalize\r\n\r\n def forward_once(self, x):\r\n x = self.cnn1(x)\r\n x = self.pool(x)\r\n return self.normal(x, ).squeeze(-1).squeeze(-1)\r\n\r\n def style_vec(self, x):\r\n x = self.cnn1(x)\r\n return x\r\n\r\n def forward(self, input1, input2):\r\n output1 = self.forward_once(input1)\r\n output2 = self.forward_once(input2)\r\n\r\n return output1, output2\r\n\r\n def __repr__(self):\r\n return self.__class__.__name__ + '(resnet50+rmac+l2n)'\r\n\r\n\r\nclass StyleModel:\r\n def __init__(self, finetuning=False, file_path=None):\r\n if not finetuning:\r\n self.net = SiameseNetwork().to(device).eval()\r\n else:\r\n net = SiameseNetwork(False).to(device)\r\n net.load_state_dict(torch.load(file_path))\r\n self.net = net.eval()\r\n\r\n def normalize(self, x, copy=False):\r\n \"\"\"\r\n A helper function that wraps the function of the same name in sklearn.\r\n This helper handles the case of a single column vector.\r\n \"\"\"\r\n if type(x) == np.ndarray and len(x.shape) == 1:\r\n return np.squeeze(sknormalize(x.reshape(1, -1), copy=copy))\r\n else:\r\n return sknormalize(x, copy=copy)\r\n\r\n def extract_style_feature(self, image_path):\r\n imgs = image_loader(image_path)\r\n final_feature = []\r\n for img in imgs:\r\n features = self.net.style_vec(img.to(device)).data.cpu().numpy()\r\n features = np.transpose(features, [0, 2, 3, 1])\r\n features = self.get_style_gram(features)\r\n final_feature.append(features)\r\n\r\n return self.normalize(np.array(final_feature, dtype=np.float32).sum(axis=0)).squeeze()\r\n\r\n def extract_feature(self, image_path):\r\n return self.extract_style_feature(image_path)\r\n\r\n def get_style_gram(self, style_features):\r\n \"\"\"\r\n get the gram matrix\r\n :param style_features:\r\n :return:\r\n \"\"\"\r\n _, height, width, channel = style_features.shape[0], style_features.shape[1], style_features.shape[2], \\\r\n style_features.shape[3]\r\n size = height * width * channel\r\n style_features = np.reshape(style_features, (-1, channel))\r\n style_features_t = np.transpose(style_features)\r\n style_gram = np.matmul(style_features_t, style_features) / size\r\n gram = style_gram.astype(np.float32)\r\n vector = []\r\n for i in range(len(gram)):\r\n vector.extend(gram[i][0:i + 1])\r\n vector = self.normalize(np.array(vector, dtype=np.float32))\r\n return vector\r\n\r\n\r\nif __name__ == '__main__':\r\n model = StyleModel()\r\n since = time.time()\r\n feature = model.extract_feature(\"404.jpg\")\r\n\r\n print(feature)\r\n print(len(feature))\r\n print(np.dot(feature, feature.T))\r\n"
},
{
"alpha_fraction": 0.5991735458374023,
"alphanum_fraction": 0.6049586534500122,
"avg_line_length": 34.66666793823242,
"blob_id": "aed71c5bff7fb2f6b11ad4716ab719179497f4bc",
"content_id": "5dab099a3a00db8aef2b1f3df4553ce013a1c9b8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3630,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 99,
"path": "/feature.py",
"repo_name": "zhuojg/style-cluster",
"src_encoding": "UTF-8",
"text": "import numpy as np\r\nimport joblib\r\nfrom sklearn.decomposition import PCA\r\nimport os\r\nfrom style_model import StyleModel\r\nimport time\r\nfrom utils import time_convert, get_image_list, get_image_list_recursion\r\nimport argparse\r\n\r\n\r\ndef get_style_feature(model, image_path, result_path, cnt=0):\r\n if not os.path.exists(result_path):\r\n os.makedirs(result_path)\r\n \r\n image_path = get_image_list_recursion(image_path)\r\n\r\n # only save the file name and category name\r\n new_image_path = [item.split('/')[-2] + '/' + item.split('/')[-1] for item in image_path]\r\n image_path = new_image_path\r\n\r\n cnn_feature_path = os.path.join(result_path, 'cnn_features.pkl')\r\n\r\n step = 200 # save result and print status every 200 images\r\n\r\n # if the cnn_feature exists, start from the stop position\r\n if os.path.exists(cnn_feature_path):\r\n images, features = joblib.load(cnn_feature_path)\r\n start_index = len(images)\r\n print('start index: %s' % str(start_index))\r\n else:\r\n features = []\r\n images = []\r\n start_index = 0\r\n\r\n for i, path in enumerate(image_path):\r\n if i < start_index:\r\n continue\r\n \r\n try:\r\n features.append(model.extract_feature(path))\r\n images.append(path)\r\n except Exception as e:\r\n print('get {} image feature failed: '.format(path), e)\r\n \r\n if i - start_index > 0 and i % 10 == 0:\r\n print('%d / %d' % (i, len(image_path)))\r\n \r\n if i >= cnt > 0:\r\n break\r\n \r\n if i > 0 and i % step == 0:\r\n features = np.array(features)\r\n joblib.dump((images, features), cnn_feature_path)\r\n \r\n features = np.array(features)\r\n return images, features\r\n\r\n\r\ndef pca(images, features, n_components, result_path):\r\n print('Constructing PCA model...')\r\n # construct pca model\r\n model = PCA(n_components=n_components, whiten=False, copy=False)\r\n print('Fitting the features...')\r\n model.fit(features)\r\n joblib.dump(model, os.path.join(result_path, 'pca_result.pkl'))\r\n print('Result stored in %s' % os.path.join(result_path, 'pca_result.pkl'))\r\n\r\n print('Processing features using PCA...')\r\n # process features using PCA\r\n pca_features = model.fit_transform(features)\r\n joblib.dump((images, pca_features), os.path.join(result_path, 'pca_features.pkl'))\r\n print('Result stored in %s' % os.path.join(result_path, 'pca_features.pkl'))\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(description='Generate features.')\r\n flag_parser = parser.add_mutually_exclusive_group(required=False)\r\n flag_parser.add_argument('--exist', dest='exist', action='store_true',\r\n help='use existed cnn features to calculate pca features')\r\n flag_parser.add_argument('--no-exist', dest='exist', action='store_false',\r\n help='run get_style_feature function')\r\n parser.set_defaults(exist=False)\r\n\r\n parser.add_argument('--result_path', type=str, help='path to result files', required=True)\r\n parser.add_argument('--data_path', type=str, help='path to data', required=True)\r\n\r\n args = parser.parse_args()\r\n\r\n if args.exist:\r\n images, features = joblib.load(os.path.join(args.result_path, 'cnn_features.pkl'))\r\n else:\r\n style_model = StyleModel()\r\n images, features = get_style_feature(\r\n model=style_model,\r\n image_path=args.data_path,\r\n result_path=args.result_path\r\n )\r\n\r\n pca(images, features, 1024, args.result_path)\r\n"
},
{
"alpha_fraction": 0.5827389359474182,
"alphanum_fraction": 0.589514970779419,
"avg_line_length": 34.415584564208984,
"blob_id": "fbc60a209683addff37b8c26fb1fa5146703ac46",
"content_id": "608983da0c00cfe5c061826a5c0493029dde129a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2804,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 77,
"path": "/demo.py",
"repo_name": "zhuojg/style-cluster",
"src_encoding": "UTF-8",
"text": "import style_model\r\nimport matplotlib.pyplot as plt\r\nfrom PIL import Image\r\nimport joblib\r\nimport faiss\r\nimport os\r\nfrom sklearn.cluster import DBSCAN\r\nimport shutil\r\nimport argparse\r\n\r\n\r\nclass Cluster:\r\n def __init__(self, feature_path, center_num, num_per_category):\r\n print('Start clustering...')\r\n self.image_paths, self.features = joblib.load(\r\n os.path.join(feature_path)\r\n )\r\n self.features = self.features.astype('float32')\r\n self.center_num = center_num\r\n d = self.features.shape[1]\r\n\r\n # construct kmeans using faiss\r\n self.kmeans = faiss.Kmeans(d, self.center_num, niter=100, verbose=True)\r\n self.kmeans.train(self.features)\r\n self.index = faiss.IndexFlatL2(d)\r\n self.index.add(self.features)\r\n\r\n # get the results\r\n # D contains the squared L2 distances\r\n # I contains the nearest neighbors for each centroid\r\n self.D, self.I = self.index.search(self.kmeans.centroids, num_per_category)\r\n\r\n self.img_paths = []\r\n self.scores = []\r\n # so we enumerate I, to get every centroid's neighbors\r\n for i, item in enumerate(self.I):\r\n temp_paths = []\r\n temp_scores = []\r\n for j, index in enumerate(item):\r\n temp_paths.append(self.image_paths[index])\r\n temp_scores.append(self.D[i][j])\r\n self.img_paths.append(temp_paths)\r\n self.scores.append(temp_scores)\r\n\r\n print('Job done.')\r\n\r\n def show_in_pic(self, save_path, data_path):\r\n \"\"\"\r\n generate a big picture for every cluster using images in this cluster\r\n\r\n :param save_path:\r\n :return:\r\n \"\"\"\r\n if not os.path.exists(save_path):\r\n os.makedirs(save_path)\r\n\r\n for i, cluster in enumerate(self.img_paths):\r\n plt.figure()\r\n for j, img in enumerate(cluster):\r\n plt.subplot(10, 5, j + 1)\r\n\r\n image = Image.open(os.path.join(data_path, img))\r\n image = image.convert('RGB')\r\n plt.imshow(image)\r\n plt.axis('off')\r\n plt.savefig(os.path.join(save_path, '%s.png' % str(i)), dpi=600)\r\n\r\n\r\nif __name__ == '__main__':\r\n parser = argparse.ArgumentParser(description='Generate features.')\r\n parser.add_argument('--data_path', type=str, help='path to data', required=True)\r\n parser.add_argument('--feature_path', type=str, help='path to pca feature', required=True)\r\n parser.add_argument('--save_path', type=str, help='path to save result', required=True)\r\n args = parser.parse_args()\r\n\r\n c = Cluster(feature_path=args.feature_path, center_num=15, num_per_category=50)\r\n c.show_in_pic(save_path=args.save_path, data_path=args.data_path)\r\n"
},
{
"alpha_fraction": 0.6746463775634766,
"alphanum_fraction": 0.6849836707115173,
"avg_line_length": 33.346153259277344,
"blob_id": "7fada1d22fc93bbf2137a8ad991dcfc95e18b2e6",
"content_id": "b93a6708dc731fa48b5f80b752e23199c2a0dfa3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1838,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 52,
"path": "/README.md",
"repo_name": "zhuojg/style-cluster",
"src_encoding": "UTF-8",
"text": "# Design Style Cluster with ResNet34 and K-means\r\n\r\nThis project tries to extract image features with CNN and cluster them with K-means. \r\nThe result seems to be reasonable with data from Tongji Tezign Design A.I Lab (<https://sheji.ai).>\r\n\r\n## Setup\r\n* Create python virtual environment\r\n```shell script\r\npython3 -m venv venv\r\nsource venv/bin/activate\r\npip install -r requirements.txt\r\n```\r\n\r\n## Run Demo\r\n* Download preprocessed features `pca_features.pkl` from \r\nhttps://drive.google.com/open?id=1yeMFaNly7pZRGcTWPEmAvHZ2pY4gSRJ7 \r\nand move it to `./result`\r\n* Download data from \r\nhttps://drive.google.com/drive/folders/1cdYHtQyOMfoZCpaXiiMcRK-mzH4NqLEG?usp=sharing \r\n* Unzip data to `./` and rename the folder to `data` \r\n* Run demo as follow, remember to change args according to your environment. \r\n```shell script\r\npython demo.py --data_path './data' --feature_path './result/pca_features.pkl' --save_path './result'\r\n```\r\n\r\n| args | description | \r\n| :------ | :------ | \r\n| data_path | path to data |\r\n| feature_path | path to feature file |\r\n| save_path | path to save result | \r\n\r\n* This figure shows images from 1 of 15 clusters. \r\n\r\n\r\n\r\n## Create your own features\r\n* You can also create your own image style features using feature.py.\r\n* Run feature.py as follow, remember to change args according to your environment.\r\n```shell script\r\npython feature.py --result_path './result' --data_path './data'\r\n```\r\n\r\n| args | description | \r\n| :------ | :------ | \r\n| data_path | path to data |\r\n| result_path | path to save result |\r\n\r\n* After the feature is created, you can run demo.py to check the result. \r\n\r\n## Reference\r\n\r\n[1] Gatys L A , Ecker A S , Bethge M . A Neural Algorithm of Artistic Style[J]. Computer Science, 2015.\r\n"
}
] | 5 |
ukiradeas/aditi | https://github.com/ukiradeas/aditi | 2db018eac4763aa96fbb27c5e36a38c96227a57f | a30415075c735f4361983b8b8d275c5945f5769f | b6da1b1bd11fa9189dbc254514e2b67e98c2f531 | refs/heads/master | 2018-12-28T10:02:40.651655 | 2015-08-19T05:17:49 | 2015-08-19T05:17:49 | 41,014,409 | 0 | 0 | null | 2015-08-19T05:04:28 | 2015-08-19T05:08:29 | 2015-08-19T05:17:49 | Python | [
{
"alpha_fraction": 0.692307710647583,
"alphanum_fraction": 0.692307710647583,
"avg_line_length": 5.5,
"blob_id": "40966299773cd2b30a91a60202c95fe705ce402b",
"content_id": "af276b149f8795e32610239c17cd03edc5de47d9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 13,
"license_type": "no_license",
"max_line_length": 7,
"num_lines": 2,
"path": "/README.md",
"repo_name": "ukiradeas/aditi",
"src_encoding": "UTF-8",
"text": "# aditi\nname\n"
},
{
"alpha_fraction": 0.7222222089767456,
"alphanum_fraction": 0.7222222089767456,
"avg_line_length": 17,
"blob_id": "7b19c33f766435ccc29f42bca704389931fa58be",
"content_id": "095ff29446574440de5bd2383bef24a5d13aca89",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 108,
"license_type": "no_license",
"max_line_length": 20,
"num_lines": 6,
"path": "/file.py",
"repo_name": "ukiradeas/aditi",
"src_encoding": "UTF-8",
"text": "print \"H!... \"\nthis is first comit\nlet's learn python\nthis is second comit\nIt is easy\nthis is third comit\n"
}
] | 2 |
Ericsun01/mini-Amazon | https://github.com/Ericsun01/mini-Amazon | 98f872e7d50f92189350c3e5b8c4e47e02ba282a | 934077277b87d0c8d02347ecccef6ce98b148b3f | fb06039960f43d964839f74e4f6e3aa0c7c5f226 | refs/heads/master | 2022-11-26T16:52:58.662387 | 2020-08-12T14:29:10 | 2020-08-12T14:29:10 | 287,034,474 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7916666865348816,
"alphanum_fraction": 0.7916666865348816,
"avg_line_length": 35,
"blob_id": "51c5d0cf861bdb5f7833f6f01602e133ac8503de",
"content_id": "dbf3b821aff7328db84100c28051464837684cc2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 72,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 2,
"path": "/README.md",
"repo_name": "Ericsun01/mini-Amazon",
"src_encoding": "UTF-8",
"text": "# mini-Amazon\nTeamwork using google buffer and C++, partially completed\n"
},
{
"alpha_fraction": 0.6213408708572388,
"alphanum_fraction": 0.6244885325431824,
"avg_line_length": 23.635658264160156,
"blob_id": "7e1fc597af2da9a1e2b40916e7399aae5cd79f63",
"content_id": "6d18a2beea16b9235c7191a7f1c0d5100ad4d7e8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3177,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 129,
"path": "/erss-project-js895-hy165-master/Back-End/UPSServer.h",
"repo_name": "Ericsun01/mini-Amazon",
"src_encoding": "UTF-8",
"text": "#ifndef _UPSSERVER_\n#define _UPSSERVER_\n\n#include <arpa/inet.h>\n#include <assert.h>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <netdb.h>\n#include <netinet/in.h>\n#include <string>\n#include <sys/socket.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <vector>\n#include <sys/time.h>\n#include <thread>\n#include <queue>\n#include <mutex>\n#include <fstream>\n#include <time.h>\n#include <google/protobuf/io/coded_stream.h>\n#include <google/protobuf/io/zero_copy_stream_impl.h>\n\n// #include \"server.h\"\n\nusing namespace std;\nusing namespace google::protobuf::io;\n\nclass UPSServer {\n\n public:\n struct addrinfo host_info, *host_info_list;\n int newfd;\n int sockfd; \n int status;\n\n FileOutputStream * out;\n FileInputStream * in;\n\n UPSServer() {}\n\n void initialize(const char *_port);\n void createSocket();\n int acceptConnection();\n\n void buildServer(const char *port);\n \n // destructor\n ~UPSServer() {\n delete out;\n delete in;\n close(sockfd);\n }\n\n};\n\nvoid UPSServer::initialize(const char *_port) {\n cout << \"enter UPSServer initialize\" << endl;\n memset(&host_info, 0, sizeof(host_info));\n host_info.ai_family = AF_UNSPEC;\n host_info.ai_socktype = SOCK_STREAM;\n host_info.ai_flags = AI_PASSIVE;\n\n cout << \"UPS server start getting addrinfo\" << endl;\n status = getaddrinfo(NULL, _port, &host_info, &host_info_list);\n if (status != 0) {\n std::cerr << \"Error: UPSServer cannot get address info for host\" << std::endl;\n exit(EXIT_FAILURE);\n }\n cout << \"addrinfo get\" << endl;\n}\n\n\nvoid UPSServer::createSocket() {\n cout << \"UPS server enter createsocket\" << endl;\n sockfd = socket(host_info_list->ai_family, host_info_list->ai_socktype,\n host_info_list->ai_protocol);\n if (sockfd == -1) {\n std::cerr << \"UPSServer cannot create socket\" << std::endl;\n exit(EXIT_FAILURE);\n } \n\n int yes = 1;\n status = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));\n status = bind(sockfd, host_info_list->ai_addr, host_info_list->ai_addrlen);\n if (status == -1) {\n std::cerr << \"UPSServer cannot bind socket\" << std::endl;\n exit(EXIT_FAILURE);\n } \n\n status = listen(sockfd, 100);\n if (status == -1) {\n std::cerr << \"UPSServer cannot listen on socket\" << std::endl;\n exit(EXIT_FAILURE);\n }\n // debug\n cout << \"UPS server Waiting for connection...\" << endl; \n\n freeaddrinfo(host_info_list);\n\n // out = new FileOutputStream(sockfd);\n // in = new FileInputStream(sockfd);\n\n}\n\nint UPSServer::acceptConnection() {\n //int newfd;\n struct sockaddr_storage socket_addr;\n socklen_t socket_addr_len = sizeof(socket_addr);\n newfd = accept(sockfd, (struct sockaddr *)&socket_addr, &socket_addr_len);\n if (newfd == -1) {\n std::cerr << \"Error: UPSServer cannot accept connection on socket\" << std::endl;\n exit(EXIT_FAILURE);\n } // if\n\n return newfd;\n}\n\nvoid UPSServer::buildServer(const char *port) {\n // debug\n cout << \"enter UPSServer\" << endl;\n initialize(port);\n createSocket();\n}\n\n\n#endif"
},
{
"alpha_fraction": 0.6975333094596863,
"alphanum_fraction": 0.700861394405365,
"avg_line_length": 27.383333206176758,
"blob_id": "0cc7255a74b271b80bc5e124c3989c53dd1aa923",
"content_id": "79bb5ce73e7a63cd256a2acd04a2ea02dc8f2141",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5110,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 180,
"path": "/erss-project-js895-hy165-master/Back-End/parseMsg.h",
"repo_name": "Ericsun01/mini-Amazon",
"src_encoding": "UTF-8",
"text": "#ifndef _PARSEMSG_\n#define _PARSEMSG_\n\n#include <arpa/inet.h>\n#include <assert.h>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <netdb.h>\n#include <netinet/in.h>\n#include <string>\n#include <sys/socket.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <vector>\n#include <sys/time.h>\n#include <thread>\n#include <tuple>\n#include <queue>\n#include <mutex>\n#include <fstream>\n#include <time.h>\n#include <pqxx/pqxx>\n#include <google/protobuf/io/coded_stream.h>\n#include <google/protobuf/io/zero_copy_stream_impl.h>\n#include <atomic>\n\n#include \"world_amazon.pb.h\"\n#include \"amazon_ups.pb.h\"\n #include \"frontserver.h\"\n #include \"UPSServer.h\"\n #include \"WorldSocket.h\"\n\nusing namespace std;\nusing namespace google::protobuf::io;\nusing namespace pqxx;\n\n// global variables\n// sockets\nWorldSocket worldclient;\nUPSServer upsServer;\nFrontServer frontserver;\n\nconnection *C; // postgresql database connection\nstd::atomic <int> seqnum(0); // increment by 1\nstd::atomic <int> shipid(0); // increment by 1\nmap<int, int> ackRecv;\n\nqueue <int> newOrders;\nqueue <APurchaseMore> goRequestTruck;\nqueue <ALoaded> truckLoaded;\nqueue <UATruckArrived> readyToLoad;\nmap<int, int> orderPackedStatus;\n\n/**** helper functions ****/\nvoid update_status(connection *C, int ship_id, string status);\nvoid setTruckid(connection *C, int ship_id, int truck_id);\nvoid update_shipid(int order_id, int ship_id);\nstd::tuple<int, string, int> getOrderInfo(connection *C, int order_id);\nint getTruckidByShipid(connection *C, int ship_id);\nvector<int> getShipidById(connection *C, int id);\nstring getUPSusername(connection *C, int ship_id);\n\n\n// send and recv\ntemplate<typename T>\nbool sendMesgTo(const T & message, google::protobuf::io::FileOutputStream * out) \n{\n { \n //extra scope: make output go away before out->Flush()\n // We create a new coded stream for each message.\n // Don’t worry, this is fast.\n google::protobuf::io::CodedOutputStream output(out);\n // Write the size.\n const int size = message.ByteSize();\n output.WriteVarint32(size);\n uint8_t* buffer = output.GetDirectBufferForNBytesAndAdvance(size);\n if (buffer != NULL) \n {\n // Optimization: The message fits in one buffer, so use the faster direct-to-array serialization path.\n message.SerializeWithCachedSizesToArray(buffer);\n } \n else \n {\n // Slightly-slower path when the message is multiple buffers.\n message.SerializeWithCachedSizes(&output);\n if (output.HadError()) \n {\n return false;\n }\n }\n }\n out->Flush();\n return true;\n}\n\n//this is adpated from code that a Google engineer posted online template<typename T>\ntemplate<typename T>\nbool recvMesgFrom(T & message, google::protobuf::io::FileInputStream * in)\n{\n google::protobuf::io::CodedInputStream input(in);\n uint32_t size;\n if (!input.ReadVarint32(&size)) \n {\n cout << \"failed to read varint32!\" << endl;\n return false;\n }\n // Tell the stream not to read beyond that size.\n google::protobuf::io::CodedInputStream::Limit limit = input.PushLimit(size);\n // Parse the message.\n if (!message.MergeFromCodedStream(&input)) \n {\n cout << \"failed to merge!\" << endl;\n return false;\n }\n if (!input.ConsumedEntireMessage()) \n {\n cout << \"failed to consume entire merge!\" << endl;\n return false;\n }\n // Release the limit.\n input.PopLimit(limit);\n return true;\n}\n\n\n/* Amazon - World */\n\n// connect\nvoid connectToWorld(int world_id, int initwh_id, FileOutputStream * out);\nbool connectedToWorld(FileInputStream * in);\n\n// product\nAProduct* setAProduct(int id, string description, int count);\nvoid handleNewOrders(int order_id, FileOutputStream * out);\n\n// purchaseMore\nvoid handleAPurchaseMore(APurchaseMore arrived, FileOutputStream * worldout, FileOutputStream * upsout);\n\n// pack\nvoid handleAPacked(APacked ready, FileOutputStream * out);\n\n// put on truck(load)\nvoid handleALoaded(ALoaded loaded, FileOutputStream * worldout, FileOutputStream * upsout);\nvoid handleAPutOnTruck(FileOutputStream * out);\n\n// query\nAQuery setAQuery(int packageid, int seqnum);\nvoid handleAPackage(APackage packagestatus, FileOutputStream * out);\n\n// AErr\nACommands handleAErr(AErr aerror, FileOutputStream * out);\n\nvoid handleAcks(::google::protobuf::int64 ack, FileOutputStream * out);\n// void handleAResponses(AResponses aresponse);\n\n/* Amazon - UPS */\n\n// AUOrder, AUReqTruck\n void handleAUReqTruck(FileOutputStream * out); // mark1\n\n// UATruckArrived\nvoid handleUATruckArrived(UATruckArrived truck_arrived, FileOutputStream * out);\n\n// AUTruckLoaded\n void handleAUTruckLoaded(FileOutputStream * out); //mark2\n\n// UAPackageArrived\nvoid handleUAPackageArrived(UAPackageArrived package_arrived, FileOutputStream * out);\n\n// Errors\nUAErr setError(string error, int org_seqnum, int seqnum);\nvoid handleError(UAErr uaerror, FileOutputStream * out);\n\n// UACommand\n// void handleUACommands(UACommands uacommand);\n\n\n#endif"
},
{
"alpha_fraction": 0.6864407062530518,
"alphanum_fraction": 0.6920903921127319,
"avg_line_length": 28.41666603088379,
"blob_id": "7a6fabe9591c3913448d062e45ebbc58c795d512",
"content_id": "5af08cfd6657ede0e1c504445f0c3805a432530c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 354,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 12,
"path": "/erss-project-js895-hy165-master/Back-End/Makefile",
"repo_name": "Ericsun01/mini-Amazon",
"src_encoding": "UTF-8",
"text": "CC = g++\nCFLAGS = -std=c++11 -Wall -pedantic\nLDFLAGS = -lpthread -pthread\nGPBFLAGS = `pkg-config --cflags --libs protobuf`\nEXTRAFLAGS = -lpqxx -lpq\n\n\namazon: connection.cpp world_amazon.pb.cc amazon_ups.pb.cc\n\t$(CC) $(CFLAGS) $(LDFLAGS) -o amazon connection.cpp world_amazon.pb.cc amazon_ups.pb.cc $(EXTRAFLAGS) $(GPBFLAGS)\n\nclean:\n\trm -f *~ *.o amazon\n\n"
},
{
"alpha_fraction": 0.566013514995575,
"alphanum_fraction": 0.567940890789032,
"avg_line_length": 37.88750076293945,
"blob_id": "6e1d9411bb76ee65be26972f1cdae166bd118f95",
"content_id": "82bbbbc0c5c525af5876007c5d3ff54a6cfa359d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3113,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 80,
"path": "/erss-project-js895-hy165-master/Front-End/erss_amazon/amazon/forms.py",
"repo_name": "Ericsun01/mini-Amazon",
"src_encoding": "UTF-8",
"text": "from django import forms\nfrom django.forms import ModelForm\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.forms import UserCreationForm\nfrom .models import AmazonUser, Department, Products, Orders\nfrom django.utils.safestring import mark_safe\n\n\nclass RegisterForm(UserCreationForm):\n ups_username = forms.CharField(max_length=100)\n email = forms.EmailField()\n\n class Meta:\n model = AmazonUser\n fields = ['username', 'email', 'password1', 'password2', 'ups_username']\n\n\nclass CatalogueForm(forms.ModelForm):\n\n class Meta:\n model = Products\n fields = ['name', 'department', 'price']\n labels = {\n \"name\": \"Product Name\",\n \"department\": \"Department\",\n \"price\": \"Price\",\n }\n widgets = {\n \"name\": forms.widgets.TextInput(attrs={\"class\": \"form-control\"}),\n \"department\": forms.widgets.TextInput(attrs={\"class\": \"form-control\"}),\n \"price\": forms.widgets.TextInput(attrs={\"class\": \"form-control\", \"step\":\"0.01\"}),\n }\n\nclass PlaceOrderForm(forms.ModelForm):\n\n description = forms.ModelChoiceField(queryset=Products.objects.all())\n\n class Meta:\n model = Orders\n fields = ['description', 'count', 'ship_addr_x', 'ship_addr_y']\n labels = {\n \"description\": \"Product Name\",\n \"count\": \"Count\",\n \"ship_addr_x\": \"Address_x\",\n \"ship_addr_y\": \"Address_y\",\n }\n widgets = {\n # \"description\": forms.widgets.TextInput(attrs={\"class\": \"form-control\"}),\n \"count\": forms.widgets.NumberInput(attrs={\"class\": \"form-control\"}),\n \"ship_addr_x\": forms.widgets.NumberInput(attrs={\"class\": \"form-control\"}),\n \"ship_addr_y\": forms.widgets.NumberInput(attrs={\"class\": \"form-control\"}),\n }\n\n\n# class ViewOrdersForm(forms.ModelForm):\n\n# class Meta:\n# model = Orders\n# fields = ['owner', 'description', 'count', 'ship_addr_x', 'ship_addr_y', 'ship_id', 'truck_id', 'status']\n# labels = {\n# \"owner\": \"Username\",\n# \"description\": \"Product Name\",\n# \"count\": \"Count\",\n# \"ship_addr_x\": \"Address_x\",\n# \"ship_addr_y\": \"Address_y\",\n# \"ship_id\": \"Ship id\",\n# \"truck_id\": \"Truck id\",\n# \"status\": \"Order Status\",\n\n# }\n# widgets = {\n# \"owner\": forms.widgets.TextInput(attrs={\"class\": \"form-control\"}),\n# \"description\": forms.widgets.TextInput(attrs={\"class\": \"form-control\"}),\n# \"count\": forms.widgets.NumberInput(attrs={\"class\": \"form-control\"}),\n# \"ship_addr_x\": forms.widgets.NumberInput(attrs={\"class\": \"form-control\"}),\n# \"ship_addr_y\": forms.widgets.NumberInput(attrs={\"class\": \"form-control\"}),\n# \"ship_id\": forms.widgets.NumberInput(attrs={\"class\": \"form-control\"}),\n# \"truck_id\": forms.widgets.NumberInput(attrs={\"class\": \"form-control\"}),\n# \"status\": forms.widgets.TextInput(attrs={\"class\": \"form-control\"}),\n# }\n\n\n"
},
{
"alpha_fraction": 0.5084007382392883,
"alphanum_fraction": 0.5295581817626953,
"avg_line_length": 27.192981719970703,
"blob_id": "926a41b3cd496d44f1a504c262f5fa15a2a4f3d6",
"content_id": "1148b17e5030fd1fe7985672b9a81724085b499d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1607,
"license_type": "no_license",
"max_line_length": 117,
"num_lines": 57,
"path": "/erss-project-js895-hy165-master/Front-End/erss_amazon/amazon/migrations/0003_auto_20200416_0203.py",
"repo_name": "Ericsun01/mini-Amazon",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.0.4 on 2020-04-16 02:03\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('amazon', '0002_auto_20200414_2328'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='products',\n old_name='description',\n new_name='name',\n ),\n migrations.RemoveField(\n model_name='orders',\n name='ship_addr',\n ),\n migrations.RemoveField(\n model_name='orders',\n name='track_num',\n ),\n migrations.AddField(\n model_name='orders',\n name='count',\n field=models.IntegerField(default=0),\n ),\n migrations.AddField(\n model_name='orders',\n name='description',\n field=models.OneToOneField(null=True, on_delete=django.db.models.deletion.CASCADE, to='amazon.Products'),\n ),\n migrations.AddField(\n model_name='orders',\n name='ship_addr_x',\n field=models.IntegerField(default=0),\n ),\n migrations.AddField(\n model_name='orders',\n name='ship_addr_y',\n field=models.IntegerField(default=0),\n ),\n migrations.AddField(\n model_name='orders',\n name='truck_id',\n field=models.IntegerField(null=True),\n ),\n migrations.AlterField(\n model_name='orders',\n name='ship_id',\n field=models.IntegerField(null=True),\n ),\n ]\n"
},
{
"alpha_fraction": 0.5951293706893921,
"alphanum_fraction": 0.6103500723838806,
"avg_line_length": 16.3157901763916,
"blob_id": "3651b6611b58c7459f6167b6b2b85abec023c61d",
"content_id": "6e935b10257f84325dc94325edbf1c27be8589df",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 657,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 38,
"path": "/erss-project-js895-hy165-master/Back-End/interact.h",
"repo_name": "Ericsun01/mini-Amazon",
"src_encoding": "UTF-8",
"text": "#include <stdlib.h>\n#include <stdio.h>\n#include <unistd.h>\n#include <string>\n#include <iostream>\n#include <pqxx/pqxx>\n\nusing namespace std;\nusing namespace pqxx;\n\n\n/*\nint main(void) {\n\n connection *C;\n FrontServer frontserver;\n\n connectDB(C);\n\n frontserver.buildServer(\"6666\");\n int client_fd = frontserver.acceptConnection();\n char buffer[128];\n int len = recv(client_fd, buffer, sizeof(buffer), 0);\n if (len == -1) {\n perror(\"recv\");\n }\n buffer[len] = 0;\n // DEBUG\n cout << \"Server received: \" << buffer << endl;\n\n \n\n //TODO: Close database connection\n // C->disconnect();\n\n\n return EXIT_SUCCESS;\n}*/"
},
{
"alpha_fraction": 0.5733194947242737,
"alphanum_fraction": 0.5768879652023315,
"avg_line_length": 28.17796516418457,
"blob_id": "1323e5761ba3b164be79b40bdbf34263ebf91ddc",
"content_id": "47a531788b092b283ced89c41cbc5fe4b7299abc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 24100,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 826,
"path": "/erss-project-js895-hy165-master/Back-End/connection.cpp",
"repo_name": "Ericsun01/mini-Amazon",
"src_encoding": "UTF-8",
"text": "#include <arpa/inet.h>\n#include <assert.h>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <netdb.h>\n#include <thread>\n#include <netinet/in.h>\n#include <string>\n#include <sys/socket.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <vector>\n#include <fstream>\n#include <functional>\n#include <sys/time.h>\n#include <pqxx/pqxx>\n#include <google/protobuf/io/coded_stream.h>\n#include <google/protobuf/io/zero_copy_stream_impl.h>\n\n#include \"world_amazon.pb.h\"\n#include \"amazon_ups.pb.h\"\n#include \"frontserver.h\"\n#include \"UPSServer.h\"\n#include \"WorldSocket.h\"\n#include \"parseMsg.h\"\n\nusing namespace google::protobuf::io;\nusing namespace std;\nusing namespace pqxx;\n\n/**** helper functions ****/\n\n/*\n*** update the order status in database\n*/\nvoid update_status(connection *C, int ship_id, string status) {\n stringstream sbuffer;\n string sql;\n work W(*C);\n\n sbuffer << \"UPDATE amazon_orders \";\n sbuffer << \"SET status = \" << W.quote(status) << \" \";\n sbuffer << \"WHERE status = \" << ship_id << \";\";\n\n sql = sbuffer.str();\n\n W.exec(sql);\n W.commit();\n\n}\n/*\n*** set truckid according to shipid in database\n*/\nvoid setTruckid(connection *C, int ship_id, int truck_id) {\n\n stringstream sbuffer;\n string sql;\n work W(*C);\n\n sbuffer << \"UPDATE amazon_orders \";\n sbuffer << \"SET truck_id = \" << truck_id << \" \";\n sbuffer << \"WHERE ship_id = \" << ship_id << \";\";\n\n sql = sbuffer.str();\n\n W.exec(sql);\n\n}\n/*\n*** set shipid in database\n*/\nvoid update_shipid(int order_id, int ship_id) {\n\n stringstream sbuffer;\n string sql;\n work W(*C);\n\n sbuffer << \"UPDATE amazon_orders \";\n sbuffer << \"SET ship_id = \" << ship_id << \" \";\n sbuffer << \"WHERE id = \" << order_id << \";\";\n\n sql = sbuffer.str();\n\n W.exec(sql); \n \n}\n/*\n*** get order information based on order id\n*/\nstd::tuple<int, string, int> getOrderInfo(connection *C, int order_id) {\n\n nontransaction N(*C);\n string sql;\n stringstream sbuffer;\n\n sbuffer << \"SELECT whnum, description, count \";\n sbuffer << \"FROM amazon_orders, amazon_products \";\n sbuffer << \"WHERE amazon_orders.description = amazon_products.name \";\n sbuffer << \"AND amazon_orders.id = \" << order_id << \";\";\n\n sql = sbuffer.str();\n\n /* Execute SQL query */\n result R(N.exec(sql));\n\n int whnum;\n string description;\n int count;\n // print our headers\n cout << \"whnum \" << \"description\" << \"count\" << endl;\n // print out results\n for (result::const_iterator c = R.begin(); c != R.end(); ++c) {\n whnum = c[0].as<int>();\n description = c[1].as<string>();\n count = c[2].as<int>();\n\n cout << \"whnum = \" << whnum << endl;\n cout << \"description = \" << description << endl;\n cout << \"count = \" << count << endl;\n }\n std::tuple<int, string, int> order_info;\n order_info = make_tuple(whnum, description, count);\n\n return order_info;\n}\n/*\n*** get truck id by order id\n*/\nint getTruckidByShipid(connection *C, int ship_id) {\n\n nontransaction N(*C);\n string sql;\n stringstream sbuffer;\n\n sbuffer << \"SELECT truck_id \";\n sbuffer << \"FROM amazon_orders \";\n sbuffer << \"WHERE ship_id = \" << ship_id << \";\";\n\n sql = sbuffer.str();\n result R(N.exec(sql));\n\n int truck_id;\n // print out results\n for (result::const_iterator c = R.begin(); c != R.end(); ++c) {\n truck_id = c[0].as<int>();\n cout << \"truck_id = \" << truck_id << endl;\n } \n return truck_id;\n}\n/*\n*** get shipid based on primary key id\n*/\nvector<int> getShipidById(connection *C, int id) {\n\n nontransaction N(*C);\n string sql;\n stringstream sbuffer;\n\n sbuffer << \"SELECT ship_id, ship_addr_x, ship_addr_y \";\n sbuffer << \"FROM amazon_orders \";\n sbuffer << \"WHERE id = \" << id << \";\";\n\n sql = sbuffer.str();\n result R(N.exec(sql));\n\n int ship_id;\n int ship_addr_x;\n int ship_addr_y;\n // print out results\n for (result::const_iterator c = R.begin(); c != R.end(); ++c) {\n ship_id = c[0].as<int>();\n ship_addr_x = c[1].as<int>();\n ship_addr_y = c[2].as<int>();\n cout << \"ship_id = \" << ship_id << endl;\n cout << \"ship_addr_x = \" << ship_addr_x << endl;\n cout << \"ship_addr_y = \" << ship_addr_y << endl;\n\n } \n vector<int> order_info;\n order_info.push_back(ship_id);\n order_info.push_back(ship_addr_x);\n order_info.push_back(ship_addr_y);\n\n return order_info;\n}\n/*\n*** get upsusername based on ship id\n*/\nstring getUPSusername(connection *C, int ship_id) {\n\n nontransaction N(*C);\n string sql;\n stringstream sbuffer;\n\n sbuffer << \"SELECT amazon_amazonuser.ups_username \";\n sbuffer << \"FROM amazon_orders, amazon_amazonuser \";\n sbuffer << \"WHERE amazon_orders.ship_id = \" << ship_id << \";\";\n\n sql = sbuffer.str();\n result R(N.exec(sql));\n\n string ups_username;\n // print out results\n for (result::const_iterator c = R.begin(); c != R.end(); ++c) {\n ups_username = c[0].as<string>();\n cout << \"ship_id = \" << ups_username << endl;\n } \n return ups_username;\n}\n\n\n/**** handler functions ****/\n\n/*\n*** connect to the world\n*/\nvoid connectToWorld(int world_id, int initwh_id, FileOutputStream * out) {\n AConnect a_connect;\n // a_connect.set_worldid(world_id);\n cout << \"world_id set!\" << endl;\n\n AInitWarehouse * initwh = a_connect.add_initwh();\n cout << \"initwh init\" << endl;\n initwh->set_id(initwh_id);\n cout << \"initwh id set:\" << initwh->id() << endl;\n initwh->set_x(2);\n cout << \"initwh x set: \" << initwh->x() << endl;\n initwh->set_y(3);\n cout << \"initwh y set: \" << initwh->y() << endl;\n\n a_connect.set_isamazon(true);\n cout << \"isamazon set: \" << a_connect.isamazon() << endl;\n\n // send message\n bool sent = sendMesgTo(a_connect, out);\n if ( sent == false) {\n cout << \"cannot send message!\" << endl;\n }\n \n google::protobuf::ShutdownProtobufLibrary();\n}\n/*\n*** recv AConnected from the world\n*/\nbool connectedToWorld(FileInputStream * in) {\n AConnected a_connected;\n while (recvMesgFrom(a_connected, in) == false) {\n // wait\n }\n\n std::cout << \"world_id = \" << a_connected.worldid() << std::endl;\n std::cout << a_connected.result() << std::endl;\n \n if (a_connected.result().compare(\"connected!\")) {\n return true;\n }\n else {\n return false;\n } \n}\n/*\n*** handle new orders: send APurchaseMore\n*/\nvoid handleNewOrders(int order_id, FileOutputStream * out) {\n\n std::tuple<int, string, int> order_info = getOrderInfo(C, order_id);\n int whnum;\n string description;\n int count;\n tie (whnum, description, count) = order_info;\n // pack to APurchaseMore and acommands\n ACommands acommand; \n APurchaseMore * ap = acommand.add_buy();\n ap->set_whnum(whnum); // set whnum\n ap->set_seqnum(seqnum); // set seqnum\n // set products\n AProduct * product = ap->add_things();\n product->set_id(order_id);\n product->set_description(description);\n product->set_count(count);\n\n if (sendMesgTo(acommand, out) == false) { // send ack\n cout << \"cannot send APurchaseMore!\" << endl;\n }\n else {\n cout << \"APurchaseMore sent!\" << endl;\n }\n\n // send to world\n}\n/*\n*** handle APurchaseMore: send APack to world, send AUReqtruck to ups\n*/\nvoid handleAPurchaseMore(APurchaseMore arrived, FileOutputStream * worldout, FileOutputStream * upsout) {\n // goRequestTruck.push(arrived); // enqueue for ups socket to handle\n ::google::protobuf::int32 whnum = arrived.whnum();\n vector<AProduct> things;\n for (int j = 0; j < arrived.things_size(); j++) {\n things.push_back(arrived.things(j));\n } \n // send Apack to world\n ACommands acommand;\n // set APack\n APack* apack = acommand.add_topack();\n apack->set_whnum(whnum); // set whnum\n AProduct * thing = apack->add_things();\n thing->set_id(things[0].id());\n thing->set_description(things[0].description());\n thing->set_count(things[0].count()); \n /* assign shipid */\n apack->set_shipid(shipid); \n shipid++;\n update_shipid(thing->id(), shipid); // in database\n apack->set_seqnum(seqnum); // set seqnum\n seqnum++;\n // set the seq of arrived as ack\n acommand.add_acks(arrived.seqnum());\n\n if (sendMesgTo(acommand, worldout) == false) { // send ack\n cout << \"cannot send APack!\" << endl;\n }\n else {\n cout << \"APack sent!\" << endl;\n }\n\n // send AUReqTruck to ups\n // APurchaseMore ap = goRequestTruck.front();\n // goRequestTruck.pop();\n // get whnum\n AProduct product = arrived.things(0);\n int id = product.id();\n string description = product.description();\n // get shipid from database\n vector<int> order_info = getShipidById(C, id);\n int ship_id = order_info[0];\n int ship_addr_x = order_info[1];\n int ship_addr_y = order_info[2];\n string ups_username = getUPSusername(C, ship_id);\n\n AUCommands aucommand;\n AUReqTruck * req_truck = aucommand.add_requests();\n req_truck->set_warehouseid(whnum); // set whnum\n req_truck->set_shipid(ship_id); // set shipid\n req_truck->set_seqnum(seqnum); // set seqnum\n seqnum++;\n // set orders\n AUOrder * orders;\n orders->set_description(description);\n orders->set_locationx(ship_addr_x);\n orders->set_locationy(ship_addr_y);\n orders->set_username(ups_username);\n req_truck->set_allocated_orders(orders);\n\n if (sendMesgTo(aucommand, upsout) == false) { // send ack\n cout << \"cannot send AUReqTruck!\" << endl;\n }\n else {\n cout << \"AUReqTruck sent!\" << endl;\n } \n\n}\n/*\n*** handle APacked: send ack\n*/\nvoid handleAPacked(APacked ready, FileOutputStream * out) {\n ACommands acommand;\n\n int ship_id = ready.shipid();\n orderPackedStatus[ship_id] = 1; // set flag to 1\n // set the seq of ready as ack\n acommand.add_acks(ready.seqnum());\n\n if (sendMesgTo(acommand, out) == false) { // send ack\n cout << \"cannot send ack for APacked!\" << endl;\n }\n else {\n cout << \"Ack for APacked sent!\" << endl;\n }\n}\n/*\n*** handle ALoaded: send ack to world, send AUTruckloaded to ups\n*/\nvoid handleALoaded(ALoaded loaded, FileOutputStream * worldout, FileOutputStream * upsout) {\n ACommands acommand;\n // truckLoaded.push(loaded); // enqueue for ups socket to handle\n // set the seq of ready as ack\n acommand.add_acks(loaded.seqnum());\n\n if (sendMesgTo(acommand, worldout) == false) { // send ack\n cout << \"cannot send ack for ALoaded!\" << endl;\n }\n else {\n cout << \"Ack for ALoaded sent!\" << endl;\n }\n\n // send AUTruckloaded to ups\n int ship_id = loaded.shipid();\n int truck_id = getTruckidByShipid(C, ship_id);\n\n AUCommands aucommand;\n AUTruckLoaded * autruck_loaded = aucommand.add_truckloaded();\n autruck_loaded->set_truckid(truck_id);\n autruck_loaded->set_shipid(shipid);\n autruck_loaded->set_seqnum(seqnum);\n seqnum++;\n\n if (sendMesgTo(aucommand, upsout) == false) { // send ack\n cout << \"cannot send AUTruckLoaded!\" << endl;\n }\n else {\n cout << \"AUTruckLoaded sent!\" << endl;\n }\n}\n/*\n*** handle ALoaded: send APutOnTruck to world\n*/\nvoid handleAPutOnTruck(FileOutputStream * out) {\n UATruckArrived truck_arrived = readyToLoad.front(); // get the first item in queue\n readyToLoad.pop();\n int ship_id = truck_arrived.shipid(); // get ship id\n if (orderPackedStatus[ship_id] == 1) { // if already packed\n ACommands acommand;\n // set APutOnTruck\n APutOnTruck* load = acommand.add_load();\n load->set_whnum(1); // set whnum to 1\n load->set_truckid(truck_arrived.truckid()); // set shipid\n load->set_shipid(ship_id);\n load->set_seqnum(seqnum); // set seqnum\n seqnum++;\n // set the seq of arrived as ack\n acommand.add_acks(truck_arrived.seqnum());\n\n if (sendMesgTo(acommand, out) == false) { // send ack\n cout << \"cannot send APutOnTruck!\" << endl;\n }\n else {\n cout << \"APutOnTruck sent!\" << endl;\n }\n }\n else { // if haven't packed yet, put it back and keep waiting\n readyToLoad.push(truck_arrived);\n }\n}\n\n// // query\n// AQuery setAQuery(int packageid, int seqnum) {\n\n// }\n\n/*\n*** handle APackage: update status in database\n*/\nvoid handleAPackage(APackage packagestatus, FileOutputStream * out) {\n int ship_id = packagestatus.packageid(); // get shipid\n string status = packagestatus.status(); // get status\n // renew database\n update_status(C, ship_id, status);\n ACommands acommand;\n acommand.add_acks(packagestatus.seqnum());\n\n if (sendMesgTo(acommand, out) == false) { // send ack\n cout << \"cannot send ack for APackage!\" << endl;\n }\n else {\n cout << \"Ack for APackage sent!\" << endl;\n }\n}\n\n// AErr\n// ACommands handleAErr(AErr aerror, FileOutputStream * out) {\n\n// }\n\n/*\n*** handle acks: set flag to 1, indicating the message has been recv by world\n*/\nvoid handleAcks(::google::protobuf::int64 ack, FileOutputStream * out) {\n map<int, int>::iterator it;\n if ((it = ackRecv.find(ack)) != ackRecv.end()) { // if found seqnum\n it->second = 1; // set flag to 1\n }\n else {\n cerr << \"seqnum does not exist!\" << endl;\n }\n}\n\n\n/************ Amazon - UPS *************/\n\n/*\n*** handle UATruckArrived: send ack to the world, push into \"readyToLoad\" queue\n*/\nvoid handleUATruckArrived(UATruckArrived truck_arrived, FileOutputStream * out) {\n int ship_id = truck_arrived.shipid();\n int truck_id = truck_arrived.truckid();\n setTruckid(C, ship_id, truck_id); // set truckid in database\n readyToLoad.push(truck_arrived);\n\n AUCommands aucommand;\n // set the seq as ack\n aucommand.add_acks(truck_arrived.seqnum());\n\n if (sendMesgTo(aucommand, out) == false) { // send ack\n cout << \"cannot send ack for UATruckArrived!\" << endl;\n }\n else {\n cout << \"Ack for UATruckArrived sent!\" << endl;\n }\n}\n/*\n*** handle UAPackageArrived: send ack to the world, update order status to 1\n*/\nvoid handleUAPackageArrived(UAPackageArrived package_arrived, FileOutputStream * out) {\n int ship_id = package_arrived.shipid();\n update_status(C, ship_id, \"delivered\");\n AUCommands aucommand;\n // set the seq as ack\n aucommand.add_acks(package_arrived.seqnum());\n\n if (sendMesgTo(aucommand, out) == false) { // send ack\n cout << \"cannot send ack for UAPackageArrived!\" << endl;\n }\n else {\n cout << \"Ack for UAPackageArrived sent!\" << endl;\n }\n}\n\nvoid handleAUReqTruck(FileOutputStream * out) {\n APurchaseMore ap = goRequestTruck.front();\n goRequestTruck.pop();\n // get whnum\n int whnum = ap.whnum();\n AProduct thing = ap.things(0);\n int id = thing.id();\n string description = thing.description();\n // get shipid from database\n vector<int> order_info = getShipidById(C, id);\n int ship_id = order_info[0];\n int ship_addr_x = order_info[1];\n int ship_addr_y = order_info[2];\n string ups_username = getUPSusername(C, ship_id);\n\n AUCommands aucommand;\n AUReqTruck * req_truck = aucommand.add_requests();\n req_truck->set_warehouseid(whnum); // set whnum\n req_truck->set_shipid(ship_id); // set shipid\n req_truck->set_seqnum(seqnum); // set seqnum\n seqnum++;\n // set orders\n AUOrder * orders;\n orders->set_description(description);\n orders->set_locationx(ship_addr_x);\n orders->set_locationy(ship_addr_y);\n orders->set_username(ups_username);\n req_truck->set_allocated_orders(orders);\n\n if (sendMesgTo(aucommand, out) == false) { // send ack\n cout << \"cannot send AUReqTruck!\" << endl;\n }\n else {\n cout << \"AUReqTruck sent!\" << endl;\n } \n}\n\nvoid handleAUTruckLoaded(FileOutputStream * out) {\n ALoaded loaded = truckLoaded.front();\n truckLoaded.pop();\n int ship_id = loaded.shipid();\n int truck_id = getTruckidByShipid(C, ship_id);\n\n AUCommands aucommand;\n AUTruckLoaded * autruck_loaded = aucommand.add_truckloaded();\n autruck_loaded->set_truckid(truck_id);\n autruck_loaded->set_shipid(shipid);\n autruck_loaded->set_seqnum(seqnum);\n seqnum++;\n\n if (sendMesgTo(aucommand, out) == false) { // send ack\n cout << \"cannot send AUTruckLoaded!\" << endl;\n }\n else {\n cout << \"AUTruckLoaded sent!\" << endl;\n }\n\n}\n\n// Errors\n// UAErr setError(string error, int org_seqnum, int seqnum);\n// void handleError(UAErr uaerror, FileOutputStream * out) {\n// }\n\n/*\n*** connect to database\n*/\nvoid connectDB(connection *C) {\n try {\n //Establish a connection to the database\n //Parameters: database name, user name, user password\n C = new connection(\"dbname=erss_amazon user=postgres password=ece568\");\n if (C->is_open()) {\n cout << \"Opened database successfully: \" << C->dbname() << endl;\n } else {\n cout << \"Can't open database\" << endl;\n }\n } catch (const std::exception &e){\n cerr << e.what() << std::endl;\n }\n}\n/*\n*** frontsocket thread\n*/\nvoid front() {\n// void front(FrontServer & frontserver) {\n // debug\n cout << \"Entered front thread\" << endl;\n int fd;\n int order_id;\n std::mutex mtx;\n\n // fd = frontserver.acceptConnection();\n \n // string buff;\n while (true) {\n while (true) {\n fd = frontserver.acceptConnection();\n // debug\n cout << \"listening to front...\" << endl;\n char buffer[128];\n int len = recv(fd, buffer, sizeof(buffer), 0);\n if (len == -1) {\n perror(\"recv\");\n }\n if (len > 0) {\n buffer[len] = 0;\n // DEBUG\n cout << \"Server received: \" << buffer << endl;\n order_id = stoi(buffer);\n mtx.lock();\n newOrders.push(order_id);\n // DEBUG\n cout << \"Push into queue: \" << newOrders.back() << endl; \n mtx.unlock();\n break;\n } \n }\n }\n}\n/*\n*** the thread listening to world and ups\n*/ \nvoid back() {\n\n // debug\n cout << \"Entered back thread\" << endl;\n\n int world_id;\n int initwh_id = 2;\n\n int ups_fd = upsServer.acceptConnection();\n upsServer.out = new FileOutputStream(ups_fd);\n upsServer.in = new FileInputStream(ups_fd);\n\n\n // /*\n // 1. recv worldbuilt \n // */\n UAWorldBuilt world_built;\n while (recvMesgFrom(world_built, upsServer.in) == false) {\n // wait \n }\n world_id = world_built.worldid();\n // debug\n cout << \"recv world_id = \" << world_id << endl;\n\n AUCommands aucommand;\n // set the seq as ack\n aucommand.add_acks(world_built.seqnum());\n if (sendMesgTo(aucommand, upsServer.out) == false) { // send ack\n cout << \"cannot send Aconnect!\" << endl;\n }\n\n /*\n 2. connect to world \n */\n connectToWorld(world_id, 1, worldclient.out);\n //connectToWorld(3, 1, worldclient.out); // test; remove later\n if (connectedToWorld(worldclient.in) == true) {\n cout << \"Connected to world!\" << endl;\n }\n\n\n /*\n 3. general responses \n */\n\n while(true) { \n cout << \"enter Aresponse loop\" << endl;\n /* \n communication with world \n */\n AResponses aresponse; \n cout << \"Aresponse init\" << endl; \n // if new order comes in\n while (!newOrders.empty()) {\n cout << \"enter new order loop\" << endl; \n int order_id = newOrders.front();\n newOrders.pop();\n // debug\n cout << \"pop from queue: \" << order_id << endl;\n cout << \"\" << endl;\n thread (handleNewOrders, order_id, worldclient.out).detach(); \n } \n cout << \"currently no new orders\" << endl; \n\n if (recvMesgFrom(aresponse, worldclient.in) == true) { // if recv aresponse\n cout << \"new aresponse\" << endl; \n for (int i = 0; i < aresponse.acks_size(); i++) {\n ::google::protobuf::int64 ack = aresponse.acks(i);\n thread (handleAcks, ack, worldclient.out).detach();\n }\n // handle APurchaseMore\n for (int i = 0; i < aresponse.arrived_size(); i++) {\n APurchaseMore arrived = aresponse.arrived(i);\n thread (handleAPurchaseMore, arrived, worldclient.out, upsServer.out).detach();\n }\n // handle APacked\n for (int i = 0; i < aresponse.ready_size(); i++) {\n APacked ready = aresponse.ready(i);\n thread (handleAPacked, ready, worldclient.out).detach();\n\n }\n // handle ALoaded\n for (int i = 0; i < aresponse.loaded_size(); i++) {\n ALoaded loaded = aresponse.loaded(i);\n thread (handleALoaded, loaded, worldclient.out, upsServer.out).detach();\n }\n // handle APackage\n for (int i = 0; i < aresponse.packagestatus_size(); i++) {\n APackage packagestatus = aresponse.packagestatus(i);\n thread (handleAPackage, packagestatus, worldclient.out).detach();\n }\n // handle AErr\n // for (int i = 0; i < aresponse.error_size(); i++) {\n // AErr error = aresponse.error(i);\n // thread (handleAErr, error, worldclient.out).detach();\n // }\n }\n\n cout << \"currently no aresponse\" << endl;\n\n while (!readyToLoad.empty()) {\n std::thread (handleAPutOnTruck, worldclient.out).detach(); // send APutOnTruck\n }\n\n cout << \"currently nothing ready to load\" << endl;\n \n /* \n communication with ups \n */\n UACommands uacommand;\n while (recvMesgFrom(uacommand, worldclient.in) == true) { // if received from ups\n\n for (int i = 0; i < uacommand.acks_size(); i++) {\n ::google::protobuf::int64 ack = uacommand.acks(i);\n std::thread (handleAcks, ack, upsServer.out).detach();\n // handleAcks(ack, ups.out);\n }\n // handle UATruckArrived\n for (int i = 0; i < uacommand.truckarrived_size(); i++) {\n UATruckArrived truckarrived = uacommand.truckarrived(i);\n std::thread (handleUATruckArrived, truckarrived, upsServer.out).detach();\n // handleUATruckArrived(truckarrived, ups.out);\n }\n // handle UAPackageArrived\n for (int i = 0; i < uacommand.packagearrived_size(); i++) {\n UAPackageArrived packagearrived = uacommand.packagearrived(i);\n std::thread (handleUAPackageArrived, packagearrived, upsServer.out).detach();\n // handleUAPackageArrived(packagearrived, ups.out);\n }\n // handle AErr\n // for (int i = 0; i < uacommand.uaerror_size(); i++) {\n // UAErr error = uacommand.uaerror(i);\n // handleError(error, upsServer.out);\n // }\n\n }\n\n //cout << \"currently no uacommand\" << endl;\n // while (!goRequestTruck.empty()) {\n // std::thread (handleAUReqTruck, upsServer.out).detach();\n // std::thread (goRequestT).detach();\n // }\n // while (!truckLoaded.empty()) {\n // std::thread (handleAUTruckLoaded, upsServer.out).detach();\n // std::thread (truckL).detach();\n // }\n }\n}\n\n\nint main (int argc, char **argv) {\n\n connectDB(C);\n\n int fd = worldclient.connect_server(\"vcm-13673.vm.duke.edu\", \"23456\");\n \n /******** test code area *********/\n\n /******** test code area *********/\n \n\n frontserver.buildServer(\"5678\");\n upsServer.buildServer(\"43210\");\n\n std::thread th1 (front);\n th1.detach();\n std::thread th2 (back);\n th2.detach();\n\n while (true) {} \n \n return EXIT_SUCCESS;\n \n}"
},
{
"alpha_fraction": 0.5038961172103882,
"alphanum_fraction": 0.5844155550003052,
"avg_line_length": 20.38888931274414,
"blob_id": "dc687a804674afdde826f7fee29ddf3f702a0c58",
"content_id": "bd407398a05683492cc8218815e8b2bbb5c55f78",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 385,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 18,
"path": "/erss-project-js895-hy165-master/Front-End/erss_amazon/amazon/migrations/0004_auto_20200416_0203.py",
"repo_name": "Ericsun01/mini-Amazon",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.0.4 on 2020-04-16 02:03\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('amazon', '0003_auto_20200416_0203'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='products',\n name='wh_id',\n field=models.IntegerField(null=True),\n ),\n ]\n"
},
{
"alpha_fraction": 0.5357334613800049,
"alphanum_fraction": 0.5398530960083008,
"avg_line_length": 29.839778900146484,
"blob_id": "ea992372c4b510ed92ea1229633a46428bb07ccf",
"content_id": "c9670f86e23dfbdef65644f8145ec67346681723",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5583,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 181,
"path": "/erss-project-js895-hy165-master/Back-End/tests.cpp",
"repo_name": "Ericsun01/mini-Amazon",
"src_encoding": "UTF-8",
"text": "/************ functionality test codes *************/\n#include <arpa/inet.h>\n#include <assert.h>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <netdb.h>\n#include <netinet/in.h>\n#include <string>\n#include <sys/socket.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <vector>\n#include <sys/time.h>\n#include <thread>\n#include <tuple>\n#include <queue>\n#include <mutex>\n#include <fstream>\n#include <time.h>\n#include <pqxx/pqxx>\n#include <google/protobuf/io/coded_stream.h>\n#include <google/protobuf/io/zero_copy_stream_impl.h>\n#include <atomic>\n\n#include \"world_amazon.pb.h\"\n#include \"amazon_ups.pb.h\"\n#include \"frontserver.h\"\n#include \"UPSServer.h\"\n#include \"WorldSocket.h\"\n#include \"parseMsg.h\"\n\nusing namespace google::protobuf::io;\nusing namespace std;\nusing namespace pqxx;\n\n/*\n**** AConnect test codes: send AConnect and receive AConnected ****\n\n connectToWorld(3, 1, worldclient.out); \n if (connectedToWorld(worldclient.in) == true) {\n cout << \"Connected to world!\" << endl;\n }\n\n*/\n\n/*\n**** APurchaseMore test codes: send APurchaseMore, receive AResponse ****\n**** containing APurchaseMore, and send APack ****\n\n ACommands acommand; \n APurchaseMore * ap = acommand.add_buy();\n ap->set_whnum(1); // set whnum\n ap->set_seqnum(2); // set seqnum\n // set products\n AProduct * product = ap->add_things();\n product->set_id(15);\n product->set_description(\"juice\");\n product->set_count(3);\n\n if (sendMesgTo(acommand, worldclient.out) == false) { // send ack\n cout << \"cannot send APurchaseMore!\" << endl;\n }\n else {\n cout << \"APurchaseMore sent!\" << endl;\n }\n\n AResponses aresponse;\n if (recvMesgFrom(aresponse, worldclient.in) == false) {\n cout << \"Failed to recv aresponse!\" << endl;\n }\n else {\n for (int i = 0; i < aresponse.arrived_size(); i++) {\n APurchaseMore arrived = aresponse.arrived(i);\n // thread (handleAPurchaseMore, arrived, worldclient.out, upsServer.out).detach();\n\n ::google::protobuf::int32 whnum = arrived.whnum();\n cout << \"whnum = \" << whnum << endl;\n vector<AProduct> things;\n for (int j = 0; j < arrived.things_size(); j++) {\n things.push_back(arrived.things(j));\n }\n\n // send Apack to world\n ACommands acommand;\n // set APack\n APack* apack = acommand.add_topack();\n apack->set_whnum(whnum); // set whnum\n AProduct * thing = apack->add_things();\n thing->set_id(things[0].id());\n cout << \"things id set: \" << things[0].id() << endl;\n thing->set_description(things[0].description());\n cout << \"things description set: \" << things[0].description() << endl;\n thing->set_count(things[0].count());\n cout << \"things count set: \" << things[0].count() << endl; \n\n apack->set_shipid(shipid);\n cout << \"things shipid set: \" << shipid << endl; \n // update_shipid(C, thing->id(), shipid); // in database\n shipid++;\n cout << \"things shipid updated\" << endl;\n apack->set_seqnum(seqnum); // set seqnum\n cout << \"things seqnum set: \" << seqnum << endl;\n seqnum++;\n // set the seq of arrived as ack\n acommand.add_acks(arrived.seqnum());\n cout << \"ack set: \" << seqnum << endl;\n\n if (sendMesgTo(acommand, worldclient.out) == false) { // send ack\n cout << \"cannot send APack!\" << endl;\n }\n else {\n cout << \"APack sent!\" << endl;\n }\n\n\n // doesn't work\n // recv APacked\n AResponses aresponse;\n if (recvMesgFrom(aresponse, worldclient.in) == false) {\n cout << \"Failed to recv aresponse!\" << endl;\n }\n for (int i = 0; i < aresponse.ready_size(); i++) {\n APacked ready = aresponse.ready(i);\n // thread (handleAPacked, ready, worldclient.out).detach();\n\n ACommands acommand;\n int ship_id = ready.shipid();\n\n // set the seq of ready as ack\n acommand.add_acks(ready.seqnum());\n\n if (sendMesgTo(acommand, worldclient.out) == false) { // send ack\n cout << \"cannot send ack for APacked!\" << endl;\n }\n else {\n cout << \"Ack for APacked sent!\" << endl;\n }\n }\n }\n }\n\n*/\n\n/*\n**** APutOnTruck test codes: send APutOnTruck, receive ALoaded ****\n\n ACommands acommand;\n // set APutOnTruck\n APutOnTruck* load = acommand.add_load();\n load->set_whnum(1); \n load->set_truckid(2); \n load->set_shipid(3); // set shipid\n load->set_seqnum(5); // set seqnum\n seqnum++;\n\n if (sendMesgTo(acommand, out) == false) { // send ack\n cout << \"cannot send APutOnTruck!\" << endl;\n }\n else {\n cout << \"APutOnTruck sent!\" << endl;\n }\n\n AResponses aresponse;\n if (recvMesgFrom(aresponse, worldclient.in) == false) {\n cout << \"Failed to recv aresponse!\" << endl;\n }\n else {\n for (int i = 0; i < aresponse.loaded_size(); i++) {\n ALoaded loaded = aresponse.loaded(i);\n\n int ship_id = loaded.shipid();\n cout << \"ship_id: \" << ship_id << endl;\n int seqnum = loaded.seqnum();\n cout << \"seq_num: \" << seqnum << endl;\n\n }\n }\n\n*/\n\n"
},
{
"alpha_fraction": 0.5500910878181458,
"alphanum_fraction": 0.5719490051269531,
"avg_line_length": 40.17499923706055,
"blob_id": "f52ba38e7c0f2a27da409817e141e993af21ec3a",
"content_id": "0ca0fb98d44b183f520a755666e5fce10c201d78",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1647,
"license_type": "no_license",
"max_line_length": 207,
"num_lines": 40,
"path": "/erss-project-js895-hy165-master/Front-End/erss_amazon/amazon/migrations/0002_auto_20200414_2328.py",
"repo_name": "Ericsun01/mini-Amazon",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.0.4 on 2020-04-14 23:28\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('amazon', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Products',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('description', models.CharField(max_length=300)),\n ('department', models.CharField(choices=[('Food', 'Food'), ('Fashion', 'Fashion'), ('Household', 'Household'), ('Sports', 'Sports'), ('Others', 'Others')], default='Others', max_length=100)),\n ('price', models.DecimalField(decimal_places=2, max_digits=10)),\n ('wh_id', models.IntegerField(blank=True)),\n ],\n ),\n migrations.AddField(\n model_name='amazonuser',\n name='ups_username',\n field=models.CharField(default='xxx', max_length=100),\n ),\n migrations.CreateModel(\n name='Orders',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('ship_addr', models.CharField(max_length=300)),\n ('ship_id', models.IntegerField(blank=True)),\n ('track_num', models.CharField(blank=True, max_length=50)),\n ('owner', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n ],\n ),\n ]\n"
},
{
"alpha_fraction": 0.6013676524162292,
"alphanum_fraction": 0.60337895154953,
"avg_line_length": 23.382352828979492,
"blob_id": "50459af6019321d6a6fecf5242e3d646fb0e5b14",
"content_id": "c37d7708dafc338db964dee0df7628a8587017da",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2486,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 102,
"path": "/erss-project-js895-hy165-master/Back-End/WorldSocket.h",
"repo_name": "Ericsun01/mini-Amazon",
"src_encoding": "UTF-8",
"text": "#ifndef _WORLDSOCKET_\n#define _WORLDSOCKET_\n\n#include <arpa/inet.h>\n#include <assert.h>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <netdb.h>\n#include <netinet/in.h>\n#include <string>\n#include <sys/socket.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <vector>\n#include <sys/time.h>\n#include <thread>\n#include <queue>\n#include <mutex>\n#include <fstream>\n#include <time.h>\n#include <google/protobuf/io/coded_stream.h>\n#include <google/protobuf/io/zero_copy_stream_impl.h>\n\nusing namespace std;\nusing namespace google::protobuf::io;\n\nclass WorldSocket {\n\n public:\n\n struct addrinfo host_info, *host_info_list;\n int socket_fd; \n int status;\n FileOutputStream * out;\n FileInputStream * in;\n\n\n WorldSocket() {\n\n }\n\n public:\n int connect_server(const char *hostname, const char *port);\n void send_init_msg();\n\n // destructor\n ~WorldSocket() {\n delete out;\n delete in;\n close(socket_fd);\n }\n \n};\n\nint WorldSocket::connect_server(const char *hostname, const char *port) {\n\n memset(&host_info, 0, sizeof(struct addrinfo));\n host_info.ai_family = AF_UNSPEC;\n host_info.ai_socktype = SOCK_STREAM;\n\n status = getaddrinfo(hostname, port, &host_info, &host_info_list);\n if (status != 0) {\n std::cerr << \"cannot get address info for host\" << std::endl;\n std::cout << \" (\" << hostname << \",\" << port << \")\" << std::endl;\n exit(EXIT_FAILURE);\n } // if\n\n socket_fd = socket(host_info_list->ai_family, host_info_list->ai_socktype,\n host_info_list->ai_protocol);\n if (socket_fd == -1) {\n std::cerr << \"cannot create socket\" << std::endl;\n std::cout << \" (\" << hostname << \",\" << port << \")\" << std::endl;\n exit(EXIT_FAILURE);\n } // if\n\n status = connect(socket_fd, host_info_list->ai_addr, host_info_list->ai_addrlen);\n if (status == -1) {\n std::cerr << \"cannot connect to socket\" << std::endl;\n std::cout << \" (\" << hostname << \",\" << port << \")\" << std::endl;\n exit(EXIT_FAILURE);\n } // if\n\n freeaddrinfo(host_info_list);\n\n // init gpb stream\n out = new FileOutputStream(socket_fd);\n in = new FileInputStream(socket_fd);\n\n // cout << \"world connected!\" << endl;\n\n return socket_fd;\n}\n\nvoid WorldSocket::send_init_msg() {\n const char *message = \"hi there!\";\n send(socket_fd, message, strlen(message), 0);\n cout << \"init msg sent\" << endl;\n}\n\n#endif"
},
{
"alpha_fraction": 0.570841908454895,
"alphanum_fraction": 0.6344969272613525,
"avg_line_length": 24.63157844543457,
"blob_id": "b7089c73b2c5a4e56de9b1e9b64448b514d98fa5",
"content_id": "bc5f62fea67df91de31c3feee79bb8432772ab29",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 487,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 19,
"path": "/erss-project-js895-hy165-master/Front-End/erss_amazon/amazon/migrations/0007_auto_20200416_2014.py",
"repo_name": "Ericsun01/mini-Amazon",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.0.4 on 2020-04-16 20:14\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('amazon', '0006_auto_20200416_1811'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='orders',\n name='description',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='amazon.Products'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.5998610854148865,
"alphanum_fraction": 0.6026390194892883,
"avg_line_length": 27.609272003173828,
"blob_id": "dd00c4bd2831901c5de3ce53c0a02d2a8491b7a8",
"content_id": "31ddf739213d454e30cf7b72eda37ac4d92797df",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 17279,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 604,
"path": "/erss-project-js895-hy165-master/Back-End/parseMsg.cpp",
"repo_name": "Ericsun01/mini-Amazon",
"src_encoding": "UTF-8",
"text": "#include <arpa/inet.h>\n#include <assert.h>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <netdb.h>\n#include <netinet/in.h>\n#include <string>\n#include <sys/socket.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <vector>\n#include <sys/time.h>\n#include <thread>\n#include <queue>\n#include <tuple>\n#include <mutex>\n#include <fstream>\n#include <sstream>\n#include <time.h>\n#include <pqxx/pqxx>\n#include <google/protobuf/io/coded_stream.h>\n#include <google/protobuf/io/zero_copy_stream_impl.h>\n#include <google/protobuf/stubs/common.h>\n#include <google/protobuf/arena.h>\n#include <google/protobuf/arenastring.h>\n#include <google/protobuf/generated_message_util.h>\n#include <google/protobuf/metadata.h>\n#include <google/protobuf/message.h>\n#include <google/protobuf/repeated_field.h>\n#include <google/protobuf/extension_set.h>\n#include <google/protobuf/unknown_field_set.h>\n\n#include \"world_amazon.pb.h\"\n#include \"amazon_ups.pb.h\"\n#include \"parseMsg.h\"\n\n\nusing namespace std;\nusing namespace google::protobuf::io;\nusing namespace pqxx;\n\n// // global variables\n// connection *C; // postgresql database connection\n// std::atomic <int> seqnum(0); // increment by 1\n// std::atomic <int> shipid(0); // increment by 1\n// map<int, int> ackRecv;\n\n// queue <int> newOrders;\n// queue <APurchaseMore> goRequestTruck;\n// queue <ALoaded> truckLoaded;\n// queue <UATruckArrived> readyToLoad;\n// map<int, int> orderPackedStatus;\n\n/**** helper functions ****/\n\nvoid update_status(connection *C, int ship_id, string status) {\n stringstream sbuffer;\n string sql;\n work W(*C);\n\n sbuffer << \"UPDATE amazon_orders \";\n sbuffer << \"SET status = \" << W.quote(status) << \" \";\n sbuffer << \"WHERE status = \" << ship_id << \";\";\n\n sql = sbuffer.str();\n\n W.exec(sql);\n W.commit();\n\n}\n\nvoid setTruckid(connection *C, int ship_id, int truck_id) {\n\n stringstream sbuffer;\n string sql;\n work W(*C);\n\n sbuffer << \"UPDATE amazon_orders \";\n sbuffer << \"SET truck_id = \" << truck_id << \" \";\n sbuffer << \"WHERE ship_id = \" << ship_id << \";\";\n\n sql = sbuffer.str();\n\n W.exec(sql);\n\n}\n\nvoid update_shipid(int order_id, int ship_id) {\n\n stringstream sbuffer;\n string sql;\n work W(*C);\n\n sbuffer << \"UPDATE amazon_orders \";\n sbuffer << \"SET ship_id = \" << ship_id << \" \";\n sbuffer << \"WHERE id = \" << order_id << \";\";\n\n sql = sbuffer.str();\n\n W.exec(sql); \n \n}\n\nstd::tuple<int, string, int> getOrderInfo(connection *C, int order_id) {\n\n nontransaction N(*C);\n string sql;\n stringstream sbuffer;\n\n sbuffer << \"SELECT whnum, description, count \";\n sbuffer << \"FROM amazon_orders, amazon_products \";\n sbuffer << \"WHERE amazon_orders.description = amazon_products.name \";\n sbuffer << \"AND amazon_orders.id = \" << order_id << \";\";\n\n sql = sbuffer.str();\n\n /* Execute SQL query */\n result R(N.exec(sql));\n\n int whnum;\n string description;\n int count;\n // print our headers\n cout << \"whnum \" << \"description\" << \"count\" << endl;\n // print out results\n for (result::const_iterator c = R.begin(); c != R.end(); ++c) {\n whnum = c[0].as<int>();\n description = c[1].as<string>();\n count = c[2].as<int>();\n\n cout << \"whnum = \" << whnum << endl;\n cout << \"description = \" << description << endl;\n cout << \"count = \" << count << endl;\n }\n std::tuple<int, string, int> order_info;\n order_info = make_tuple(whnum, description, count);\n\n return order_info;\n}\n\nint getTruckidByShipid(connection *C, int ship_id) {\n\n nontransaction N(*C);\n string sql;\n stringstream sbuffer;\n\n sbuffer << \"SELECT truck_id \";\n sbuffer << \"FROM amazon_orders \";\n sbuffer << \"WHERE ship_id = \" << ship_id << \";\";\n\n sql = sbuffer.str();\n result R(N.exec(sql));\n\n int truck_id;\n // print out results\n for (result::const_iterator c = R.begin(); c != R.end(); ++c) {\n truck_id = c[0].as<int>();\n cout << \"truck_id = \" << truck_id << endl;\n } \n return truck_id;\n}\n\nvector<int> getShipidById(connection *C, int id) {\n\n nontransaction N(*C);\n string sql;\n stringstream sbuffer;\n\n sbuffer << \"SELECT ship_id, ship_addr_x, ship_addr_y \";\n sbuffer << \"FROM amazon_orders \";\n sbuffer << \"WHERE id = \" << id << \";\";\n\n sql = sbuffer.str();\n result R(N.exec(sql));\n\n int ship_id;\n int ship_addr_x;\n int ship_addr_y;\n // print out results\n for (result::const_iterator c = R.begin(); c != R.end(); ++c) {\n ship_id = c[0].as<int>();\n ship_addr_x = c[1].as<int>();\n ship_addr_y = c[2].as<int>();\n cout << \"ship_id = \" << ship_id << endl;\n cout << \"ship_addr_x = \" << ship_addr_x << endl;\n cout << \"ship_addr_y = \" << ship_addr_y << endl;\n\n } \n vector<int> order_info;\n order_info.push_back(ship_id);\n order_info.push_back(ship_addr_x);\n order_info.push_back(ship_addr_y);\n\n return order_info;\n}\n\nstring getUPSusername(connection *C, int ship_id) {\n\n nontransaction N(*C);\n string sql;\n stringstream sbuffer;\n\n sbuffer << \"SELECT amazon_amazonuser.ups_username \";\n sbuffer << \"FROM amazon_orders, amazon_amazonuser \";\n sbuffer << \"WHERE amazon_orders.ship_id = \" << ship_id << \";\";\n\n sql = sbuffer.str();\n result R(N.exec(sql));\n\n string ups_username;\n // print out results\n for (result::const_iterator c = R.begin(); c != R.end(); ++c) {\n ups_username = c[0].as<string>();\n cout << \"ship_id = \" << ups_username << endl;\n } \n return ups_username;\n}\n\n\n/**** handler functions ****/\n\nvoid connectToWorld(int world_id, int initwh_id, FileOutputStream * out) {\n AConnect a_connect;\n a_connect.set_worldid(world_id);\n cout << \"world_id set!\" << endl;\n\n AInitWarehouse * initwh = a_connect.add_initwh();\n cout << \"initwh init\" << endl;\n initwh->set_id(initwh_id);\n cout << \"initwh id set:\" << initwh->id() << endl;\n initwh->set_x(2);\n cout << \"initwh x set: \" << initwh->x() << endl;\n initwh->set_y(3);\n cout << \"initwh y set: \" << initwh->y() << endl;\n\n a_connect.set_isamazon(true);\n cout << \"isamazon set: \" << a_connect.isamazon() << endl;\n\n // send message\n bool sent = sendMesgTo(a_connect, out);\n if ( sent == false) {\n cout << \"cannot send message!\" << endl;\n }\n \n google::protobuf::ShutdownProtobufLibrary();\n}\n\n\nbool connectedToWorld(FileInputStream * in) {\n AConnected a_connected;\n while (recvMesgFrom(a_connected, in) == false) {\n // wait\n }\n\n std::cout << \"world_id = \" << a_connected.worldid() << std::endl;\n std::cout << a_connected.result() << std::endl;\n \n if (a_connected.result().compare(\"connected!\")) {\n return true;\n }\n else {\n return false;\n } \n}\n\n\n\n// product\n// AProduct* setAProduct(int id, string description, int count) {\n\n// AProduct* thing;\n// thing->set_id(id);\n// thing->set_description(description);\n// thing->set_count(count);\n\n// return thing;\n// }\n\n// purchaseMore\nvoid handleNewOrders(FileOutputStream * out) {\n int order_id = newOrders.front();\n newOrders.pop();\n // TODO: find info in database\n std::tuple<int, string, int> order_info = getOrderInfo(C, order_id);\n int whnum;\n string description;\n int count;\n tie (whnum, description, count) = order_info;\n // pack to APurchaseMore and acommands\n ACommands acommand; \n APurchaseMore * ap = acommand.add_buy();\n ap->set_whnum(whnum); // set whnum\n ap->set_seqnum(seqnum); // set seqnum\n // set products\n AProduct * product = ap->add_things();\n product->set_id(order_id);\n product->set_description(description);\n product->set_count(count);\n\n if (sendMesgTo(acommand, out) == false) { // send ack\n cout << \"cannot send APurchaseMore!\" << endl;\n }\n else {\n cout << \"APurchaseMore sent!\" << endl;\n }\n\n // send to world\n}\n\nvoid handleAPurchaseMore(APurchaseMore arrived, FileOutputStream * out) {\n goRequestTruck.push(arrived); // enqueue for ups socket to handle\n ::google::protobuf::int32 whnum = arrived.whnum();\n vector<AProduct> things;\n for (int j = 0; j < arrived.things_size(); j++) {\n things.push_back(arrived.things(j));\n } \n // put into acommand\n ACommands acommand;\n // set APack\n APack* apack = acommand.add_topack();\n apack->set_whnum(whnum); // set whnum\n AProduct * thing = apack->add_things();\n thing->set_id(things[0].id());\n thing->set_description(things[0].description());\n thing->set_count(things[0].count()); \n /* assign shipid */\n apack->set_shipid(shipid); \n shipid++;\n update_shipid(thing->id(), shipid); // in database\n apack->set_seqnum(seqnum); // set seqnum\n seqnum++;\n // set the seq of arrived as ack\n acommand.add_acks(arrived.seqnum());\n\n if (sendMesgTo(acommand, out) == false) { // send ack\n cout << \"cannot send APack!\" << endl;\n }\n else {\n cout << \"APack sent!\" << endl;\n }\n}\n\nvoid handleAPacked(APacked ready, FileOutputStream * out) {\n ACommands acommand;\n\n int ship_id = ready.shipid();\n orderPackedStatus[ship_id] = 1; // set flag to 1\n // set the seq of ready as ack\n acommand.add_acks(ready.seqnum());\n\n if (sendMesgTo(acommand, out) == false) { // send ack\n cout << \"cannot send ack for APacked!\" << endl;\n }\n else {\n cout << \"Ack for APacked sent!\" << endl;\n }\n}\n\nvoid handleALoaded(ALoaded loaded, FileOutputStream * out) {\n ACommands acommand;\n truckLoaded.push(loaded); // enqueue for ups socket to handle\n // set the seq of ready as ack\n acommand.add_acks(loaded.seqnum());\n\n if (sendMesgTo(acommand, out) == false) { // send ack\n cout << \"cannot send ack for ALoaded!\" << endl;\n }\n else {\n cout << \"Ack for ALoaded sent!\" << endl;\n }\n}\n\nvoid handleAPutOnTruck(FileOutputStream * out) {\n UATruckArrived truck_arrived = readyToLoad.front(); // get the first item in queue\n readyToLoad.pop();\n int ship_id = truck_arrived.shipid(); // get ship id\n if (orderPackedStatus[ship_id] == 1) { // if already packed\n ACommands acommand;\n // set APack\n APutOnTruck* load = acommand.add_load();\n load->set_whnum(1); // set whnum to 1\n load->set_truckid(truck_arrived.truckid()); // set shipid\n load->set_shipid(ship_id);\n load->set_seqnum(seqnum); // set seqnum\n seqnum++;\n // set the seq of arrived as ack\n acommand.add_acks(truck_arrived.seqnum());\n\n if (sendMesgTo(acommand, out) == false) { // send ack\n cout << \"cannot send APutOnTruck!\" << endl;\n }\n else {\n cout << \"APutOnTruck sent!\" << endl;\n }\n }\n else { // if haven't packed yet, put it back and keep waiting\n readyToLoad.push(truck_arrived);\n }\n}\n\n// // query\n// AQuery setAQuery(int packageid, int seqnum) {\n\n// }\n\nvoid handleAPackage(APackage packagestatus, FileOutputStream * out) {\n int ship_id = packagestatus.packageid(); // get shipid\n string status = packagestatus.status(); // get status\n // renew database\n update_status(C, ship_id, status);\n ACommands acommand;\n acommand.add_acks(packagestatus.seqnum());\n\n if (sendMesgTo(acommand, out) == false) { // send ack\n cout << \"cannot send ack for APackage!\" << endl;\n }\n else {\n cout << \"Ack for APackage sent!\" << endl;\n }\n}\n\n// AErr\n// ACommands handleAErr(AErr aerror, FileOutputStream * out) {\n\n// }\n\n// acks\nvoid handleAcks(::google::protobuf::int64 ack, FileOutputStream * out) {\n map<int, int>::iterator it;\n if ((it = ackRecv.find(ack)) != ackRecv.end()) { // if found seqnum\n it->second = 1; // set flag to 1\n }\n else {\n cerr << \"seqnum does not exist!\" << endl;\n }\n}\n\n// ACommands\n// void handleAResponses(AResponses aresponse, FileOutputStream * out) {\n // handle acks\n // for (int i = 0; i < aresponse.acks_size(); i++) {\n // ::google::protobuf::int64 ack = aresponse.acks(i);\n\n // std::thread (handleAcks, ack, out).detach();\n // // handleAcks(ack, out);\n // }\n // // handle APurchaseMore\n // for (int i = 0; i < aresponse.arrived_size(); i++) {\n // APurchaseMore arrived = aresponse.arrived(i);\n // std::thread (handleAPurchaseMore, arrived, out).detach();\n // // handleAPurchaseMore(arrived, out);\n // }\n // // handle APacked\n // for (int i = 0; i < aresponse.ready_size(); i++) {\n // APacked ready = aresponse.ready(i);\n // handleAPacked(ready, out);\n // }\n // // handle ALoaded\n // for (int i = 0; i < aresponse.loaded_size(); i++) {\n // ALoaded loaded = aresponse.loaded(i);\n // handleALoaded(loaded, out);\n // }\n // // handle APackage\n // for (int i = 0; i < aresponse.packagestatus_size(); i++) {\n // APackage packagestatus = aresponse.packagestatus(i);\n // handleAPackage(packagestatus, out);\n // }\n // // handle AErr\n // for (int i = 0; i < aresponse.error_size(); i++) {\n // AErr error = aresponse.error(i);\n // handleAErr(error, out);\n // }\n// }\n\n/* Amazon - UPS */\n\n// AUOrder, AUReqTruck\nvoid handleAUReqTruck(FileOutputStream * out) {\n APurchaseMore ap = goRequestTruck.front();\n goRequestTruck.pop();\n // get whnum\n int whnum = ap.whnum();\n AProduct thing = ap.things(0);\n int id = thing.id();\n string description = thing.description();\n // get shipid from database\n vector<int> order_info = getShipidById(C, id);\n int ship_id = order_info[0];\n int ship_addr_x = order_info[1];\n int ship_addr_y = order_info[2];\n string ups_username = getUPSusername(C, ship_id);\n\n AUCommands aucommand;\n AUReqTruck * req_truck = aucommand.add_requests();\n req_truck->set_warehouseid(whnum); // set whnum\n req_truck->set_shipid(ship_id); // set shipid\n req_truck->set_seqnum(seqnum); // set seqnum\n seqnum++;\n // set orders\n AUOrder * orders;\n orders->set_description(description);\n orders->set_locationx(ship_addr_x);\n orders->set_locationy(ship_addr_y);\n orders->set_username(ups_username);\n req_truck->set_allocated_orders(orders);\n\n if (sendMesgTo(aucommand, out) == false) { // send ack\n cout << \"cannot send AUReqTruck!\" << endl;\n }\n else {\n cout << \"AUReqTruck sent!\" << endl;\n } \n}\n\n// UATruckArrived\nvoid handleUATruckArrived(UATruckArrived truck_arrived, FileOutputStream * out) {\n int ship_id = truck_arrived.shipid();\n int truck_id = truck_arrived.truckid();\n setTruckid(C, ship_id, truck_id); // set truckid in database\n readyToLoad.push(truck_arrived);\n\n AUCommands aucommand;\n // set the seq as ack\n aucommand.add_acks(truck_arrived.seqnum());\n\n if (sendMesgTo(aucommand, out) == false) { // send ack\n cout << \"cannot send ack for UATruckArrived!\" << endl;\n }\n else {\n cout << \"Ack for UATruckArrived sent!\" << endl;\n }\n}\n\n// AUTruckLoaded\nvoid handleAUTruckLoaded(FileOutputStream * out) {\n ALoaded loaded = truckLoaded.front();\n truckLoaded.pop();\n int ship_id = loaded.shipid();\n int truck_id = getTruckidByShipid(C, ship_id);\n\n AUCommands aucommand;\n AUTruckLoaded * autruck_loaded = aucommand.add_truckloaded();\n autruck_loaded->set_truckid(truck_id);\n autruck_loaded->set_shipid(shipid);\n autruck_loaded->set_seqnum(seqnum);\n seqnum++;\n\n if (sendMesgTo(aucommand, out) == false) { // send ack\n cout << \"cannot send AUTruckLoaded!\" << endl;\n }\n else {\n cout << \"AUTruckLoaded sent!\" << endl;\n }\n\n}\n\n// UAPackageArrived\nvoid handleUAPackageArrived(UAPackageArrived package_arrived, FileOutputStream * out) {\n int ship_id = package_arrived.shipid();\n update_status(C, ship_id, \"delivered\");\n // TODO: set truckArrived to 1 (can't remember what it was..)\n AUCommands aucommand;\n // set the seq as ack\n aucommand.add_acks(package_arrived.seqnum());\n\n if (sendMesgTo(aucommand, out) == false) { // send ack\n cout << \"cannot send ack for UAPackageArrived!\" << endl;\n }\n else {\n cout << \"Ack for UAPackageArrived sent!\" << endl;\n }\n}\n\n// Errors\n// UAErr setError(string error, int org_seqnum, int seqnum);\n// void handleError(UAErr uaerror, FileOutputStream * out) {\n\n// }\n\n// UACommands\n// void handleUACommands(UACommands uacommand) {\n // handle acks\n // for (int i = 0; i < uacommand.acks_size(); i++) {\n // ::google::protobuf::int64 ack = uacommand.acks(i);\n // handleAcks(ack, ups.in);\n // }\n // // handle UATruckArrived\n // for (int i = 0; i < uacommand.truckarrived_size(); i++) {\n // UATruckArrived truckarrived = uacommand.truckarrived(i);\n // handleUATruckArrived(truckarrived, ups.in);\n // }\n // // handle UAPackageArrived\n // for (int i = 0; i < uacommand.packagearrived_size(); i++) {\n // UAPackageArrived packagearrived = uacommand.packagearrived(i);\n // handleUAPackageArrived(packagearrived, ups.in);\n // }\n // // handle AErr\n // for (int i = 0; i < uacommand.uaerror_size(); i++) {\n // UAErr error = uacommand.uaerror(i);\n // handleError(error, ups.in);\n // }\n// }"
},
{
"alpha_fraction": 0.6316321492195129,
"alphanum_fraction": 0.6387064456939697,
"avg_line_length": 26.47222137451172,
"blob_id": "769f96ef631ff028b56f93e142d96ffbe662bcd6",
"content_id": "5c412b960f629b7f8005a79fd2692ca33398ac21",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1987,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 72,
"path": "/erss-project-js895-hy165-master/Back-End/gpb_test.cpp",
"repo_name": "Ericsun01/mini-Amazon",
"src_encoding": "UTF-8",
"text": "#include <arpa/inet.h>\n#include <assert.h>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <netdb.h>\n#include <netinet/in.h>\n#include <string>\n#include <sys/socket.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <vector>\n#include <sys/time.h>\n#include <google/protobuf/io/coded_stream.h>\n#include <google/protobuf/io/zero_copy_stream_impl.h>\n\n#include \"world_amazon.pb.h\"\n#include \"amazon_ups.pb.h\"\n#include \"interact.h\"\n#include \"frontserver.h\"\n#include \"UPSServer.h\"\n#include \"WorldSocket.h\"\n// #include \"gpb_test.h\"\n#include \"parseMsg.h\"\n\nusing namespace google::protobuf::io;\nusing namespace std;\n\nint main(void) {\n\n WorldSocket worldclient;\n\n worldclient.connect_server(\"vcm-13673.vm.duke.edu\", \"23456\");\n cout << \"fd: \" << worldclient.socket_fd << endl;\n worldclient.out = new FileOutputStream(worldclient.socket_fd); // send\n worldclient.in = new FileInputStream(worldclient.socket_fd); // 开头设定 recv\n\n // send gpb message for test\n AConnect a_connect;\n // a_connect.set_worldid(1);\n // cout << \"world_id set!\" << endl;\n\n AInitWarehouse * initwh = a_connect.add_initwh();\n initwh->set_id(2);\n cout << \"initwh id:\" << initwh->id() << endl;\n initwh->set_x(2);\n cout << \"initwh x: \" << initwh->x() << endl;\n initwh->set_y(3);\n cout << \"initwh y: \" << initwh->y() << endl;\n\n a_connect.set_isamazon(true);\n cout << \"isamazon: \" << a_connect.isamazon() << endl;\n\n // cout << \"outstream defined\" << endl;\n bool sent = sendMesgTo(a_connect, worldclient.out);\n if ( sent == false) {\n cout << \"cannot send message!\" << endl;\n }\n\n AConnected a_connected;\n if (recvMesgFrom(a_connected, worldclient.in) == false) {\n cout << \"Failed to recv message!\" << endl;\n }\n std::cout << a_connected.worldid() << std::endl;\n std::cout << a_connected.result() << std::endl;\n\n google::protobuf::ShutdownProtobufLibrary();\n\n return EXIT_SUCCESS;\n \n}\n\n"
},
{
"alpha_fraction": 0.5086419582366943,
"alphanum_fraction": 0.5925925970077515,
"avg_line_length": 21.5,
"blob_id": "9a89050f3cee92ec5726d9478a57e166a01c87d0",
"content_id": "b06ea5cf27400157cb6b941f3fd983a091329934",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 405,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 18,
"path": "/erss-project-js895-hy165-master/Front-End/erss_amazon/amazon/migrations/0005_orders_status.py",
"repo_name": "Ericsun01/mini-Amazon",
"src_encoding": "UTF-8",
"text": "# Generated by Django 3.0.4 on 2020-04-16 15:06\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('amazon', '0004_auto_20200416_0203'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='orders',\n name='status',\n field=models.CharField(default='Confirmed', max_length=100),\n ),\n ]\n"
},
{
"alpha_fraction": 0.595646858215332,
"alphanum_fraction": 0.6005517840385437,
"avg_line_length": 24.286821365356445,
"blob_id": "06a2e4608f3a2969c4c41460ef7b0f35f7ea93e3",
"content_id": "2ff8a39daaf036acfae5e20a0a6b861b570d34c1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3262,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 129,
"path": "/erss-project-js895-hy165-master/Back-End/frontserver.h",
"repo_name": "Ericsun01/mini-Amazon",
"src_encoding": "UTF-8",
"text": "#ifndef _FRONTSERVER_\n#define _FRONTSERVER_\n\n#include <arpa/inet.h>\n#include <assert.h>\n#include <cstdio>\n#include <cstdlib>\n#include <cstring>\n#include <iostream>\n#include <netdb.h>\n#include <netinet/in.h>\n#include <string>\n#include <sys/socket.h>\n#include <sys/types.h>\n#include <unistd.h>\n#include <vector>\n#include <sys/time.h>\n#include <thread>\n#include <queue>\n#include <mutex>\n#include <fstream>\n#include <time.h>\n\n// #include \"server.h\"\n\nusing namespace std;\n\nclass FrontServer {\n\n public:\n struct addrinfo host_info, *host_info_list;\n int newfd;\n int sockfd; \n int status;\n\n FrontServer() {}\n\n void initialize(const char *_port);\n void createSocket();\n int acceptConnection();\n\n void buildServer(const char *port);\n \n // void recv_order_id() {\n // int client_fd = acceptConnection();\n // char buffer[128];\n // int len = recv(client_fd, buffer, sizeof(buffer), 0);\n // if (len == -1) {\n // perror(\"recv\");\n // }\n // buffer[len] = 0;\n // // DEBUG\n // cout << \"Server received: \" << buffer << endl;\n // }\n\n // destructor\n ~FrontServer() {\n // close(sockfd);\n }\n\n};\n\nvoid FrontServer::initialize(const char *_port) {\n cout << \"enter FrontServer initialize\" << endl;\n memset(&host_info, 0, sizeof(host_info));\n host_info.ai_family = AF_UNSPEC;\n host_info.ai_socktype = SOCK_STREAM;\n host_info.ai_flags = AI_PASSIVE;\n\n cout << \"Front server start getting addrinfo\" << endl;\n status = getaddrinfo(NULL, _port, &host_info, &host_info_list);\n if (status != 0) {\n std::cerr << \"Error: FrontServer cannot get address info for host\" << std::endl;\n exit(EXIT_FAILURE);\n }\n cout << \"addrinfo get\" << endl;\n}\n\n\nvoid FrontServer::createSocket() {\n cout << \"Front server enter createsocket\" << endl;\n sockfd = socket(host_info_list->ai_family, host_info_list->ai_socktype,\n host_info_list->ai_protocol);\n if (sockfd == -1) {\n std::cerr << \"FrontServer cannot create socket\" << std::endl;\n exit(EXIT_FAILURE);\n } \n\n int yes = 1;\n status = setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &yes, sizeof(int));\n status = bind(sockfd, host_info_list->ai_addr, host_info_list->ai_addrlen);\n if (status == -1) {\n std::cerr << \"FrontServer cannot bind socket\" << std::endl;\n exit(EXIT_FAILURE);\n } \n\n status = listen(sockfd, 100);\n if (status == -1) {\n std::cerr << \"FrontServer cannot listen on socket\" << std::endl;\n exit(EXIT_FAILURE);\n }\n // debug\n cout << \"Front server Waiting for connection...\" << endl; \n\n freeaddrinfo(host_info_list);\n}\n\nint FrontServer::acceptConnection() {\n //int newfd;\n struct sockaddr_storage socket_addr;\n socklen_t socket_addr_len = sizeof(socket_addr);\n newfd = accept(sockfd, (struct sockaddr *)&socket_addr, &socket_addr_len);\n if (newfd == -1) {\n std::cerr << \"Error: FrontServer cannot accept connection on socket\" << std::endl;\n exit(EXIT_FAILURE);\n } // if\n\n return newfd;\n}\n\nvoid FrontServer::buildServer(const char *port) {\n // debug\n cout << \"enter FrontServer\" << endl;\n initialize(port);\n createSocket();\n}\n\n\n#endif\n"
},
{
"alpha_fraction": 0.8256880640983582,
"alphanum_fraction": 0.8256880640983582,
"avg_line_length": 23.33333396911621,
"blob_id": "782f65d247a8fe0e2b14630a48de0da3ca713b85",
"content_id": "e7feb00b683aede5f0835361040a3d4b848eb389",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 218,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 9,
"path": "/erss-project-js895-hy165-master/Front-End/erss_amazon/amazon/admin.py",
"repo_name": "Ericsun01/mini-Amazon",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\n\nfrom .models import AmazonUser, Department, Products, Orders\n\n\nadmin.site.register(AmazonUser)\nadmin.site.register(Department)\nadmin.site.register(Products)\nadmin.site.register(Orders)"
}
] | 18 |
basketballandlearn/MRC_Competition_Repositories | https://github.com/basketballandlearn/MRC_Competition_Repositories | 184f5f2c5e5b17297fb8688a2ee650895bacb872 | 88238267031a2d8745355a4cdeaf159412f95ce0 | 7f2e68759d2d41c19014d30c971244a9c386d6b7 | refs/heads/master | 2023-04-19T04:05:29.860030 | 2022-10-14T12:57:57 | 2022-10-14T12:57:57 | 189,688,627 | 29 | 2 | null | null | null | null | null | [
{
"alpha_fraction": 0.6253702044487,
"alphanum_fraction": 0.6547384262084961,
"avg_line_length": 33.623931884765625,
"blob_id": "9c6063e0ae2ef57ec9ae29a4cc1d1c0f0edb8144",
"content_id": "e9ed373c4eef651b613622395e1fdc6d6c21dff3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 6691,
"license_type": "no_license",
"max_line_length": 194,
"num_lines": 117,
"path": "/README.md",
"repo_name": "basketballandlearn/MRC_Competition_Repositories",
"src_encoding": "UTF-8",
"text": "## 机器阅读理解预训练模型及代码开源\n\n\n*********************** **更新** ***********************\n* 5/21:开源**基于大规模MRC数据再训练**的模型(包括`roberta-wwm-large`、`macbert-large`)\n* 5/18:开源比赛代码\n\n\n## Contents\n - [基于大规模MRC数据再训练的模型](#基于大规模MRC数据再训练)\n - [仓库介绍](#仓库介绍)\n - [运行流程](#运行流程)\n - [小小提示](#小小提示)\n\n\n## 基于大规模MRC数据再训练\n\n此库发布的再训练模型,在 阅读理解/分类 等任务上均有大幅提高<br/>\n(已有多位小伙伴在 Dureader、法研杯、医疗问答 等多个比赛中取得**top5**的好成绩😁)\n\n| 模型/数据集 | Dureader-2021 | tencentmedical |\n| ------------------------------------------|--------------- | --------------- |\n| | F1-score | Accuracy |\n| | dev / A榜 | test-1 |\n| macbert-large (哈工大预训练语言模型) | 65.49 / 64.27 | 82.5 |\n| roberta-wwm-ext-large (哈工大预训练语言模型) | 65.49 / 64.27 | 82.5 |\n| macbert-large (ours) | 70.45 / **68.13**| **83.4** |\n| roberta-wwm-ext-large (ours) | 68.91 / 66.91 | 83.1 |\n\n\n* **数据来源**\n * 网上收集的大量中文MRC数据\n (其中包括公开的MRC数据集以及自己爬取的网页数据等,\n 囊括了医疗、教育、娱乐、百科、军事、法律、等领域。)\n\n* **数据构造**\n * 清洗\n * 舍弃:context>1024的舍弃、question>64的舍弃、网页标签占比超过30%的舍弃。\n * 重新标注:若answer>64且不完全出现在文档中,则采用模糊匹配: 计算所有片段与answer的相似度(F1值),取相似度最高的且高于阈值(0.8)\n * 数据标注\n * 收集的数据有一部分是不包含的位置标签的,仅仅是(问题-文章-答案)的三元组形式。\n 所以,对于只有答案而没有位置标签的数据通过正则匹配进行位置标注:<br/>\n ① 若答案片段多次出现在文章中,选择上下文与问题最相似的答案片段作为标准答案(使用F1值计算相似度,答案片段的上文48和下文48个字符作为上下文);<br/>\n ② 若答案片段只出现一次,则默认该答案为标准答案。\n * 采用滑动窗口将长文档切分为多个重叠的子文档,故一个文档可能会生成多个有答案的子文档。\n * 无答案数据构造\n * 在跨领域数据上训练可以增加数据的领域多样性,进而提高模型的泛化能力,而负样本的引入恰好能使得模型编码尽可能多的数据,加强模型对难样本的识别能力:<br/>\n ① 对于每一个问题,随机从数据中捞取context,并保留对应的title作为负样本;(50%)<br/>\n ② 对于每一个问题,将其正样本中答案出现的句子删除,以此作为负样本;(20%)<br/>\n ③ 对于每一个问题,使用BM25算法召回得分最高的前十个文档,然后根据得分采样出一个context作为负样本,\n 对于非实体类答案,剔除得分最高的context(30%)\n* **用途** \n * 此mrc模型可直接用于`open domain`,[点击体验](https://huggingface.co/luhua/chinese_pretrain_mrc_roberta_wwm_ext_large)\n * 将此模型放到下游 MRC/分类 任务微调可比直接使用预训练语言模型提高`2个点`/`1个点`以上\n* **合作**\n * 相关训练数据以及使用更多数据训练的模型/一起打比赛 可邮箱联系([email protected])~ \n \n```\n----- 使用方法 -----\nfrom transformers import AutoTokenizer, AutoModelForQuestionAnswering\n\nmodel_name = \"chinese_pretrain_mrc_roberta_wwm_ext_large\" # \"chinese_pretrain_mrc_macbert_large\"\n\n# Use in Transformers\ntokenizer = AutoTokenizer.from_pretrained(f\"luhua/{model_name}\")\nmodel = AutoModelForQuestionAnswering.from_pretrained(f\"luhua/{model_name}\")\n\n# Use locally(通过 https://huggingface.co/luhua 下载模型及配置文件)\ntokenizer = BertTokenizer.from_pretrained(f'./{model_name}')\nmodel = AutoModelForQuestionAnswering.from_pretrained(f'./{model_name}')\n```\n\n## 仓库介绍\n* **目的**\n * **开源了基于MRC数据再训练的模型**,在MRC任务下微调,效果大幅优于使用预训练的语言模型,其次,旨在提供一个效果不错的`强基线`\n * 有些[mrc比赛](#比赛)由于\"年代久远\"整理不过来(`others`文件夹),但方案和代码都有,对比着看就看懂了\n* **优化**\n * 代码基于Hugginface的squad代码。之前自己开发,版本多且许多细节没有考虑,便转移到squad代码上迭代。但其实现的类缺乏对中文的支持,推理结果有一些影响,**修改之后 此库能较好的支持中文,抽取的答案精度也尽可能不受影响**\n \n\n## 运行流程\n\n脚本参数解释\n\n* `--lm`: 要加载的模型的文件夹名称\n* `--do_train`: 开启训练\n* `--evaluate_during_training`: 开启训练时的验证\n* `--do_test`: 开启预测\n* `--version_2_with_negative`: 开启适配于数据中有`无答案数据`(如:squad2.0、dureader2021)\n* `--threads`: 数据处理所使用的线程数(可以通过os.cpu_count()查看机器支持的线程数)\n \n##### 一、数据 & 模型:\n* 将train、dev、test等数据放在datasets文件夹下(样例数据已给出,符合格式即可)\n* 通过 export lm=xxx 指定模型目录\n\n##### 二、一键运行\n```python \nsh train_bert.sh # sh test_bert.sh\n```\n\n##### 三、无答案问题\n* 如果包含无答案类型数据(如:squad2.0、dureader2021),加入--version_2_with_negative就行\n* 将数据替换为Dureader2021_checklist的数据, 加入--version_2_with_negative即可\n\n\n## 小小提示:\n* 代码上传前已经跑通。文件不多,所以如果碰到报错之类的信息,可能是代码路径不对、缺少安装包等问题,一步步解决,可以提issue\n* 环境\n ```\n pip install transformers==2.10.0 \n ```\n* 代码基于transformers 2.10.0版本,但是预训练模型可以使用其他版本加载。转换为tf可使用[转换](https://github.com/huggingface/transformers/blob/master/src/transformers/models/bert/convert_bert_pytorch_checkpoint_to_original_tf.py)\n* 预训练相关参数 [参考](https://github.com/basketballandlearn/MRC_Competition_Dureader/issues/33)\n\n\n## 感谢\n[zhangxiaoyu](https://github.com/Decalogue) [zhongjialun](https://github.com/slaxes) [huanghui](https://github.com/huanghuidmml) [nanfulai](https://github.com/nanfulai)\n\n"
},
{
"alpha_fraction": 0.6377952694892883,
"alphanum_fraction": 0.7007874250411987,
"avg_line_length": 23,
"blob_id": "237846ed7a457199e6f14b98767fe011b540b351",
"content_id": "689e33e9d47e4d44a07f869798e32bbecc7c9434",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 127,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 5,
"path": "/others/idiom_MRC/知识蒸馏/Makefile",
"repo_name": "basketballandlearn/MRC_Competition_Repositories",
"src_encoding": "UTF-8",
"text": "\r\ntrain:\r\n\tCUDA_VISIBLE_DEVICES=0,1,2,3,4,5,7 python train.py\r\n\r\ntest:\r\n\tCUDA_VISIBLE_DEVICES=6 python result.py --do_predict\r\n"
},
{
"alpha_fraction": 0.7174238562583923,
"alphanum_fraction": 0.7523714303970337,
"avg_line_length": 33.534481048583984,
"blob_id": "c155359119276ba3c5a3551ae47418ba65881b0c",
"content_id": "12a1dcdda08c21aedf5709fda6727a7c9c144d31",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3285,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 58,
"path": "/others/Dureader_2019/README.md",
"repo_name": "basketballandlearn/MRC_Competition_Repositories",
"src_encoding": "UTF-8",
"text": "# Dureader-Bert\n2019 Dureader机器阅读理解 单模型代码。\n\n### 哈工大讯飞联合实验室发布的中文全词覆盖BERT\n[论文地址]( https://arxiv.org/abs/1906.08101) \n[预训练模型下载地址]( https://github.com/ymcui/Chinese-BERT-wwm) \n* 只需将要加载的预训练模型换为压缩包内的chinese_wwm_pytorch.bin,即修改from_pretrained函数中weights_path和config_file即可。\n\n### 谷歌发布的中文bert与哈工大发布的中文全词覆盖BERT在Dureader上的效果对比\n\n| 模型 | ROUGE-L | BLEU-4 |\n| ------ | ------ | ------ |\n| 谷歌bert | 49.3 | 50.2 | \n| 哈工大bert| 50.32 | 51.4 |\n\n由于官方没有给出测试集,实验数据是在验证集上跑出来的\n\n## 许多人询问,说明一下:\n* 1、由于涉及多文档,故不用squad的数据处理,数据输入符合就行,也可以自己重写\n* 2、比赛提升主要使用 Multi-task训练、以及答案抽取,由于代码繁重,故这份代码只有单任务训练\n\n## 代码:\n* 代码主要删减大量不必要代码,也将英文的数据处理改为中文的数据处理,方便阅读和掌握bert的代码。\n* handle_data文件夹是处理Dureader的数据,与比赛有关,与bert没有多大关系。\n* dataset文件夹是处理中文数据的代码,大致是将文字转化为bert的输入:(inputs_ids,token_type_ids,input_mask), 然后做成dataloader。\n* predict文件夹是用来预测的,基本与训练时差不多,一些细节不一样(输出)。\n* 总的来说,只要输入符合bert的输入:(inputs_ids,token_type_ids,input_mask)就可以了。\n\n## 小小提示:\n* 竞赛最终结果第七名, ROUGE-L:53.62, BLEU-4:54.97\n* 代码上传前已经跑通,所以如果碰到报错之类的信息,可能是代码路径不对、缺少安装包等问题,一步步解决,可以提issue。\n\n### 环境(不支持cpu)\n* python3 \n* torch 1.0\n* 依赖包 pytorch-pretrained-bert、tqdm、pickle、torchtext\n\n### Reference\n [Bert论文](https://arxiv.org/pdf/1810.04805.pdf) \n [Dureader](https://github.com/baidu/DuReader) \n [Bert中文全词覆盖论文]( https://arxiv.org/abs/1906.08101) \n [pytorch-pretrained-BERT](https://github.com/huggingface/pytorch-pretrained-BERT)\n\n### 运行流程 \n###### 一、数据处理:\n* 将trainset、devset等数据放在data文件里 (data下的trainset、devset有部份数据,可以换成全部数据。)\n* 到handle_data目录下运行 sh run.sh --para_extraction, 便会将处理后的数据放在extracted下的对应文件夹里\n###### 二、制作dataset:\n* 到dataset目录下运行两次 python3 run_squad.py,分别生成train.data与dev.data,第一次运行结束后要修改run_squad.py的参数,具体做法run_squad.py末尾有具体说明\n###### 三、训练:\n* 到root下运行 python3 train.py,边训练边验证\n###### 四、测试:\n* 到predict目录下运行 python3 util.py (测试集太多,也可以在该文件里将路径改为验证集,默认为验证集路径)\n* 运行 python3 predicting.py\n* 到metric目录下, 运行 python3 mrc_eval.py predicts.json ref.json v1 即可\n\n#### 排行榜:\n\n"
},
{
"alpha_fraction": 0.7396449446678162,
"alphanum_fraction": 0.7522189617156982,
"avg_line_length": 38.14706039428711,
"blob_id": "125ee6b37ae30864168cc9159750ed14e1b75ae3",
"content_id": "74170dcf1cc3c3038fb6bd8184ad1eb9c5cc6812",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2628,
"license_type": "no_license",
"max_line_length": 233,
"num_lines": 34,
"path": "/others/Epidemic_QA_Assistant/README.md",
"repo_name": "basketballandlearn/MRC_Competition_Repositories",
"src_encoding": "UTF-8",
"text": "\n## 最终排名:冠军\n\n### 比赛介绍\n\n* 比赛名称:科技战役-疫情政务问答助手\n* [比赛链接](https://www.datafountain.cn/special/BJSJ/talent)\n\n* 疫情政务问答助手比赛提供以疫情相关的**政策数据集**、用户问题以及标注好的答案,其中答案片段一定出现在政策数据集中,因此可以认为答案一定是文档中的一个片段(span)\n* 本队将该赛题看成多文档阅读理解任务(Multi-Document Machine Reading Comprehension, MDMRC),这一问题已经在学术界有了较多的研究。大部分的研究将MDMRC分解为文档检索任务和抽取型阅读理解任务,**其中文档检索任务在文档库中检索到和问题最相关的若干文档,抽取型阅读理解任务在从检索到的文档中抽取问题对应的答案片段**。这种框架形式较为灵活,可以在不同的子任务中尝试不同的方法,然后再将子任务的结果组合得到最终答案。\n\n### 队伍介绍\n\n* 队伍名称:中国加油-湖北加油\n* 成员介绍\n * 陆华、钟嘉伦和王力来自**华中科技大学Dian团队AI实验室**,组内研究方向包括自然语言处理、计算机视觉等。\n * 余嘉豪是**北京邮电大学**本科三年级在读生,现在在**北京大学王选计算机研究所**严睿老师团队下实习,该团队致力于人机对话、认知计算等自然语言处理方向的研究。\n * 张原来自**北京来也网络科技有限公司**。北京来也网络科技有限公司创办于2015年,致力于做人机共生时代具备全球影响力的智能机器人公司)。\n\n### 方法概要\n\n* 本队采用了**文档检索-阅读理解框架**,使用了预训练模型、**召回优化**、**负样本选择策略**、**多任务训练**等方法辅助模型训练,最后通过模型融合得到了在测试集(A榜)0.744的Rouge-L分数,**排名第一**,验证了自然语言处理可以有效应用于实际生活中。\n\n### ppt分享\n\n* 本队的答辩ppt已上传,供大家学习交流(时间匆忙,所以ppt制作得比较粗糙)\n\n### 比赛结果\n\n* A榜和B榜得分均top1\n\n* <center class=\"half\">\n <img src=\"https://github.com/basketballandlearn/MRC_Competition_Dureader/tree/master/others/Epidemic_QA_Assistant/image/B榜排名.PNG\" alt=\"B榜排名\" width = \"45%\" align=right style=\"zoom: 20%;\" />\n <img src=\"https://github.com/basketballandlearn/MRC_Competition_Dureader/tree/master/others/Epidemic_QA_Assistant/image/A榜排名.PNG\" alt=\"A榜排名\" width = \"45%\" align=left style=\"zoom: 20%;\" />\n <center>\n\n \n\t\n \t \n \n \n"
},
{
"alpha_fraction": 0.592334508895874,
"alphanum_fraction": 0.6803135871887207,
"avg_line_length": 26.75,
"blob_id": "153753d490f8a6321cd71fbdafb1eaebeb2b6a29",
"content_id": "de1b4b354cbf19fc1221ea95129666dc37da95c7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1204,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 40,
"path": "/others/Epidemic_QA_Assistant/epidemic_qa/args.py",
"repo_name": "basketballandlearn/MRC_Competition_Repositories",
"src_encoding": "UTF-8",
"text": "import torch\r\n\r\ncontext_data = './data/NCPPolicies_context_20200301.csv'\r\ntrain_data = './data/NCPPolicies_train_20200301.csv'\r\ntest_data = './data/NCPPolicies_test.csv'\r\n\r\nsplit_train_data = './data/train_data.json'\r\nsplit_dev_data = './data/dev_data.json'\r\n\r\nprocess_split_train_data = './data/pro_train_data.json'\r\nprocess_split_dev_data = './data/pro_dev_data.json'\r\n\r\nid_dev = './data/dev_id.json'\r\nid_train = './data/train_id.json'\r\n\r\nmax_para_num = 30 # 使用f1召回的数量\r\n\r\n# model and optimizer\r\nepoch = 2\r\nbatch_size = 4\r\ndata_num = 12524 #{'noans': 6316, 'hasans': 6208}\r\ngradient_accumulation_steps = 6\r\nnum_train_optimization_steps = int(data_num / gradient_accumulation_steps / batch_size) * epoch\r\nlog_step = int(data_num / batch_size / 3)\r\n\r\nbest_model_path = './checkpoints/best_model.pth'\r\n\r\n# 数据处理\r\npad_id = 0\r\ngt_score = 0.7\r\nmax_recall_para_len= 3000\r\nmax_c_len = 490\r\nmax_ans_len = 170\r\n# other\r\ndevice = torch.device(\"cuda\", 0)\r\nseed = 4\r\n\r\n# 原始cls_logit没有影响,softmax的verify77.9, 不过:0.7828 mean:0.7838 cls_logit*5:0.7836\r\n# soft_label + 0.2*verify: 0.7838,0.2*verify: 0.7743,soft_label:0.7709,pure:0.7794\r\n# bert_recall_top15:0.7061"
}
] | 5 |
PythooonUser/death-counter | https://github.com/PythooonUser/death-counter | d41da1263e1b5a3aca5ed257cf685ca5d275d39d | 0728c216f94395436d458ad2b673bd2f87083770 | 72c11f3507f8063c2b4fccd71e44ba9d09ca38c4 | refs/heads/master | 2020-05-03T06:49:45.898202 | 2019-03-29T22:39:08 | 2019-03-29T22:39:08 | 178,483,031 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7300000190734863,
"alphanum_fraction": 0.734000027179718,
"avg_line_length": 24,
"blob_id": "421d35111346f0570196d92836f1411ba1ed443b",
"content_id": "6acb469f2211680d181103751baba0162ed438a7",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 500,
"license_type": "permissive",
"max_line_length": 96,
"num_lines": 20,
"path": "/README.md",
"repo_name": "PythooonUser/death-counter",
"src_encoding": "UTF-8",
"text": "# death-counter\n\n\n\nInstall Python dependencies listed in `requirements.txt`.\n\nCreate `deaths.dat` file and link it to a Text object in OBS.\n\nAdjust counter text to your needs.\n\nRun\n```shell\n$ python death-counter.py\n```\nand terminate with `Ctrl + C`.\n\nHotkey | Action\n-- | --\n`F1` | Count Up\n`F2` | Count Down\n"
},
{
"alpha_fraction": 0.5353773832321167,
"alphanum_fraction": 0.5448113083839417,
"avg_line_length": 21.3157901763916,
"blob_id": "ce49d91f2cb225086436889a469d7ffc40a47209",
"content_id": "75d33d350a9a9c5b2cf4b24f7fe58554ed37ac6b",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 848,
"license_type": "permissive",
"max_line_length": 53,
"num_lines": 38,
"path": "/death-counter.py",
"repo_name": "PythooonUser/death-counter",
"src_encoding": "UTF-8",
"text": "import time\nimport keyboard\n\n\nclass DeathCounter(object):\n def __init__(self):\n with open(\"deaths.dat\") as file:\n self.deaths = int(file.read().split()[1])\n\n keyboard.on_press_key(\"f1\", self.increment)\n keyboard.on_press_key(\"f2\", self.decrement)\n\n def increment(self, event):\n self.deaths += 1\n self.update_file()\n\n def decrement(self, event):\n self.deaths -= 1\n self.update_file()\n\n def update_file(self):\n with open(\"deaths.dat\", mode=\"w\") as file:\n file.write(\"deaths: \" + str(self.deaths))\n\n def run(self):\n while True:\n try:\n time.sleep(0.25)\n except KeyboardInterrupt:\n return\n\n\ndef main():\n death_counter = DeathCounter()\n death_counter.run()\n\nif __name__ == '__main__':\n main()\n"
}
] | 2 |
Qalb-E-Abbas/Cost-Function-ML | https://github.com/Qalb-E-Abbas/Cost-Function-ML | 877b62046d45a00b9c1f7e1f228083d73027ccba | a2aa2367f0380d0e7677bd3cfc66ab2557956a9c | 41e672d2c77eebc1b13c68b5a51e8e3faff0fab9 | refs/heads/main | 2023-02-10T18:47:49.089789 | 2021-01-05T13:37:24 | 2021-01-05T13:37:24 | 327,008,712 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.650897204875946,
"alphanum_fraction": 0.6680260896682739,
"avg_line_length": 16.238805770874023,
"blob_id": "b9591aa9b08d092a74d5f7adf62277d2360adc30",
"content_id": "c1dea31f6c19018cd960f21428b37933c3be58eb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1226,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 67,
"path": "/Cost function.py",
"repo_name": "Qalb-E-Abbas/Cost-Function-ML",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\r\n\"\"\"\r\nCreated on Tue Jan 5 17:51:23 2021\r\n\r\n@author: Qalbe\r\n\"\"\"\r\n\r\n#imports\r\nimport pandas as pd\r\nimport matplotlib.pyplot as plt\r\nfrom sklearn.linear_model import LinearRegression\r\nfrom sklearn.metrics import mean_squared_error, r2_score\r\n\r\n\r\n\r\n#reading file\r\nfile = pd.read_csv(\"homeprices.csv\")\r\nfile\r\n\r\n\r\n#diving into x and y\r\nX=file.iloc[:,1].values.reshape(-1, 1)\r\ny=file.iloc[:,:-1].values\r\n\r\n\r\n\r\n# sckit-learn implementation\r\n\r\n# Model initialization\r\nregression_model = LinearRegression()\r\n\r\n# Fit the data(train the model)\r\nregression_model.fit(X, y)\r\n\r\n\r\n\r\n# Predict\r\ny_predicted = regression_model.predict(X)\r\n\r\n\r\n\r\n# model evaluation\r\nrms = mean_squared_error(y, y_predicted)\r\nr2 = r2_score(y, y_predicted)\r\n\r\n\r\n# printing values\r\nprint('Slope:' ,regression_model.coef_)\r\nprint('Intercept:', regression_model.intercept_)\r\nprint('Root mean squared error: ', rms)\r\nprint('R2 score: ', r2)\r\n\r\n\r\n# plotting values\r\nplt.plot(X, y, color = 'g')\r\nplt.xlabel('x')\r\nplt.ylabel('y')\r\n\r\n\r\n# predicted values\r\nplt.plot(X, y_predicted, color='r')\r\nplt.show()\r\n\r\n\r\n# predicted values, just checking difference through graph\r\nplt.scatter(y,y_predicted, color = 'purple', marker = '*')\r\nplt.show()\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.7368420958518982,
"alphanum_fraction": 0.7368420958518982,
"avg_line_length": 18,
"blob_id": "55cd6d367b83f7d17ee8f8e52414e8897e0178fb",
"content_id": "87e561eddb6994d7efb8378f1fa8f2158702ffde",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 19,
"license_type": "no_license",
"max_line_length": 18,
"num_lines": 1,
"path": "/README.md",
"repo_name": "Qalb-E-Abbas/Cost-Function-ML",
"src_encoding": "UTF-8",
"text": "# Cost-Function-ML\n"
}
] | 2 |
Wenling/Vote4Whatever | https://github.com/Wenling/Vote4Whatever | 1548b0156b58c5a80ed3915d015830f2eb56540a | e6d8fe6d543e9fa5955e3bc53e733484d7bee2f8 | 7a369f694111b7bd8dbba3c1b46f4cc7ed01f96b | refs/heads/master | 2016-09-05T09:32:35.507982 | 2012-12-18T21:46:36 | 2012-12-18T21:46:36 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.47911423444747925,
"alphanum_fraction": 0.6381479501724243,
"avg_line_length": 48.70000076293945,
"blob_id": "cf795a7b677f3437a82176e916f2ce6d3e2b7a88",
"content_id": "d44d2ec7c1c20e9de043175347ac24110712a732",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1987,
"license_type": "no_license",
"max_line_length": 180,
"num_lines": 40,
"path": "/js/prettify.js",
"repo_name": "Wenling/Vote4Whatever",
"src_encoding": "UTF-8",
"text": "{\\rtf1\\ansi\\ansicpg1252\\cocoartf1138\\cocoasubrtf510\n{\\fonttbl\\f0\\fnil\\fcharset0 Menlo-Regular;}\n{\\colortbl;\\red255\\green255\\blue255;\\red188\\green0\\blue0;\\red7\\green127\\blue137;\\red34\\green0\\blue255;\n\\red5\\green101\\blue0;}\n\\paperw11900\\paperh16840\\margl1440\\margr1440\\vieww10800\\viewh8400\\viewkind0\n\\deftab720\n\\pard\\pardeftab720\\sl260\n\n\\f0\\fs22 \\cf0 .com \\{ \\cf2 color\\cf0 : \\cf3 #93a1a1\\cf0 ; \\}\\\n.lit \\{ \\cf2 color\\cf0 : \\cf3 #195f91\\cf0 ; \\}\\\n.pun, .opn, .clo \\{ \\cf2 color\\cf0 : \\cf3 #93a1a1\\cf0 ; \\}\\\n.fun \\{ \\cf2 color\\cf0 : \\cf3 #dc322f\\cf0 ; \\}\\\n.str, .atv \\{ \\cf2 color\\cf0 : \\cf3 #D14\\cf0 ; \\}\\\n.kwd, .prettyprint .tag \\{ \\cf2 color\\cf0 : \\cf3 #1e347b\\cf0 ; \\}\\\n.typ, .atn, .dec, .var \\{ \\cf2 color\\cf0 : \\cf3 teal\\cf0 ; \\}\\\n.pln \\{ \\cf2 color\\cf0 : \\cf3 #48484c\\cf0 ; \\}\\\n\\\n.prettyprint \\{\\\n \\cf2 padding\\cf0 : \\cf4 8px\\cf0 ;\\\n \\cf2 background-color\\cf0 : \\cf3 #f7f7f9\\cf0 ;\\\n \\cf2 border\\cf0 : \\cf4 1px\\cf0 \\cf3 solid\\cf0 \\cf3 #e1e1e8\\cf0 ;\\\n\\}\\\n.prettyprint.linenums \\{\\\n \\cf2 -webkit-box-shadow\\cf0 : \\cf3 inset\\cf0 \\cf4 40px\\cf0 \\cf4 0\\cf0 \\cf4 0\\cf0 \\cf3 #fbfbfc\\cf0 , \\cf3 inset\\cf0 \\cf4 41px\\cf0 \\cf4 0\\cf0 \\cf4 0\\cf0 \\cf3 #ececf0\\cf0 ;\\\n -moz-box-shadow: \\cf3 inset\\cf0 \\cf4 40px\\cf0 \\cf4 0\\cf0 \\cf4 0\\cf0 \\cf3 #fbfbfc\\cf0 , \\cf3 inset\\cf0 \\cf4 41px\\cf0 \\cf4 0\\cf0 \\cf4 0\\cf0 \\cf3 #ececf0\\cf0 ;\\\n \\cf2 box-shadow\\cf0 : \\cf3 inset\\cf0 \\cf4 40px\\cf0 \\cf4 0\\cf0 \\cf4 0\\cf0 \\cf3 #fbfbfc\\cf0 , \\cf3 inset\\cf0 \\cf4 41px\\cf0 \\cf4 0\\cf0 \\cf4 0\\cf0 \\cf3 #ececf0\\cf0 ;\\\n\\}\\\n\\\n\\pard\\pardeftab720\\sl260\n\\cf5 /* Specify class=linenums on a pre to get line numbering */\\cf0 \\\nol.linenums \\{\\\n \\cf2 margin\\cf0 : \\cf4 0\\cf0 \\cf4 0\\cf0 \\cf4 0\\cf0 \\cf4 33px\\cf0 ; \\cf5 /* IE indents via margin-left */\\cf0 \\\n\\}\\\nol.linenums li \\{\\\n \\cf2 padding-left\\cf0 : \\cf4 12px\\cf0 ;\\\n \\cf2 color\\cf0 : \\cf3 #bebec5\\cf0 ;\\\n \\cf2 line-height\\cf0 : \\cf4 20px\\cf0 ;\\\n \\cf2 text-shadow\\cf0 : \\cf4 0\\cf0 \\cf4 1px\\cf0 \\cf4 0\\cf0 \\cf3 #fff\\cf0 ;\\\n\\}\\\n}"
},
{
"alpha_fraction": 0.5181924104690552,
"alphanum_fraction": 0.5232644081115723,
"avg_line_length": 37.893150329589844,
"blob_id": "723a348aa6953c9e61129bba040b1d6f1449a61e",
"content_id": "b4084a24eddd1afde79e6de79d89bc2933493b6a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 28391,
"license_type": "no_license",
"max_line_length": 352,
"num_lines": 730,
"path": "/voting.py",
"repo_name": "Wenling/Vote4Whatever",
"src_encoding": "UTF-8",
"text": "from __future__ import with_statement\nimport cgi\nimport datetime\nimport urllib\nimport os\nimport random\nimport operator\nimport pickle\nimport webapp2\n\nfrom google.appengine.ext import db\nfrom google.appengine.api import users\nfrom google.appengine.api import images\nfrom google.appengine.ext import blobstore\nfrom google.appengine.ext.webapp import blobstore_handlers\nfrom google.appengine.api import files\nfrom google.appengine.ext.db import stats\nfrom google.appengine.api import memcache\n\nimport jinja2\nimport xml.dom.minidom\nfrom xml.etree import ElementTree\nfrom xml.etree.ElementTree import Element, SubElement, Comment\n\njinja_environment = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))\n\nclass User(db.Model):\n user_id = db.StringProperty()\n user_name = db.StringProperty()\n\n#category has ancestor user\nclass Category(db.Model):\n owner = db.StringProperty()\n owner_id = db.StringProperty()\n name = db.CategoryProperty()\n create_time = db.DateTimeProperty(auto_now_add=True)\n expiration_time = db.DateTimeProperty()\n\n#item has ancestor category\nclass Item(db.Model):\n #category = db.Key()\n name = db.StringProperty()\n create_time = db.DateTimeProperty(auto_now_add=True)\n picture = db.BlobProperty()\n\n#vote has ancestor item\nclass Vote(db.Model):\n voter = db.StringProperty()\n unvoted_item = db.ReferenceProperty()\n #favored = db.BooleanProperty()\n vote_time = db.DateTimeProperty(auto_now_add=True)\n\n#comment has ancestor item\nclass Comment(db.Model):\n commenter_id = db.StringProperty()\n commenter = db.StringProperty()\n create_time = db.DateTimeProperty(auto_now_add=True)\n content = db.StringProperty()\n\n\"\"\"Used to retrieve the keys of the model given a user's information\"\"\"\ndef user_key(user_id=None):\n return db.Key.from_path('UserId', user_id or 'default_user')\n\ndef cat_key(user_id=None, cat_name=None):\n return db.Key.from_path('UserId', user_id, 'CatId', cat_name)\n\ndef item_key(cat_id=None, item_name=None):\n return db.Key.from_path('CatId', cat_id, 'ItemId', item_name)\n\n\"\"\"These functions are the models' manipulations\"\"\"\n#insert a new category\ndef insertCat(user_id, user_name, cat_name, expiration_time):\n ancestor = user_key(user_id)\n time_str = expiration_time.split('/')\n cat_expt = datetime.datetime(int(time_str[2]), int(time_str[0]), int(time_str[1]), 1)\n cat = Category(parent=ancestor, owner=user_name, owner_id=user_id, key_name=cat_name, name=cat_name, expiration_time=cat_expt)\n cat.put()\n return cat\n\n#list all categories under the user\ndef searchCat(query):\n q = Category.all()\n for k in query:\n if k=='ancestor':\n q.ancestor(query[k])\n else:\n q.filter(k, query[k])\n return q\n\n#insert a new item, will check for the user is valid to add item in that category\ndef insertItem(cat_id, item_name, pic_dir, key_name):\n randnum = random.random()\n item = Item(parent=cat_id, key_name=key_name, name=item_name, rand=randnum)\n if pic_dir:\n item.picture = db.Blob(pic_dir)\n item.put()\n return item\n\n#list all items under the category\ndef searchItem(query):\n q = Item.all()\n for k in query:\n if k=='ancestor':\n q.ancestor(query[k])\n elif k=='rand':\n q.filter('Item.rand >=', query[k])\n else:\n q.filter(k, query[k])\n return q\n\n#insert a new vote\ndef insertVote(voter, voted_item_id, unvoted_item):\n vote = Vote(parent=voted_item_id, unvoted_item=unvoted_item, voter=voter)\n vote.put()\n return vote\n\n#list all votes under the item\ndef searchVote(query):\n q = Vote.all()\n for k in query:\n if k=='ancestor':\n q.ancestor(query[k])\n else:\n q.filter(k, query[k])\n return q\n\n#remove all votes given the item\ndef deleteVote(query):\n list = searchVote(query)\n if list.count() > 0:\n db.delete(list)\n\n#remove all comments given the item\ndef deleteComment(query):\n list = searchComment(query)\n db.delete(list)\n\n#remove the item give id\ndef deleteItem(query):\n list = searchItem(query)\n db.delete(list)\n\n#remove the category given category id\ndef deleteCategory(query):\n list = searchCat(query)\n db.delete(list)\n\n#insert comment given item id\ndef insertComment(commenter, commenter_id, item_id, content):\n comment = Comment(parent=item_id, commenter = commenter, commenter_id = commenter_id, content = content)\n comment.put()\n return comment\n\n#search comments given query\ndef searchComment(query):\n q = Comment.all()\n for k in query:\n if k=='ancestor':\n q.ancestor(query[k])\n else:\n q.filter(k, query[k])\n return q\n\n#get random items under the category\ndef pickRandom(cat_id):\n num = Item.all().ancestor(cat_id).count()\n rand = random.randint(0, num-1)\n item = Item.get_by_key_name(str(rand), parent=cat_id)\n return item\n\n#list all voting results under the category\ndef listResult(owner_id, cat_name, user_id):\n results = {}\n not_voted = {}\n cat_id = cat_key(owner_id, cat_name)\n query = {'ancestor':cat_id}\n items = searchItem(query).run()\n for item in items:\n item_id = item_key(owner_id + '/' + cat_name, item.name)\n un_item = searchItem\n q_favored = {'ancestor' : item_id}\n favored_count = searchVote(q_favored).count()\n q_un = {'unvoted_item' : item}\n un_count = searchVote(q_un).count()\n \n if favored_count == 0 and un_count == 0:\n percent = 0\n not_voted[item.name] = [0, 0, '-']\n else:\n percent = favored_count / (0.0 + favored_count + un_count)\n results[item.name] = [favored_count, un_count, percent]\n\n return results, not_voted\n\ndef getText(nodelist):\n rc = []\n for node in nodelist:\n if node.nodeType == node.TEXT_NODE:\n rc.append(node.data)\n return ''.join(rc)\n\ndef prettify(elem):\n \"\"\"Return a pretty-printed XML string for the Element.\n \"\"\"\n rough_string = ElementTree.tostring(elem, 'utf-8')\n reparsed = xml.dom.minidom.parseString(rough_string)\n return reparsed.toprettyxml(indent=\" \")\n\nclass AddCat(webapp2.RequestHandler):\n def post(self):\n cat_name = self.request.get('cat_name')\n expiration_time = self.request.get('expiration_time')\n \n if users.get_current_user():\n user_id = users.get_current_user().user_id()\n user_name = users.get_current_user().nickname()\n query = {'ancestor':user_key(user_id), 'name':cat_name}\n if searchCat(query).count() == 0:\n cat = insertCat(user_id, user_name, cat_name, expiration_time)\n #self.response.out.write(cat_id)\n self.redirect('/?add=success&cat_name=' + cat_name + '&owner=' + user_id)\n else:\n self.redirect('/?add=fail&category=a')\n\nclass AddItem(webapp2.RequestHandler):\n def post(self):\n template_values = {}\n user_id = users.get_current_user().user_id()\n #self.response.out.write(user_id)\n cat_name = self.request.get('cat_name')\n #self.response.out.write(cat_name)\n owner_id = self.request.get('owner')\n if owner_id == user_id:\n cat_id = cat_key(owner_id, cat_name)\n item_name = self.request.get('item_name')\n pic_dir = self.request.get('picture')\n \n if item_name:\n query = {'ancestor': cat_id, 'name': item_name}\n list = searchItem(query)\n num = list.count()\n if num == 0:\n item = insertItem(cat_id, item_name, pic_dir, str(num))\n #self.response.out.write(item.name)\n \n self.redirect('/category?id='+user_id+'&name='+cat_name)\n #self.redirect('/?' + urllib.urlencode({'parent': cat_name}) + '&' + urllib.urlencode({'owner':user_id}) + '&'+ urllib.urlencode({'item_name': item_name}))\n else:\n \n self.redirect('/category?id='+user_id+'&name='+cat_name+'&add_fail=True')\n\nclass Image(webapp2.RequestHandler):\n def get(self):\n item = db.get(self.request.get('img_id'))\n if item.picture:\n self.response.headers['Content-Type'] = 'image/png'\n self.response.out.write(item.picture)\n else:\n self.response.out.write('No image')\n\nclass VoteItem(webapp2.RequestHandler):\n def get(self):\n cat_name = self.request.get('cat_name')\n owner_id = self.request.get('owner')\n user_id = users.get_current_user().user_id()\n cat_id = owner_id + '/' + cat_name\n \n if self.request.get('item_name'):\n item_name = self.request.get('item_name')\n unvoted_item = self.request.get('unvote_item')\n item1_id = item_key(cat_id, item_name)\n query = {'ancestor':cat_key(owner_id, cat_name), 'name':unvoted_item}\n item2 = searchItem(query).get()\n vote1 = insertVote(user_id, item1_id, item2)\n #self.response.out.write(item_name)\n \n self.redirect('/?prev1=' + item_name + '&prev2=' + unvoted_item + '&vote_cat=' + cat_name + '&owner=' + owner_id)\n \n elif self.request.get('not_skip'):\n not_skip = self.request.get('not_skip')\n item = self.request.get('item')\n skip_item = self.request.get('skip_item')\n \n #self.response.out.write(item)\n #self.response.out.write(skip_item)\n \n self.redirect('/?' + urllib.urlencode({'not_skip': not_skip}) + '&item=' + item + '&skip_item=' + skip_item + '&vote_cat=' + cat_name + '&owner=' + owner_id)\n\nclass ImportCat(blobstore_handlers.BlobstoreUploadHandler):\n def post(self):\n #try:\n upload = self.get_uploads()[0]\n blob_key=upload.key()\n blob_reader = blobstore.BlobReader(blob_key)\n document = blob_reader.read()\n dom = xml.dom.minidom.parseString(document)\n cat_name = dom.getElementsByTagName(\"NAME\")[0]\n user_id = users.get_current_user().user_id()\n user_name = users.get_current_user().nickname()\n \n name = getText(cat_name.childNodes)\n \n items = dom.getElementsByTagName(\"ITEM\")\n \n query = {'ancestor':user_key(user_id), 'name':name}\n if searchCat(query).count() == 0:\n d = datetime.timedelta(days=+1)\n expiration_time = (datetime.datetime.now()+d).strftime(\"%m/%d/%Y\")\n cat = insertCat(user_id, user_name, name, expiration_time)\n cat_id = cat_key(user_id, name)\n for item in items:\n item_name = getText(item.getElementsByTagName(\"NAME\")[0].childNodes)\n query = {'ancestor': cat_id}\n num = searchItem(query).count()\n insertItem(cat_id, item_name, None, str(num))\n blob_reader.close()\n self.redirect('/?upload=success&category=a')\n \n else:\n modified = {}\n cat_id = cat_key(user_id, name)\n for item in items:\n item_name = getText(item.getElementsByTagName(\"NAME\")[0].childNodes)\n query = {'ancestor':cat_id, 'name':item_name}\n if searchItem(query).count() == 0:\n query = {'ancestor': cat_id}\n num = searchItem(query).count()\n insertItem(cat_id, item_name, None, str(num))\n modified[item_name] = 1\n else:\n modified[item_name] = 0\n \n query = {'ancestor':cat_id}\n list = searchItem(query)\n for l in list:\n if not l.name in modified:\n item_id = item_key(user_id+'/'+name, l.name)\n q_vote = {'ancestor':item_id}\n deleteVote(q_vote)\n q_vote = {'unvoted_item': l}\n deleteVote(q_vote)\n q_comment = {'ancestor':item_id}\n deleteComment(q_comment)\n q_item = {'ancestor':cat_id, 'name':l.name}\n deleteItem(q_item)\n \n blob_reader.close()\n self.redirect('/?upload=success&category=a')\n\n#except:\n#self.redirect('/?upload_failure=true&categories=a')\n\nclass ExportHandler(webapp2.RequestHandler):\n def get(self):\n cat_name = self.request.get('cat_name')\n owner_id = self.request.get('owner')\n self.response.out.write(cat_name)\n \n cat_id = cat_key(owner_id, cat_name)\n query = {'ancestor' : cat_id}\n list = searchItem(query)\n \n # make items into xml\n top = ElementTree.Element('top')\n \n comment = ElementTree.Comment('Generated automatically by 1010Ling.')\n top.append(comment)\n \n child = SubElement(top, 'NAME')\n child.text = cat_name\n \n for item in list:\n i = SubElement(top, 'ITEM')\n name = SubElement(i, 'NAME')\n name.text = item.name\n create_time = SubElement(i, 'CREATE_TIME')\n create_time.text = item.create_time.ctime()\n pic = SubElement(i, 'PICTURE')\n pic.text = pickle.dumps(item.picture)\n \n data = prettify(top)\n \n # Create the file\n file_name = files.blobstore.create(mime_type='application/octet-stream')\n \n # Open the file and write to it\n with files.open(file_name, 'a') as f:\n f.write(data)\n \n # Finalize the file. Do this before attempting to read it.\n files.finalize(file_name)\n \n # Get the file's blob key\n blob_key = files.blobstore.get_blob_key(file_name)\n self.redirect('/export/%s' % blob_key)\n\nclass ExportCat(blobstore_handlers.BlobstoreDownloadHandler):\n def get(self, file_key):\n if not blobstore.get(file_key):\n self.error(404)\n else:\n name = str(file_key)\n self.send_blob(file_key, save_as=name+'.xml')\n#self.response.out.write(file_key)\n\nclass AddComment(webapp2.RequestHandler):\n def post(self):\n user_id = users.get_current_user().user_id()\n user_name = users.get_current_user().nickname()\n #self.response.out.write(user_id)\n cat_name = self.request.get('cat_name')\n #self.response.out.write(cat_name)\n owner_id = self.request.get('owner')\n item_name = self.request.get('item_name')\n #self.response.out.write(item_name)\n content = self.request.get('content')\n item_id = item_key(owner_id+'/'+cat_name, item_name)\n query = {'ancestor':item_id, 'commenter_id':user_id}\n if searchComment(query).count() == 0:\n insertComment(user_name, user_id, item_id, content)\n self.redirect('/?item_name=' + item_name + '&' + urllib.urlencode({'parent': cat_name}) + '&' + urllib.urlencode({'owner':owner_id}))\n else:\n self.redirect('/?fail=true&item_name=' + item_name + '&' + urllib.urlencode({'parent': cat_name}) + '&' + urllib.urlencode({'owner':owner_id}))\n\nclass RemoveItem(webapp2.RequestHandler):\n def post(self):\n user_id = users.get_current_user().user_id()\n cat_name = self.request.get('cat_name')\n owner_id = self.request.get('owner')\n item_name = self.request.get('item_name')\n item_id = item_key(owner_id+'/'+cat_name, item_name)\n cat_id = cat_key(owner_id, cat_name)\n q_vote = {'ancestor':item_id}\n deleteVote(q_vote)\n q_vote = {'unvoted_item': item_id}\n deleteVote(q_vote)\n q_comment = {'ancestor':item_id}\n deleteComment(q_comment)\n q_item = {'ancestor':cat_id, 'name':item_name}\n deleteItem(q_item)\n \n self.redirect('/?cat_name=' + cat_name + '&owner=' + owner_id)\n\nclass Search(webapp2.RequestHandler):\n def get(self):\n q = self.request.get('query')\n self.redirect('/?query=' + q)\n\nclass BaseHandler(webapp2.RequestHandler):\n def dispatch(self):\n # Get a session store for this request.\n self.session_store = sessions.get_store(request=self.request)\n \n try:\n # Dispatch the request.\n webapp2.RequestHandler.dispatch(self)\n finally:\n # Save all sessions.\n self.session_store.save_sessions(self.response)\n \n @webapp2.cached_property\n def session(self):\n # Returns a session using the default cookie key.\n return self.session_store.get_session()\n\nclass ViewCategory(webapp2.RequestHandler):\n def get(self):\n template_values = {}\n if not self.request.get('id'):\n query = {}\n list = memcache.get('cat_all')\n if list is None:\n list = searchCat(query)\n memcache.add('cat_all', list, 60)\n \n template_values['categories'] = list\n \n elif self.request.get('id'):\n id = self.request.get('id')\n if not self.request.get('name'):\n list = memcache.get('cat_'+id)\n if list is None:\n query = {'ancestor' : user_key(id)}\n list = searchCat(query)\n memcache.add('cat_'+id, list, 60)\n \n template_values['categories'] = list\n \n elif self.request.get('name'):\n name = self.request.get('name')\n list = memcache.get('cat_'+id+'_'+name)\n if list is None:\n cat_id = cat_key(id, name)\n query = {'ancestor' : cat_id}\n list = searchItem(query)\n memcache.add('cat_'+id+'_'+name, list, 60)\n \n template_values['items'] = list\n template_values['cat_name'] = name\n template_values['owner'] = id\n a = {}\n b = {}\n i = 0\n for item in list:\n a[item.name] = i\n i = i + 1\n b[item.name] = item.key()\n template_values['id'] = a\n template_values['key'] = b\n \n if self.request.get('add_fail'):\n template_values['add_fail'] = True\n\n user = users.get_current_user()\n if user:\n url = users.create_logout_url(self.request.uri)\n url_linktext = 'Logout'\n username = user.nickname()\n user_id = user.user_id()\n \n template_values['username'] = memcache.get('username')\n template_values['user_id'] = memcache.get('user_id')\n else:\n url = users.create_login_url(self.request.uri)\n url_linktext = 'Login'\n\n template_values['url'] = url\n template_values['url_linktext'] = url_linktext\n\n template = jinja_environment.get_template('view/category_view.html')\n self.response.out.write(template.render(template_values))\n\n#self.response.out.write(list)\n\nclass Dispatcher(webapp2.RequestHandler):\n def get(self):\n \n template_values = {}\n user = users.get_current_user()\n if user:\n url = users.create_logout_url(self.request.uri)\n url_linktext = 'Logout'\n username = user.nickname()\n user_id = user.user_id()\n \n template_values['username'] = username\n template_values['user_id'] = user_id\n if not memcache.get('username'):\n memcache.add('username', username, 3600)\n memcache.add('user_id', user_id, 3600)\n else:\n memcache.get('username')\n memcache.get('user_id')\n \n if self.request.arguments():\n \n if self.request.get('item_name'):\n cat_name = self.request.get('parent')\n owner_id = self.request.get('owner')\n cat_id = cat_key(owner_id, cat_name)\n item_name = self.request.get('item_name')\n query = {'ancestor' : cat_id, 'name' : item_name}\n item = searchItem(query).get()\n \n item_id = item_key(owner_id+'/'+cat_name, item_name)\n q_comment = {'ancestor' : item_id}\n comments = searchComment(q_comment).run()\n \n template_values['item'] = item\n template_values['cat_name'] = cat_name\n template_values['owner'] = owner_id\n template_values['comments'] = comments\n template_values['item_key'] = item.key()\n if self.request.get('fail'):\n template_values['fail'] = True\n \n elif self.request.get('vote_cat')=='all':\n query = {}\n if memcache.get('cat_all'):\n list = memcache.get('cat_all')\n else:\n list = searchCat(query)\n memcache.add('cat_all', list, 60)\n \n template_values['vote_cat'] = list\n template_values['now'] = datetime.datetime.today()\n if self.request.get('not_enough'):\n template_values['not_enough'] = self.request.get('not_enough')\n template_values['cat'] = self.request.get('cat')\n template_values['owner'] = self.request.get('owner')\n\n elif self.request.get('vote_cat'):\n owner_id = self.request.get('owner')\n vote_cat = self.request.get('vote_cat')\n cat_id = cat_key(owner_id, vote_cat)\n \n template_values['vote'] = []\n template_values['owner'] = owner_id\n \n not_skip = 0\n query={'ancestor':cat_id}\n count = searchItem(query).count()\n \"\"\"\n if memcache.get('count_'+owner_id+'_'+vote_cat):\n count = memcache.get('count_'+owner_id+'_'+vote_cat)\n else:\n count = searchItem(query).count()\n memcache.add('count_'+owner_id+'_'+vote_cat, count, 60)\n \"\"\"\n if count <= 2:\n self.redirect('/?vote_cat=all&cat='+vote_cat+'&owner='+owner_id+'¬_enough='+str(count))\n \n elif self.request.get('not_skip'):\n if count > 2:\n not_skip = self.request.get('not_skip')\n skip_item = self.request.get('skip_item')\n query = {'ancestor' : cat_id, 'name' : self.request.get('item')}\n item1 = searchItem(query).get()\n #self.response.out.write(item1)\n \n item2 = pickRandom(cat_id)\n while (not item2) or (item2 and item2.name == item1.name) or (item2.name == skip_item):\n item2 = pickRandom(cat_id)\n\n elif self.request.get('prev1'):\n if count > 2:\n prev1 = self.request.get('prev1')\n prev2 = self.request.get('prev2')\n template_values['prev1'] = prev1\n template_values['prev2'] = prev2\n #item1 = 'a'\n #item2 = 'b'\n \n item1 = pickRandom(cat_id)\n \n while (not item1) or (item1 and item1.name == prev1):\n item1 = pickRandom(cat_id)\n \n item2 = pickRandom(cat_id)\n \n while (not item2) or (item2 and item2.name == item1.name) or (item2 and item2.name == prev1):\n item2 = pickRandom(cat_id)\n \n else:\n item1 = pickRandom(cat_id)\n item2 = pickRandom(cat_id)\n \n while not item1:\n item1 = pickRandom(cat_id)\n \n while (not item2) or (item2 and item2.name == item1.name):\n item2 = pickRandom(cat_id)\n\n if count > 2:\n \n if not_skip == '1':\n template_values['vote'] = [item1, item2]\n template_values['vote_key'] = [item1.key(), item2.key()]\n else:\n template_values['vote'] = [item2, item1]\n template_values['vote_key'] = [item2.key(), item1.key()]\n template_values['owner'] = owner_id\n template_values['cat'] = vote_cat\n\n \n elif self.request.get('stats_cat'):\n owner_id = self.request.get('owner')\n stats_cat = self.request.get('stats_cat')\n #cat_id = cat_key(owner_id, stats_cat)\n \n results, unvoted = listResult(owner_id, stats_cat, user_id)\n results_sorted = sorted(results.items(), key=lambda x: x[1][2], reverse=True)\n template_values['results'] = results_sorted\n template_values['unvoted'] = unvoted\n\n elif self.request.get('stats')=='all':\n query = {}\n if memcache.get('cat_all'):\n list = memcache.get('cat_all')\n else:\n list = searchCat(query)\n memcache.add('cat_all', list, 60)\n\n template_values['stats_cat'] = list.run()\n\n elif self.request.get('upload_failure'):\n template_values['upload_failure'] = True\n\n elif self.request.get('query'):\n query_name = self.request.get('query')\n q_cat = {'name':query_name}\n cat_list = searchCat(q_cat)\n q_item = {'name': query_name}\n item_list = searchItem(q_item)\n \n template_values['query_cat'] = cat_list\n template_values['query_item'] = item_list\n template_values['count_cat'] = cat_list.count()\n template_values['count_item'] = item_list.count()\n \n a = {}\n b = {}\n i = 0\n for item in item_list:\n a[item.name] = i\n i = i + 1\n b[item.name] = item.key()\n template_values['id'] = a\n template_values['key'] = b\n\n else:\n template_values['home'] = True\n \n else:\n url = users.create_login_url(self.request.uri)\n url_linktext = 'Login'\n username = ''\n\n template_values['url'] = url\n template_values['url_linktext'] = url_linktext\n\n\n template = jinja_environment.get_template('view/index.html')\n self.response.out.write(template.render(template_values))\n\nconfig = {}\nconfig['webapp2_extras.sessions'] = {\n 'secret_key': 'my-super-secret-key',\n}\napp = webapp2.WSGIApplication([('/', Dispatcher), ('/addCat', AddCat), ('/addItem', AddItem), ('/vote', VoteItem), ('/import', ImportCat), ('/export', ExportHandler), ('/export/([^/]+)?', ExportCat), ('/addComment', AddComment), ('/removeItem', RemoveItem), ('/img', Image), ('/search', Search), ('/category', ViewCategory)], debug=True, config=config)"
}
] | 2 |
nofr/coronavirus_project | https://github.com/nofr/coronavirus_project | d6e346f6b8e0623a665ac6db533f84528d8cf22b | 53904b04e0dabc5a29649d91afe65e43dcea1499 | 17cf670772f6d5235a3925c32b91365e05b3b067 | refs/heads/master | 2023-01-06T17:49:41.668612 | 2020-11-08T16:24:21 | 2020-11-08T16:24:21 | 311,102,392 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7984344363212585,
"alphanum_fraction": 0.7994129061698914,
"avg_line_length": 77.53845977783203,
"blob_id": "64781f85a82cb8c4bfc40bf030b67ab19a2ab090",
"content_id": "7f0b07c51d554a1b04adc945968da18d462f2005",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1022,
"license_type": "no_license",
"max_line_length": 369,
"num_lines": 13,
"path": "/README.md",
"repo_name": "nofr/coronavirus_project",
"src_encoding": "UTF-8",
"text": "# coronavirus_project\n## step 1\nThis python code uses the Coronavirus website https://www.worldometers.info/coronavirus/ to fetch data about the virus. The data is both globally and individually for each country , and its history, of coronavirus cases. The code fetchs the data when running it first, and updates it every x time.\n\n## Process explanation\nWe used requests, beautifulsoup and lxml platforms for creating functions of data parsing. The data is stored in lists, sets and dictionaries. There is also a function for saving the data on a file. The parsing code runs in a loop that updates the data every x time. The user can change the update times by changing it in the constant list in the beginning of the code.\n\n## Installation\nYou should install python with basic installations, such as DateTime, and all the prerequisites in the requirements.txt file.\npip install -r requirements.txt\n\n## DISCLAIMER\nWe use this information of the Coronavirus cases from the worldometers website for learning purposes only!\n\n"
},
{
"alpha_fraction": 0.6213305592536926,
"alphanum_fraction": 0.6312428712844849,
"avg_line_length": 34.090301513671875,
"blob_id": "2c512532a0803fd03cda0efe6c34adf3a97ba490",
"content_id": "d363719c3805c2e673d7bba1fc7fe0b7ae278467",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10492,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 299,
"path": "/coronavirus_step1_1.2.py",
"repo_name": "nofr/coronavirus_project",
"src_encoding": "UTF-8",
"text": "import requests\nfrom bs4 import BeautifulSoup\nfrom datetime import datetime\nimport time\n\nURL = \"https://www.worldometers.info/coronavirus/\"\n\nCOLUMNS_HTML_HEAD = 'var columns'\nCOLUMNS_HTML_TAIL = ';'\nCOUNTRY_HTML_STARTING_CODE = \"<a class=\\\"mt_a\\\" href=\\\"country\"\nCOUNTRY_HTML_ENDING_CODE = \"<td style=\\\"display:none\\\" data-continent\"\nCOUNTRY_BLOCK_SIZE = 1024\nCOUNTRY_HTML_ENDING_INDEX = 393000\n\nWORLDWIDE_CASES_HTML = \"Coronavirus Cases:</h1>\\n<div class=\\\"maincounter-number\\\">\"\"\\n<span style=\\\"color:#aaa\\\">\"\n\nUPDATE_TIME = ['08:00:00', '16:00:00', '00:00:00']\n\n\ndef html(url):\n \"\"\"\n Function html\n\n Receives a url address and returns its html code.\n :param url: the url to parse.\n :return: html page code.\n \"\"\"\n page = requests.get(url)\n # print(page.text)\n txt = page.text\n return txt\n\n\ndef parsing_columns_data(starting_line, ending_line, text):\n \"\"\"\n Function parsing_columns_data\n\n Searching in a html code for columns data (table headers).\n\n :param starting_line: starting string of the columns html block.\n :param ending_line: ending string of the columns html block.\n :param text: string of full or partial html code to search in\n :return: a list of the columns values.\n \"\"\"\n columns = ['Country']\n index1 = text.find(starting_line)\n index2 = text[index1:].find(ending_line)\n code = text[index1:index1 + index2]\n for i in range(13):\n index1 = code.find('\\'')\n index2 = code[index1 + 1:].find('\\'')\n value = code[index1 + 1:index1 + index2 + 1]\n code = code[index1 + index2 + 2:]\n columns.append(value)\n return columns\n\n\ndef parsing_country_data(starting_line, ending_line, text, countries_set, country_link_dict):\n \"\"\"\n Function parsing_country_data\n\n Searching in the html code for country's relevant data regarding the Coronavirus cases\n and returning its values in a list.\n\n :param starting_line: starting string of the country html block.\n :param ending_line: ending string of the country html block.\n :param text: string of full or partial html code to search in.\n :return: a list of the country's values.\n \"\"\"\n row_list = []\n starting_index = text.find(starting_line)\n ending_index = starting_index + len(starting_line) + text[starting_index + len(starting_line) + 1:].find('/')\n country_link = text[starting_index + len(starting_line) + 1:ending_index + 1]\n text_block = text[starting_index:]\n ending_index = text_block.find(ending_line)\n text_block = text_block[:ending_index]\n list_block = text_block.split('\\n')\n for line in list_block[:-1]:\n index1 = line.find('>')\n index2 = line[index1:].find('<')\n if index1 == -1 or index2 == -1:\n continue\n value = line[index1 + 1:index1 + index2]\n if value == '':\n index1 = line.find('>') + 1\n index1 = line.find('>', index1)\n index2 = line[index1:].find('<')\n value = line[index1 + 1:index1 + index2]\n row_list.append(value)\n for i, number in enumerate(row_list[1:]):\n if number.strip() == '' or number == 'N/A':\n row_list[i + 1] = None\n elif number.find('.') == -1:\n row_list[i + 1] = int(number.replace(',', ''))\n else:\n row_list[i + 1] = float(number)\n country = row_list[0]\n if country in countries_set:\n return []\n else:\n countries_set.add(country)\n country_link_dict[country] = country_link\n return row_list\n\n\ndef refresh_data(update_time_list):\n \"\"\"\n Function refresh_data\n\n This function receives a list of different time strings in the format of %H:%M:%S and returens True/False if\n the current time matches one of the items (time string) in the list.\n\n :param update_time_list: receives a list of different time strings (%H:%M:%S)\n :return: True or false if the current time is in the list\n \"\"\"\n current_time = str(datetime.now().strftime(\"%H:%M:%S\"))\n for time_element in update_time_list:\n if time_element == current_time:\n return True\n return False\n\n\ndef parsing_main_data(txt):\n \"\"\"\n\n the main_data function attract the main titles data from the url page,\n and returns it in a dictionary. the three main title -\n 'Coronavirus Cases', 'Deaths' and 'Recovered'-\n are presented as a dictionary keys\n and the numerical values are presented as the the key values respectively.\n\n :param txt: the readable textual given data from URL\n :return: the data as a dictionary\n \"\"\"\n\n soup = BeautifulSoup(txt, features=\"lxml\")\n\n titles_list = []\n numbers_list = []\n\n center_data = soup.select('#maincounter-wrap')\n\n for data in center_data:\n titles_list.append(data.select('h1')[0].text[:-1])\n numbers_list.append(int(data.select('span')[0].text.replace(',', \"\")))\n global_info = dict(zip(titles_list, numbers_list))\n return global_info\n\n\ndef parsing_country_history(txt):\n \"\"\"\n Function parsing_country_history.\n\n This function receives an html string of a specific country and returns its coronavirus daily history\n to the current day. The history contains 5 cases: Total Cases, Daily New Cases, Active Cases, Total Deaths and\n Daily Deaths. If the country does not have a case or cases of some kind, for example, Total Deaths = 0,\n It will return a blank list of lists for that case.\n\n :param txt: the html code (string) of the country's webpage.\n :return: a dictionary of 5 key cases containing 2 lists for each case: the list for days\n (usually starting from Feb 15) and a list of cases per day.\n \"\"\"\n starting_index = 0\n country_history = {}\n graph_list = ['Total Cases', 'Daily New Cases', 'Active Cases', 'Total Deaths', 'Daily Deaths']\n\n for graph in graph_list:\n\n if txt.find(graph) == -1:\n country_history[graph] = [[]]\n continue\n\n starting_index = starting_index + txt[starting_index:].find(graph)\n\n starting_index = starting_index + txt[starting_index:].find('categories: [')\n ending_index = starting_index + txt[starting_index:].find(']')\n\n categories_list = txt[starting_index + len('categories: [') + 1:ending_index - 1].split('\\\",\\\"')\n\n starting_index = starting_index + txt[starting_index:].find('data: [')\n ending_index = starting_index + txt[starting_index:].find(']')\n\n data_list = txt[starting_index + len('data: ['):ending_index].split(',')\n\n country_history[graph] = [categories_list, data_list]\n\n return country_history\n\n\ndef parsing_data():\n \"\"\"\n Function parsing_data\n\n Parsing data of Corona virus cases from the given website.\n\n :return: True or False if data fetching succeeded or not.\n \"\"\"\n txt = html(URL)\n country_list = []\n country_set = set()\n country_link_dict = {}\n country_history = {}\n\n current_time = datetime.now().strftime(\"%H:%M:%S\")\n print(\"Starting fetching data at:\", current_time)\n\n try:\n print(parsing_main_data(txt))\n\n columns_list = parsing_columns_data(COLUMNS_HTML_HEAD, COLUMNS_HTML_TAIL, txt)\n country_list.append(columns_list)\n\n starting_index = txt.find(COUNTRY_HTML_STARTING_CODE)\n ending_index = COUNTRY_HTML_ENDING_INDEX\n for i in range(starting_index, ending_index, COUNTRY_BLOCK_SIZE):\n country_list.append(\n parsing_country_data(COUNTRY_HTML_STARTING_CODE, COUNTRY_HTML_ENDING_CODE, txt[i:], country_set, country_link_dict))\n\n country_list = [x for x in country_list if x != []]\n\n for country in country_list:\n print(country)\n\n print()\n print('countries:', country_set)\n print('number of countries:', len(country_set))\n print()\n\n for country in country_set:\n txt = html(URL + 'country/' + country_link_dict[country] + '/')\n country_history[country] = parsing_country_history(txt)\n print(country)\n print(country_history[country])\n\n current_time = datetime.now().strftime(\"%H:%M:%S\")\n print(\"Done fetching data at:\", current_time)\n\n print('Next update/s will occur at:', UPDATE_TIME)\n except:\n print('Failed to fetch data. Check HTML code')\n return False\n\n return True\n\n\ndef saving_data_to_file(filename, starting_time, ending_time, global_info, country_list, country_set, country_history):\n \"\"\"\n Function saving_data_to_file\n\n This function saves the data from the Coronavirus web site to a file.\n\n :param filename: the name and path to a (txt) file\n :param starting_time: the starting time of the parsing process\n :param ending_time: the ending time of the parsing process\n :param global_info: a dictionary containing global data with keys: 'Coronavirus Cases', 'Deaths' and 'Recovered'\n :param country_list: a list of list (table) of every country with its individual data regarding its cases\n :param country_set: a set of the countries (216)\n :param country_history: a dictionary with country key containing a dictionary with 5 keys of cases for each country.\n Each case containing a list of 2 lists:\n 1st list contains the dates (of days) and 2nd list contains the values for each day.\n :return: True or False if creating file and writing to it was successful.\n \"\"\"\n try:\n f = open(filename, \"w\")\n except:\n print('Failed to open a file!')\n return False\n try:\n f.write(\"Starting fetching data at:\" + starting_time + \"\\n\")\n f.write(str(global_info) + \"\\n\")\n for country in country_list:\n f.write(str(country) + \"\\n\")\n f.write('countries:' + str(country_set) + \"\\n\")\n f.write('number of countries:' + str(len(country_set)) + \"\\n\")\n for country in country_set:\n f.write(str(country) + \"\\n\")\n f.write(str(country_history[country]) + \"\\n\")\n f.write(\"Done fetching data at:\" + ending_time + \"\\n\")\n f.write('Next update/s will occur at:' + str(UPDATE_TIME) + \"\\n\")\n except:\n print('Failed to write to a file!')\n return False\n finally:\n f.close()\n return True\n\n\ndef main():\n data_fetched = False\n while True:\n if refresh_data(UPDATE_TIME) or not data_fetched:\n parsing_data()\n time.sleep(5)\n data_fetched = True\n time.sleep(1)\n\n\nif __name__ == '__main__':\n main()\n"
}
] | 2 |
MeadBarrel/vimy | https://github.com/MeadBarrel/vimy | 6f0a4f8386f8962b0dbe368ddc21fde560bad8be | 00ec6ab9a30c89cbceac3ced6e3fc390108eb899 | 321f103245db4bf98563b9b6717448d373c930c8 | refs/heads/master | 2017-05-20T16:12:43.008252 | 2016-04-30T08:28:24 | 2016-04-30T08:28:24 | 57,032,306 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5083072185516357,
"alphanum_fraction": 0.5234770178794861,
"avg_line_length": 26.68666648864746,
"blob_id": "cfbc9d83f30a587df59e3a3c644503ff8962767e",
"content_id": "d0037d59ada6c49b2962b5810036b985cd85792d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4153,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 150,
"path": "/src/main.py",
"repo_name": "MeadBarrel/vimy",
"src_encoding": "UTF-8",
"text": "import sys\nimport string\nfrom curses import wrapper\nimport curses\nfrom random import choice, randint\nfrom time import sleep\nfrom traceback import format_exc\nfrom pygments import highlight\nfrom pygments.lexers.python import PythonLexer\nfrom pygments.formatters.html import HtmlFormatter\nfrom pygments.formatters.terminal256 import Terminal256Formatter\nfrom pygments.formatters.terminal import TerminalFormatter\n\n\n\nMODE_EDIT, MODE_NAVIGATE = 0, 1\n\n\nclass Buffer(object):\n def __init__(self):\n self.buffer = \"\"\n\n\nclass EditorWindow(object):\n def __init__(self, parent, size, position):\n self._buffer = ''\n self._size = size\n self._position = position\n self._win = parent.derwin(*(size + position))\n self._vertical_scroll = 0\n self._tabs_width = 4\n self._mode = MODE_NAVIGATE\n\n def vertical_scroll(self, lines):\n self._vertical_scroll += lines\n self._vertical_scroll = max(0, self._vertical_scroll)\n\n def page_scroll(self, pages):\n self.vertical_scroll(self._size[0] * pages)\n\n def load_from_file(self, filename):\n self._buffer = '\\n'.join([''.join([choice(string.ascii_letters) for i in range(randint(0, 79))]) for x in range(1000000)])\n self._vertical_scroll = 100000\n #self._buffer = open(filename, 'r').read()\n #self._buffer = highlight(self._buffer, PythonLexer(), HtmlFormatter())\n\n def process_input(self, key):\n cursor = self._win.getyx()\n if self._mode == MODE_NAVIGATE:\n if key == 'j':\n self._win.move(cursor[0]+1, cursor[1])\n elif key == 'J':\n self.vertical_scroll(1)\n elif key == 'k':\n self._win.move(cursor[0]-1, cursor[1])\n elif key == 'K':\n self.vertical_scroll(-1)\n elif key == '^J':\n self.page_scroll(1)\n elif key == '^K':\n self.page_scroll(-1)\n self.render()\n\n\n def render(self):\n old_cursor = self._win.getyx()\n curses.curs_set(0)\n self._win.clear()\n row = 0\n col = 0\n\n for char in self._buffer:\n current_cursor = self._win.getyx()\n\n if char == '\\n':\n row += 1\n col = 0\n elif char == '\\t':\n row += 1\n col = self._tabs_width\n else:\n col += 1\n\n if col >= self._size[1]:\n row += 1\n col = 0\n\n if col >= self._size[1]:\n row += 1\n col = 0\n\n if row-self._vertical_scroll >= self._size[0]-1:\n break\n\n if char not in ('\\n', '\\t'):\n try:\n self._win.addstr(row-self._vertical_scroll, col, char)\n except:\n pass\n\n curses.curs_set(1)\n self._win.move(*old_cursor)\n self._win.refresh()\n\n\nclass Application(object):\n def __init__(self, stdscr):\n curses.noecho()\n self.stdscr = stdscr\n self.size = stdscr.getmaxyx()\n self.stdscr.keypad(0)\n self.stdscr.notimeout(0)\n self._win = curses.newwin(*self.size)\n self.main_buffer = EditorWindow(self._win, self.size, (0, 0))\n self.main_buffer.load_from_file('./test_str')\n\n def get_key(self):\n ch = self._win.getch()\n result = [ch]\n self._win.nodelay(1)\n while ch != -1:\n ch = self._win.getch()\n if ch != -1:\n result.append(ch)\n self._win.nodelay(0)\n try:\n return curses.unctrl(bytes(result)).decode('utf-8')\n except TypeError:\n return ''\n\n\n def main_loop(self):\n key = ' '\n self.main_buffer.render()\n while key != '^[':\n key = self.get_key()\n self.main_buffer.process_input(key)\n\ndef main(stdscr):\n \"\"\" Application entry point \"\"\"\n stdscr.clear()\n app = Application(stdscr)\n try:\n app.main_loop()\n except Exception as e:\n return format_exc()\n\n\nif __name__ == \"__main__\":\n print(wrapper(main))\n"
},
{
"alpha_fraction": 0.6451398134231567,
"alphanum_fraction": 0.6491345167160034,
"avg_line_length": 21.432836532592773,
"blob_id": "1002d6d228a815038ae8b084d3af8ded601f21a1",
"content_id": "6e4722d1e7f68faa6f5d428fc7f7cb47e5ac8847",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1502,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 67,
"path": "/setup.py",
"repo_name": "MeadBarrel/vimy",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n\nimport os\nimport sys\n\n\ntry:\n from setuptools import setup\nexcept ImportError:\n from distutils.core import setup\n\n\nif sys.argv[-1] == 'publish':\n os.system('python3 setup.py sdist upload')\n sys.exit()\n\nwith open(os.path.join(os.path.dirname(__file__), 'README.md')) as f:\n readme = f.read()\n\n\nimport devotion\n\n\npackages = [\n 'devotion',\n 'devotion.raw_buffer'\n]\n\npackage_data = {\n}\n\nrequires = [\n]\n\nclassifiers = [\n 'Development Status :: 1 - Planning',\n 'Environment :: Console',\n 'Intended Audience :: Developers',\n 'Intended Audience :: End Users/Desktop',\n 'License :: OSI Approved :: MIT License',\n 'Operating System :: POSIX :: Linux',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 3 :: Only',\n 'Programming Language :: Python :: Implementation :: CPython',\n 'Topic :: Text Editors :: Integrated Development Environments (IDE)',\n 'Topic :: Text Editors :: Text Processing'\n]\n\nsetup(\n name='Devotion',\n version=devotion.__version__,\n description='Vim-like text editor and IDE, written in python',\n long_description=readme,\n packages=packages,\n package_data=package_data,\n install_requires=requires,\n author=devotion.__author__,\n author_email=devotion.__author_email__,\n license='MIT',\n url='https://github.com/LaiTash/Devotion',\n classifiers=classifiers,\n\n setup_requires=['pytest-runner',],\n tests_require=['pytest', 'mock'],\n)"
},
{
"alpha_fraction": 0.6351063847541809,
"alphanum_fraction": 0.6670212745666504,
"avg_line_length": 26.647058486938477,
"blob_id": "43b02452e72230e744cee8e5d4709ae5a1446472",
"content_id": "fe9a657895f93320800c817e77dab3a73ed902c7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 940,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 34,
"path": "/tests/test_interval_tree.py",
"repo_name": "MeadBarrel/vimy",
"src_encoding": "UTF-8",
"text": "import pytest\nfrom devotion.interval_tree import IntervalTree\n\n\[email protected]\ndef populated_tree():\n tree = IntervalTree()\n tree.add_interval((5, 10), 'interval_1'),\n tree.add_interval((20, 70), 'interval_2')\n tree.add_interval((50, 75), 'overlapping_interval')\n tree.add_interval((77, 80), 'bouncing_interval')\n tree.add_interval((80, 100), 'interval_3')\n return tree\n\n\n\ndef test_empty_true():\n \"\"\" `range` of the empty tree should be (0, 0) \"\"\"\n tree = IntervalTree()\n assert tree.empty\n\n\ndef test_empty_false(populated_tree):\n assert not populated_tree.empty\n\n\nclass TestFind:\n def test_find_simple_interval(self, populated_tree):\n found = populated_tree.intersection(7)\n assert set(found) == {'interval_1'}\n\n def test_find_multiple_intervals(self, populated_tree):\n found = populated_tree.intersection(60)\n assert set(found) == {'interval_2', 'overlapping_interval'}\n"
},
{
"alpha_fraction": 0.5584374070167542,
"alphanum_fraction": 0.5693243741989136,
"avg_line_length": 25.226890563964844,
"blob_id": "2fe95e787e65cc5cbf25d3fb686e2f0a8138166b",
"content_id": "762812f451df3fcc7630f69c298b6c4a12d715aa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3123,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 119,
"path": "/devotion/linebuffer.py",
"repo_name": "MeadBarrel/vimy",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\n\nclass PositionInfo:\n\n \"\"\"\n\n Stores information about line buffer position and it's contents.\n\n Fields::\n\n * row: line index\n * index: absolute index\n * item: character at position\n\n Note::\n\n PositionInfo is only a data structure and does not guarantee the\n information it stores is correct. If you want to ensure it is correct,\n use `ensure_info` of `Lines` object.\n\n \"\"\"\n\n def __init__(self, row, index, item):\n self.row = row\n self.index = index\n self.item = item\n\n def __repr__(self):\n return \"<PositionInfo:%i, %i, %s>\" % (self.row, self.index, self.item)\n\n def __eq__(self, other):\n return (\n self.row == other.row and self.index == other.index and\n self.item == other.item\n )\n\n\nclass Lines(object):\n\n \"\"\"\n\n A mutable text buffer that stores it contents as a list of lines.\n\n Contents can be accessed, edited or deleted in several ways:\n\n * Character at absolute index: lines[512] = 'a'\n * Character at row-column position: del lines[9, 16]\n * Characters between absolute indices: lines[512: 600]\n * Characters between row-column position and an absolute index:\n lines[(9, 16): 512] == \"example slice\\nof characters\"S\n * Characters between absolute index and row-column position:\n lines[82: (20, 5)] = 'thing'\n * Characters between two row-column positions:\n del lines((9, 16): (20, 5)]\n\n \"\"\"\n\n def __init__(self, lines):\n self.lines = lines\n\n def ensure_info(self, info):\n \"\"\"Ensure the information in PositionInfo object is correct.\n\n Makes sure that the information stored in `PositionInfo` object\n (that is, row, index, and item at this position) is correct in\n the context of this buffer.\n\n :param info: `PositionInfo` instance\n :return: True or False\n \"\"\"\n pass\n\n def remove_line(self, line_index):\n pass\n\n def insert_line(self, line_index, line):\n pass\n\n def append_line(self, line):\n pass\n\n def __getitem__(self, item):\n pass\n\n def __setitem__(self, key, value):\n pass\n\n def __delitem__(self, key):\n pass\n\n def _position_info(self, position):\n \"\"\"Get information about specific row-column position.\n\n :param position: position as (row, column) tuple\n :return: `PositionInfo` instance\n \"\"\"\n row, col = position\n if row < 0:\n row = len(self.lines) + row\n\n index = 0\n\n for line_i, line in enumerate(self.lines):\n if line_i == row:\n break\n index += len(line)\n else:\n raise IndexError('Row out of range')\n\n line = self.lines[row]\n col_index = col if col >= 0 else len(line) + col\n if col_index < 0 or col_index >= len(line):\n raise IndexError('Column out of range')\n\n item = line[col_index]\n index = index + col_index\n\n return PositionInfo(row, index, item)\n\n\n"
},
{
"alpha_fraction": 0.5985401272773743,
"alphanum_fraction": 0.6209245920181274,
"avg_line_length": 29.176469802856445,
"blob_id": "b63da42bbd14806003e4d80466d5b9b3659c7bce",
"content_id": "c75bf54a4329b8a235f8003126771267e9b049eb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2055,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 68,
"path": "/tests/test_linebuffer.py",
"repo_name": "MeadBarrel/vimy",
"src_encoding": "UTF-8",
"text": "import pytest\nfrom devotion.linebuffer import Lines, PositionInfo\n\nEXAMPLE_LINES = [\n \"Beautiful is better than ugly.\",\n \"Explicit is better than implicit.\",\n \"Simple is better than complex.\",\n \"Complex is better than complicated.\"\n]\n\n\[email protected]\ndef buffer():\n return Lines(EXAMPLE_LINES)\n\n\ndef test_position_info_eq():\n assert PositionInfo(1, 5, 'a') == PositionInfo(1, 5, 'a')\n\n\ndef test_position_info_not_eq():\n assert PositionInfo(1, 4, 'a') != PositionInfo(1, 5, 'a')\n\n\nclass TestPositionInfo:\n def test_row_positive_col_positive(self, buffer):\n index = len(EXAMPLE_LINES[0]) + 8\n position = (1, 8)\n expected = PositionInfo(1,index, ' ')\n assert buffer._position_info(position) == expected\n\n def test_row_negative(self, buffer):\n \"\"\"Queries such as lines[-2, 5] should return index of the fifth\n character at second row from the end\n \"\"\"\n index = 68\n position = (-2, 5)\n expected = PositionInfo(2, index, 'e')\n assert buffer._position_info(position) == expected\n\n def test_row_negative_col_negative(self, buffer):\n index = 68\n position = (-2, -25)\n expected = PositionInfo(2, index, 'e')\n assert buffer._position_info(position) == expected\n\n def test_row_positive_col_negative(self, buffer):\n index = 68\n position = (2, -25)\n expected = PositionInfo(2, index, 'e')\n assert buffer._position_info(position) == expected\n\n\n def test_positive_row_out_of_range(self, buffer):\n with pytest.raises(IndexError):\n buffer._position_info((200, 5))\n\n def test_negative_row_out_of_range(self, buffer):\n with pytest.raises(IndexError):\n buffer._position_info((-200, 5))\n\n def test_positive_col_out_of_range(self, buffer):\n with pytest.raises(IndexError):\n buffer._position_info((2, 50))\n\n def test_negative_col_out_of_range(self, buffer):\n with pytest.raises(IndexError):\n buffer._position_info((2, -50))\n\n\n\n"
},
{
"alpha_fraction": 0.800000011920929,
"alphanum_fraction": 0.800000011920929,
"avg_line_length": 59,
"blob_id": "610e4e258285a07ebbdb5f92ca1a4403ab4673c5",
"content_id": "d2005613557512cc66ec4cccf9295bc8e04f071e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 60,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 1,
"path": "/README.md",
"repo_name": "MeadBarrel/vimy",
"src_encoding": "UTF-8",
"text": "Extensible vim-like text editor and IDE, written in python.\n"
},
{
"alpha_fraction": 0.5907111763954163,
"alphanum_fraction": 0.5936139225959778,
"avg_line_length": 23.60714340209961,
"blob_id": "cd2cfcf1bd1d4fb3001b9e020b260a3627215126",
"content_id": "e34acd825600598eb926d4cf87de5fc46e65a703",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 689,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 28,
"path": "/devotion/hl_formatter.py",
"repo_name": "MeadBarrel/vimy",
"src_encoding": "UTF-8",
"text": "from pygments.formatter import Formatter\n\n\nclass HLFormatter(Formatter):\n\n \"\"\"\n\n Pygments formatter that populates IntervalTree.\n\n\n For each input token, the interval will be added to the tree indicating\n it's start and end positions within the source string.\n\n \"\"\"\n\n def __init__(self):\n super().__init__()\n self.styles = {\n token_type: style for token_type, style in self.style\n }\n\n def format(self, tokensource, outfile):\n tree = outfile\n i = 0\n for token_type, value in tokensource:\n end_x = i + len(value)\n tree.add_interval((i, end_x), self.styles[token_type])\n i = end_x + 1\n"
},
{
"alpha_fraction": 0.4583333432674408,
"alphanum_fraction": 0.5,
"avg_line_length": 23.33333396911621,
"blob_id": "4f8a460481bc57736b34d9cc802d4bd727eff5cc",
"content_id": "2ac09087a1a277158f9ceab2132b8537d26ccfac",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 72,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 3,
"path": "/devotion/__init__.py",
"repo_name": "MeadBarrel/vimy",
"src_encoding": "UTF-8",
"text": "__version__ = '0.1.0'\n__author__ = 'Lai Tash'\n__author_email__ = '[email protected]'"
},
{
"alpha_fraction": 0.540669858455658,
"alphanum_fraction": 0.5468215942382812,
"avg_line_length": 32.25,
"blob_id": "29cd923aff87c1112685572125455fee12a890b4",
"content_id": "42cf0f86e2fc8cf73e4f34baf208cde91be9fe78",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2926,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 88,
"path": "/devotion/interval_tree.py",
"repo_name": "MeadBarrel/vimy",
"src_encoding": "UTF-8",
"text": "\"\"\"Simple interval tree implementation.\n\n\nDoes not provide functionality for deletion of intervals, for it's unlikely\nwe're going to need this within python-vim.\n\n\n\"\"\"\n\nclass IntervalTree(object):\n def __init__(self):\n self._s_left = None\n self._s_right = None\n self._s_center_by_startx = []\n self._s_center_by_endx = []\n self._x_center = 0\n\n @property\n def empty(self):\n return not (\n self._s_left or self._s_right or\n self._s_center_by_startx or self._s_center_by_endx\n )\n\n def add_interval(self, interval, obj):\n \"\"\" Add an interval to the tree.\n\n :param range: interval as (start, end) tuple\n :param obj: object associated with this interval\n \"\"\"\n if self.empty:\n return self._add_first_interval(interval, obj)\n elif interval[1] < self._x_center:\n if not self._s_left:\n self._s_left = IntervalTree()\n self._s_left.add_interval(interval, obj)\n elif interval[0] > self._x_center:\n if not self._s_right:\n self._s_right = IntervalTree()\n self._s_right.add_interval(interval, obj)\n else:\n self._s_center_by_startx.append((interval[0], obj))\n self._s_center_by_endx.append((interval[1], obj))\n self._s_center_by_startx.sort(key=lambda item: item[0])\n self._s_center_by_endx.sort(key=lambda item: -item[0])\n\n\n def _add_first_interval(self, interval, obj):\n \"\"\" Add the very first interval to the tree.\n\n :param interval: interval as (start, end) tuple\n :param obj: object associated with this interval\n\n :return: self\n \"\"\"\n rng = interval\n self._x_center = (rng[0] + (rng[1]-rng[0])/2)\n self._s_center_by_startx = [(rng[0], obj)]\n self._s_center_by_endx = [(rng[1], obj)]\n return self\n\n\n def intersection(self, point):\n \"\"\" Find all intervals overlapping `point`.\n\n :param point: integer\n :return: set of objects associated with overlapping intervals\n \"\"\"\n result = []\n if point < self._x_center and self._s_left:\n result += self._s_left.intersection(point)\n elif point > self._x_center:\n result += self._s_right.intersection(point)\n if point < self._x_center and self._s_right:\n for interval in self._s_center_by_startx:\n if interval[0] <= point:\n result.append(interval[1])\n else:\n break\n elif point > self._x_center:\n for interval in self._s_center_by_endx:\n if interval[0] >= point:\n result.append(interval[1])\n else:\n break\n else:\n result += [interval[1] for interval in self._s_center_by_startx]\n return result\n"
},
{
"alpha_fraction": 0.6749175190925598,
"alphanum_fraction": 0.6815181374549866,
"avg_line_length": 30.894737243652344,
"blob_id": "6f603817f1c39089cc09b7a034b98f3fc6750070",
"content_id": "8fccacd3c7c526831ac99287228ba494c7c6ae77",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 606,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 19,
"path": "/tests/test_hl_formatter.py",
"repo_name": "MeadBarrel/vimy",
"src_encoding": "UTF-8",
"text": "import pytest\nfrom devotion.interval_tree import IntervalTree\nfrom pygments.token import Token\nfrom devotion.hl_formatter import HLFormatter\n\n\nclass test_format():\n token_source = [\n (Token.Name.Entity, 'it '),\n (Token.Error, 'should '),\n (Token.Keyword, 'just work'),\n ]\n tree = IntervalTree()\n formatter = HLFormatter()\n styles = formatter.styles\n formatter.format(token_source, tree)\n assert tree.intersection(2) == [styles[Token.Name.Entity]]\n assert tree.intersection(5) == [styles[Token.Error]]\n assert tree.intersection(12) == [styles[Token.Keyword]]\n"
},
{
"alpha_fraction": 0.7826374769210815,
"alphanum_fraction": 0.7839845418930054,
"avg_line_length": 52.820247650146484,
"blob_id": "afad464cbd38483020b3a490400ee0b32e5dc84c",
"content_id": "a913bb6efe9ba8f6eac1a7be641477ef5f5e81e5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 125454,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 2331,
"path": "/tests/data/example_python_file.py",
"repo_name": "MeadBarrel/vimy",
"src_encoding": "UTF-8",
"text": "The Project Gutenberg eBook, Gulliver's Travels, by Jonathan Swift, Edited\nby Thomas M. Balliet\n\n\nThis eBook is for the use of anyone anywhere at no cost and with\nalmost no restrictions whatsoever. You may copy it, give it away or\nre-use it under the terms of the Project Gutenberg License included\nwith this eBook or online at www.gutenberg.net\n\n\n\n\n\nTitle: Gulliver's Travels\n Into Several Remote Regions of the World\n\n\nAuthor: Jonathan Swift\n\nEditor: Thomas M. Balliet\n\nRelease Date: November 26, 2005 [eBook #17157]\n\nLanguage: English\n\nCharacter set encoding: ISO-8859-1\n\n\n***START OF THE PROJECT GUTENBERG EBOOK GULLIVER'S TRAVELS***\n\n\nE-text prepared by Juliet Sutherland, Chuck Greif, and the Project\nGutenberg Online Distributed Proofreading Team (http://www.pgdp.net/)\n\n\n\nNote: Project Gutenberg also has an HTML version of this\n file which includes the original illustrations.\n See 17157-h.htm or 17157-h.zip:\n (http://www.gutenberg.net/dirs/1/7/1/2/17157/17157-h/17157-h.htm)\n or\n (http://www.gutenberg.net/dirs/1/7/1/2/17157/17157-h.zip)\n\n\n\n\n\nGULLIVER'S TRAVELS\n\nInto Several Remote Regions of the World\n\nby\n\nJONATHAN SWIFT, D.D.\n\nEdited with Introduction and Notes by Thomas M. Balliet\nSuperintendent of Schools, Springfield, Mass.\n\nWith Thirty-Eight Illustrations and a Map\n\n\nPART I\n\nA VOYAGE TO LILLIPUT\n\n\nPART II\n\nA VOYAGE TO BROBDINGNAG\n\n\n\n\n\n\n\n[Illustration: \"HE COMMANDED HIS GENERALS TO DRAW UP THE TROOPS.\" P. 42.]\n\n\n\n\nD.C. Heath & Co., Publishers\nBoston New York Chicago\n\n1900\n\n\n\n\nPREFACE.\n\n And lo! the book, from all its end beguiled,\n A harmless wonder to some happy child.\n\n LORD LYTTON.\n\n\nGulliver's Travels was published in 1726; and, although it was by no\nmeans intended for them, the book was soon appropriated by the children,\nwho have ever since continued to regard it as one of the most delightful\nof their story books. They cannot comprehend the occasion which provoked\nthe book nor appreciate the satire which underlies the narrative, but\nthey delight in the wonderful adventures, and wander full of open-eyed\nastonishment into the new worlds through which the vivid and logically\naccurate imagination of the author so personally conducts them. And\nthere is a meaning and a moral in the stories of the Voyages to Lilliput\nand Brobdingnag which is entirely apart from the political satire they\nare intended to convey, a meaning and a moral which the youngest child\nwho can read it will not fail to seize, and upon which it is scarcely\nnecessary for the teacher to comment.\n\nFor young children the book combines in a measure the interest of\n_Robinson Crusoe_ and that of the fairy tale; its style is objective,\nthe narrative is simple, and the matter appeals strongly to the childish\nimagination. For more mature boys and girls and for adults the interest\nis found chiefly in the keen satire which underlies the narrative. It\nappeals, therefore, to a very wide range of intelligence and taste, and\ncan be read with profit by the child of ten and by the young man or\nwoman of mature years.\n\nThis edition is practically a reprint of the original (1726-27). The\npunctuation and capitalization have been modernized, some archaisms\nchanged, and the paragraphs have been made more frequent. A few passages\nhave been omitted which would offend modern ears and are unsuitable for\nchildren's reading, and some foot-notes have been added explaining\nobsolete words and obscure expressions.\n\nAs a reading book in school which must be adapted to the average mind,\nthese stories will be found suitable for classes from the fifth or sixth\nschool year to the highest grade of the grammar school.\n\nTHOMAS M. BALLIET.\n\n\n\n\nCONTENTS.\n\nVOYAGE TO LILLIPUT.\n\n\nCHAPTER I.\n\nThe Author gives some account of himself and family--His first\ninducements to travel--He is shipwrecked, and swims for his life--Gets\nsafe on shore in the country of Lilliput--Is made a prisoner, and\ncarried up the country\n\nCHAPTER II.\n\nThe emperor of Lilliput, attended by several of the nobility, comes to\nsee the Author in his confinement--The emperor's person and habits\ndescribed--Learned men appointed to teach the Author their language--He\ngains favor by his mild disposition--His pockets are searched, and his\nsword and pistols taken from him\n\nCHAPTER III.\n\nThe Author diverts the emperor, and his nobility of both sexes, in a\nvery uncommon manner--The diversions of the court of Lilliput\ndescribed--The Author has his liberty granted him upon certain\nconditions\n\nCHAPTER IV.\n\nMildendo, the metropolis of Lilliput, described, together with the\nemperor's palace--A conversation between the Author and a principal\nsecretary concerning the affairs of that empire--The Author's offers to\nserve the emperor in his wars\n\nCHAPTER V.\n\nThe Author, by an extraordinary stratagem, prevents an invasion--A high\ntitle of honor is conferred upon him--Ambassadors arrive from the\nemperor of Blefuscu, and sue for peace\n\nCHAPTER VI.\n\nOf the inhabitants of Lilliput; their learning, laws, and customs; the\nmanner of educating their children--The Author's way of living in that\ncountry--His vindication of a great lady\n\nCHAPTER VII.\n\nThe Author, being informed of a design to accuse him of high treason,\nmakes his escape to Blefuscu--His reception there\n\nCHAPTER VIII.\n\nThe Author, by a lucky accident, finds means to leave Blefuscu; and\nafter some difficulties, returns safe to his native country\n\n * * * * *\n\nLIST OF FULL-PAGE ILLUSTRATIONS.\n\n \"He commanded his generals to draw up the troops\"\n Map of Lilliput and Blefuscu\n \"I lay all this while ... in great uneasiness\"\n \"Producing his credentials\"\n \"These gentlemen made an exact inventory\"\n \"Her imperial majesty was pleased to smile very graciously upon me\"\n \"And created me a _nardac_ upon the spot\"\n \"Three hundred tailors were employed\"\n \"The happiness ... of dining with me\"\n \"He desired I would hear him with patience\"\n \"I set sail ... at six in the morning\"\n\nAND TWENTY-THREE SMALLER ONES IN THE TEXT.\n\n\n\n\nCONTENTS\n\nA VOYAGE TO BROBDINGNAG.\n\nCHAPTER I.\n\nA great storm described; the long-boat sent to fetch water, the Author\ngoes with it to discover the country--He is left on shore, is seized by\none of the natives, and carried to a farmer's house--His reception\nthere, with several accidents that happened there--A description of the\ninhabitants\n\nCHAPTER II.\n\nA description of the farmer's daughter--The Author carried to a\nmarket-town, and then to the metropolis--The particulars of his journey\n\nCHAPTER III.\n\nThe Author sent for to court--The queen buys him of his master the\nfarmer, and presents him to the king--He disputes with his majesty's\ngreat scholars--An apartment at court provided for the Author--He is in\nhigh favor with the queen--He stands up for the honor of his own\ncountry--He quarrels with the queen's dwarf\n\nCHAPTER IV.\n\nThe country described--A proposal for correcting modern maps--The king's\npalace, and some account of the metropolis--The Author's way of\ntravelling--The chief temple described\n\nCHAPTER V.\n\nSeveral adventures that happened to the Author--The execution of a\ncriminal--The Author shows his skill in navigation\n\nCHAPTER VI.\n\nSeveral contrivances of the Author to please the king and queen--He\nshows his skill in music--The king inquires into the state of Europe,\nwhich the Author relates to him--The king's observations thereon\n\nCHAPTER VII.\n\nThe Author's love of his country--He makes a proposal of much advantage\nto the king, which is rejected--The king's great ignorance in\npolitics--The learning of that country very imperfect and\nconfined--Their laws, and military affairs, and in the state\n\nCHAPTER VIII.\n\nThe king and queen make a progress to the frontiers--The Author attends\nthem--The manner in which he leaves the country very particularly\nrelated--He returns to England\n\nNOTE\n\n * * * * *\n\nLIST OF FULL-PAGE ILLUSTRATIONS.\n\n \"They concluded I was only Relplum Sealcath\"\n Map of Brobdingnag\n \"A huge creature walking ... on the sea\"\n \"Whereupon the huge creature trod short\"\n \"I drew my hanger to defend myself\"\n \"I called her my Glumdalclitch\"\n \"Flourished after the manner of fencers in England\"\n \"This gracious princess held out her little finger\"\n \"She carried me to the king\"\n \"I could only revenge myself by calling him brother\"\n \"The smaller birds did not appear to be at all afraid of me\"\n \"Gave me a gale with their fans\"\n \"The most violent exercise I ever underwent\"\n \"You have made an admirable panegyric\"\n \"She had some foreboding\"\n \"Somebody calling in the English tongue\"\n \"My daughter kneeled, but I could not see her\"\n\nAND TWELVE SMALLER ONES IN THE TEXT.\n\n\n\n\nTHE FIRST PUBLISHER TO THE READER.\n\n\nThe author of these travels, Mr. Lemuel Gulliver, is my ancient and\nintimate friend; there is likewise some relation between us on the\nmother's side. About three years ago, Mr. Gulliver, growing weary of the\nconcourse of curious people coming to him at his house in Redriff,[1]\nmade a small purchase of land, with a convenient house, near Newark, in\nNottinghamshire, his native county, where he now lives retired, yet in\ngood esteem among his neighbors.\n\nAlthough Mr. Gulliver was born in Nottinghamshire, where his father\ndwelt, yet I have heard him say his family came from Oxfordshire; to\nconfirm which, I have observed in the churchyard at Banbury, in that\ncounty, several tombs and monuments of the Gullivers. Before he quitted\nRedriff he left the custody of the following papers in my hands, with\nthe liberty to dispose of them as I should think fit. I have carefully\nperused them three times. The style is very plain and simple, and the\nonly fault I find is, that the author, after the manner of travellers,\nis a little too circumstantial. There is an air of truth apparent\nthrough the whole; and, indeed, the author was so distinguished for his\nveracity, that it became a sort of proverb among his neighbors at\nRedriff, when any one affirmed a thing, to say it was as true as if Mr.\nGulliver had spoken it.\n\nBy the advice of several worthy persons, to whom, with the author's\npermission, I communicated these papers, I now venture to send them into\nthe world, hoping they may be, at least for some time, a better\nentertainment than the common scribbles about politics and party.\n\nThis volume would have been at least twice as large if I had not made\nbold to strike out innumerable passages relating to the winds and tides,\nas well as to the variations and bearings in the several voyages;\ntogether with the minute description of the management of the ship in\nthe storms, in the style of sailors; likewise the account of longitudes\nand latitudes; wherein I have reason to apprehend that Mr. Gulliver may\nbe a little dissatisfied; but I was resolved to fit the work as much as\npossible to the general capacity of readers. However, if my own\nignorance in sea affairs shall have led me to commit some mistakes, I\nalone am answerable for them, and if any traveller hath a curiosity to\nsee the whole work at large, as it came from the hand of the author, I\nwill be ready to gratify him.\n\nAs for any farther particulars relating to the author, the reader will\nreceive satisfaction from the first pages of the book.\n\n RICHARD SYMPSON.\n\n[Illustration]\n\n[Illustration]\n\n\n\n\nTRAVELS.\n\nPART I.\n\n\n_A VOYAGE TO LILLIPUT_.\n\n\n\n\nCHAPTER I.\n\n THE AUTHOR GIVES SOME ACCOUNT OF HIMSELF AND FAMILY: HIS FIRST\n INDUCEMENTS TO TRAVEL. HE IS SHIPWRECKED, AND SWIMS FOR HIS LIFE;\n GETS SAFE ASHORE IN THE COUNTRY OF LILLIPUT; IS MADE A PRISONER,\n AND CARRIED UP THE COUNTRY.\n\n\nMy father had a small estate in Nottinghamshire; I was the third of five\nsons. He sent me to Emmanuel College in Cambridge at fourteen years old,\nwhere I resided three years, and applied myself close to my studies;\nbut the charge of maintaining me, although I had a very scanty\nallowance, being too great for a narrow fortune, I was bound apprentice\nto Mr. James Bates, an eminent surgeon in London, with whom I continued\nfour years; and my father now and then sending me small sums of money, I\nlaid them out in learning navigation, and other parts of the mathematics\nuseful to those who intend to travel, as I always believed it would be,\nsome time or other, my fortune to do. When I left Mr. Bates, I went down\nto my father, where, by the assistance of him, and my uncle John and\nsome other relations, I got forty pounds,[2] and a promise of thirty\npounds a year, to maintain me at Leyden. There I studied physic two\nyears and seven months, knowing it would be useful in long voyages.\n\nSoon after my return from Leyden, I was recommended by my good master,\nMr. Bates, to be surgeon to the \"Swallow,\" Captain Abraham Pannell,\ncommander; with whom I continued three years and a half, making a voyage\nor two into the Levant,[3] and some other parts. When I came back I\nresolved to settle in London; to which Mr. Bates, my master, encouraged\nme, and by him I was recommended to several patients. I took part of a\nsmall house in the Old Jewry; and, being advised to alter my condition,\nI married Mrs. Mary Burton,[4] second daughter to Mr. Edmund Burton,\nhosier in Newgate Street, with whom I received four hundred pounds for a\nportion.\n\nBut my good master, Bates, dying in two years after, and I having few\nfriends, my business began to fail; for my conscience would not suffer\nme to imitate the bad practice of too many among my brethren. Having,\ntherefore, consulted with my wife, and some of my acquaintance, I\ndetermined to go again to sea. I was surgeon successively in two ships,\nand made several voyages, for six years, to the East and West Indies, by\nwhich I got some addition to my fortune. My hours of leisure I spent in\nreading the best authors, ancient and modern, being always provided with\na good number of books; and, when I was ashore, in observing the manners\nand dispositions of the people, as well as learning their language,\nwherein I had a great facility, by the strength of my memory.\n\nThe last of these voyages not proving very fortunate, I grew weary of\nthe sea, and intended to stay at home with my wife and family. I removed\nfrom the Old Jewry to Fetter Lane, and from thence to Wapping, hoping to\nget business among the sailors; but it would not turn to account. After\nthree years' expectation that things would mend, I accepted an\nadvantageous offer from Captain William Prichard, master of the\n\"Antelope,\" who was making a voyage to the South Sea.[5] We set sail\nfrom Bristol, May 4, 1699; and our voyage at first was very prosperous.\n\nIt would not be proper, for some reasons, to trouble the reader with the\nparticulars of our adventures in those seas. Let it suffice to inform\nhim, that, in our passage from thence to the East Indies, we were driven\nby a violent storm, to the northwest of Van Diemen's Land.[6]\n\nBy an observation, we found ourselves in the latitude of 30 degrees and\n2 minutes south. Twelve of our crew were dead by immoderate labor and\nill food; the rest were in a very weak condition.\n\nOn the fifth of November, which was the beginning of summer in those\nparts, the weather being very hazy, the seamen spied a rock within half\na cable's length of the ship;[7] but the wind was so strong, that we\nwere driven directly upon it, and immediately split. Six of the crew, of\nwhom I was one, having let down the boat into the sea, made a shift to\nget clear of the ship and the rock. We rowed, by my computation, about\nthree leagues, till we were able to work no longer, being already spent\nwith labor, while we were in the ship. We, therefore, trusted ourselves\nto the mercy of the waves; and, in about half an hour, the boat was\noverset by a sudden flurry from the north. What became of my companions\nin the boat, as well as those who escaped on the rock, or were left in\nthe vessel, I cannot tell, but conclude they were all lost.\n\nFor my own part, I swam as fortune directed me, and was pushed forward\nby wind and tide. I often let my legs drop, and could feel no bottom;\nbut, when I was almost gone, and able to struggle no longer, I found\nmyself within my depth; and, by this time, the storm was much abated.\n\nThe declivity was so small that I walked near a mile before I got to the\nshore, which I conjectured was about eight o'clock in the evening. I\nthen advanced forward near half a mile, but could not discover any sign\nof houses or inhabitants; at least, I was in so weak a condition, that I\ndid not observe them. I was extremely tired, and with that, and the\nheat of the weather, and about half a pint of brandy that I drank as I\nleft the ship, I found myself much inclined to sleep. I lay down on the\ngrass, which was very short and soft, where I slept sounder than ever I\nremembered to have done in my life, and, as I reckoned, about nine\nhours; for, when I awaked, it was just daylight. I attempted to rise,\nbut was not able to stir: for as I happened to lie on my back, I found\nmy arms and legs were strongly fastened on each side to the ground; and\nmy hair, which was long and thick, tied down in the same manner. I\nlikewise felt several slender ligatures across my body, from my arm-pits\nto my thighs. I could only look upwards, the sun began to grow hot, and\nthe light offended my eyes.\n\nI heard a confused noise about me; but, in the posture I lay, could see\nnothing except the sky. In a little time, I felt something alive moving\non my left leg, which, advancing gently forward over my breast, came\nalmost up to my chin; when, bending my eyes downward, as much as I\ncould, I perceived it to be a human creature, not six inches high, with\na bow and arrow in his hands, and a quiver at his back. In the meantime\nI felt at least forty more of the same kind (as I conjectured) following\nthe first.\n\nI was in the utmost astonishment, and roared so loud that they all ran\nback in a fright; and some of them, as I was afterwards told, were hurt\nwith the falls they got by leaping from my sides upon the ground.\nHowever, they soon returned, and one of them, who ventured so far as to\nget a full sight of my face, lifting up his hands and eyes by way of\nadmiration, cried out in a shrill, but distinct voice--_Hekinah degul!_\nthe others repeated the same words several times, but I then knew not\nwhat they meant.\n\nI lay all this while, as the reader may believe, in great uneasiness. At\nlength, struggling to get loose, I had the fortune to break the strings,\nand wrench out the pegs, that fastened my left arm to the ground; for by\nlifting it up to my face, I discovered the methods they had taken to\nbind me, and, at the same time, with a violent pull, which gave me\nexcessive pain, I a little loosened the strings that tied down my hair\non the left side, so that I was just able to turn my head about two\ninches.\n\nBut the creatures ran off a second time, before I could seize them;\nwhereupon there was a great shout in a very shrill accent, and after it\nceased, I heard one of them cry aloud, _Tolgo phonac_; when, in an\ninstant, I felt above an hundred arrows discharged on my left hand,\nwhich pricked me like so many needles; and, besides, they shot another\nflight into the air, as we do bombs in Europe, whereof many, I suppose,\nfell on my body (though I felt them not), and some on my face, which I\nimmediately covered with my left hand.\n\nWhen this shower of arrows was over, I fell a-groaning with grief and\npain, and then striving again to get loose, they discharged another\nvolley larger than the first, and some of them attempted with spears to\nstick me in the sides; but by good luck I had on me a buff jerkin,[8]\nwhich they could not pierce. I thought it the most prudent method to lie\nstill, and my design was to continue so till night, when, my left hand\nbeing already loose, I could easily free myself; and as for the\ninhabitants, I had reason to believe I might be a match for the\ngreatest army they could bring against me, if they were all of the same\nsize with him that I saw.\n\n[Illustration: \"I LAY ALL THIS WHILE IN GREAT UNEASINESS\" P. 8.]\n\nBut fortune disposed otherwise of me. When the people observed I was\nquiet, they discharged no more arrows: but, by the noise I heard, I knew\ntheir numbers increased; and about four yards from me, over against my\nright ear, I heard a knocking for above an hour, like that of people at\nwork; when, turning my head that way, as well as the pegs and strings\nwould permit me, I saw a stage erected, about a foot and a half from the\nground, capable of holding four of the inhabitants, with two or three\nladders to mount it; from whence one of them, who seemed to be a person\nof quality, made me a long speech, whereof I understood not one\nsyllable.\n\n[Illustration]\n\nBut I should have mentioned, that before the principal person began his\noration, he cried out three times, _Langro debul san_ (these words, and\nthe former, were afterwards repeated, and explained to me). Whereupon\nimmediately about fifty of the inhabitants came and cut the strings that\nfastened the left side of my head, which gave me the liberty of turning\nit to the right, and of observing the person and gesture of him that was\nto speak. He appeared to be of a middle age, and taller than any of the\nother three who attended him, whereof one was a page that held up his\ntrain, and seemed to be somewhat longer than my middle finger; the other\ntwo stood one on each side, to support him. He acted every part of an\norator, and I could observe many periods of threatenings, and others of\npromises, pity, and kindness.\n\nI answered in a few words, but in the most submissive manner, lifting up\nmy left hand, and both my eyes, to the sun, as calling him for a\nwitness: and, being almost famished with hunger, having not eaten a\nmorsel for some hours before I left the ship, I found the demands of\nnature so strong upon me, that I could not forbear showing my impatience\n(perhaps against the strict rules of decency) by putting my finger\nfrequently to my mouth, to signify that I wanted food. The _hurgo_ (for\nso they call a great lord, as I afterwards learned) understood me very\nwell. He descended from the stage, and commanded that several ladders\nshould be applied to my sides; on which above a hundred of the\ninhabitants mounted, and walked towards my mouth, laden with baskets\nfull of meat, which had been provided and sent thither by the king's\norders, upon the first intelligence he received of me.\n\nI observed there was the flesh of several animals, but could not\ndistinguish them by the taste. There were shoulders, legs, and loins,\nshaped like those of mutton, and very well dressed, but smaller than the\nwings of a lark. I ate them by two or three at a mouthful, and took\nthree loaves at a time, about the bigness of musket bullets. They\nsupplied me as they could, showing a thousand marks of wonder and\nastonishment at my bulk and appetite. I then made another sign that I\nwanted drink.\n\nThey found by my eating that a small quantity would not suffice me; and\nbeing a most ingenious people, they slung up with great dexterity, one\nof their largest hogsheads, then rolled it towards my hand, and beat out\nthe top: I drank it off at a draught; which I might well do, for it did\nnot hold half a pint, and tasted like a small[9] wine of Burgundy, but\nmuch more delicious. They brought me a second hogshead, which I drank in\nthe same manner, and made signs for more; but they had none to give me.\n\nWhen I had performed these wonders, they shouted for joy, and danced\nupon my breast, repeating, several times, as they did at first, _Hekinah\ndegul_. They made me a sign, that I should throw down the two hogsheads,\nbut first warning the people below to stand out of the way, crying\naloud, _Borach nevola_; and, when they saw the vessels in the air, there\nwas an universal shout of _Hekinah degul_.\n\nI confess, I was often tempted, while they were passing backwards and\nforwards on my body, to seize forty or fifty of the first that came in\nmy reach, and dash them against the ground. But the remembrance of what\nI had felt, which probably might not be the worst they could do, and the\npromise of honor I made them--for so I interpreted my submissive\nbehavior--soon drove out those imaginations. Besides, I now considered\nmyself as bound, by the laws of hospitality, to a people who had treated\nme with so much expense and magnificence. However, in my thoughts I\ncould not sufficiently wonder at the intrepidity of these diminutive\nmortals, who durst venture to mount and walk upon my body, while one of\nmy hands was at liberty, without trembling at the very sight of so\nprodigious a creature, as I must appear to them.\n\n[Illustration: \"PRODUCING HIS CREDENTIALS.\" P. 14.]\n\nAfter some time, when they observed that I made no more demands for\nmeat, there appeared before me a person of high rank from his imperial\nmajesty. His excellency, having mounted on the small of my right leg,\nadvanced forwards up to my face, with about a dozen of his retinue: and,\nproducing his credentials under the signet-royal,[10] which he applied\nclose to my eyes, spoke about ten minutes, without any signs of anger,\nbut with a kind of determinate resolution, often pointing forwards,\nwhich, as I afterwards found, was towards the capital city, about half a\nmile distant, whither it was agreed by his majesty in council that I\nmust be conveyed. I answered in few words, but to no purpose, and made a\nsign with my hand that was loose, putting it to the other (but over his\nexcellency's head, for fear of hurting him or his train) and then to my\nown head and body, to signify that I desired my liberty.\n\nIt appeared that he understood me well enough, for he shook his head by\nway of disapprobation, and held his hand in a posture to show that I\nmust be carried as a prisoner. However, he made other signs, to let me\nunderstand that I should have meat and drink enough, and very good\ntreatment. Whereupon I once more thought of attempting to break my\nbonds; but again, when I felt the smart of their arrows upon my face and\nhands, which were all in blisters, and many of the darts still sticking\nin them, and observing, likewise, that the number of my enemies\nincreased, I gave tokens to let them know, that they might do with me\nwhat they pleased. Upon this the _hurgo_ and his train withdrew, with\nmuch civility, and cheerful countenances.\n\nSoon after, I heard a general shout, with frequent repetitions of the\nwords, _Peplom selan_, and I felt great numbers of people on my left\nside, relaxing the cords to such a degree, that I was able to turn upon\nmy right, and to get a little ease. But, before this, they had daubed my\nface and both my hands with a sort of ointment very pleasant to the\nsmell, which, in a few minutes, removed all the smart of their arrows.\nThese circumstances, added to the refreshment I had received by their\nvictuals and drink, which were very nourishing, disposed me to sleep. I\nslept about eight hours, as I was afterwards assured; and it was no\nwonder, for the physicians, by the emperor's order, had mingled a sleepy\npotion in the hogsheads of wine.\n\nIt seems that, upon the first moment I was discovered sleeping on the\nground after my landing, the emperor had early notice of it, by an\nexpress; and determined in council, that I should be tied in the manner\nI have related (which was done in the night, while I slept), that plenty\nof meat and drink should be sent to me, and a machine prepared to carry\nme to the capital city.\n\nThis resolution, perhaps, may appear very bold and dangerous, and I am\nconfident would not be imitated by any prince in Europe, on the like\noccasion. However, in my opinion, it was extremely prudent, as well as\ngenerous; for, supposing these people had endeavored to kill me with\ntheir spears and arrows, while I was asleep, I should certainly have\nawaked with the first sense of smart, which might so far have roused my\nrage and strength, as to have enabled me to break the strings wherewith\nI was tied; after which, as they were not able to make resistance, so\nthey could expect no mercy.\n\nThese people are most excellent mathematicians, and arrived to a great\nperfection in mechanics, by the countenance and encouragement of the\nemperor, who is a renowned patron of learning. The prince hath several\nmachines fixed on wheels for the carriage of trees, and other great\nweights. He often builds his largest men of war, whereof some are nine\nfeet long, in the woods where the timber grows, and has them carried on\nthese engines three or four hundred yards to the sea. Five hundred\ncarpenters and engineers were immediately set to work, to prepare the\ngreatest engine they had. It was a frame of wood, raised three inches\nfrom the ground, about seven feet long and four wide, moving upon\ntwenty-two wheels. The shout I heard was upon the arrival of this\nengine, which, it seems, set out in four hours after my landing. It was\nbrought parallel to me, as I lay. But the principal difficulty was, to\nraise and place me in this vehicle.\n\nEighty poles, each of one foot high, were erected for this purpose, and\nvery strong cords, of the bigness of packthread, were fastened by hooks\nto many bandages, which the workmen had girt round my neck, my hands, my\nbody, and my legs. Nine hundred of the strongest men were employed to\ndraw up these cords by many pulleys fastened on the poles; and thus, in\nless than three hours, I was raised and slung into the engine, and tied\nfast.\n\n[Illustration]\n\nAll this I was told; for, while the whole operation was performing, I\nlay in a profound sleep, by the force of that soporiferous medicine\ninfused into my liquor. Fifteen hundred of the emperor's largest horses,\neach about four inches and a half high, were employed to draw me\ntowards the metropolis, which, as I said, was half a mile distant.\n\nAbout four hours after we began our journey, I awaked, by a very\nridiculous accident; for, the carriage being stopt a while, to adjust\nsomething that was out of order, two or three of the young natives had\nthe curiosity to see how I looked, when I was asleep. They climbed up\ninto the engine, and advancing very softly to my face, one of them, an\nofficer in the guards, put the sharp end of his half-pike[11] a good way\nup into my left nostril, which tickled my nose like a straw, and made me\nsneeze violently; whereupon they stole off, unperceived, and it was\nthree weeks before I knew the cause of my awaking so suddenly.\n\nWe made a long march the remaining part of the day, and rested at night\nwith five hundred guards on each side of me, half with torches, and half\nwith bows and arrows, ready to shoot me, if I should offer to stir. The\nnext morning, at sunrise, we continued our march, and arrived within two\nhundred yards of the city gates about noon. The emperor, and all his\ncourt, came out to meet us; but his great officers would by no means\nsuffer his majesty to endanger his person, by mounting on my body.\n\nAt the place where the carriage stopt, there stood an ancient temple,\nesteemed to be the largest in the whole kingdom, which, having been\npolluted some years before by an unnatural murder, was, according to the\nzeal of those people, looked upon as profane, and therefore had been\napplied to common use, and all the ornaments and furniture carried\naway. In this edifice it was determined I should lodge. The great gate,\nfronting to the north, was about four feet high, and almost two feet\nwide, through which I could easily creep. On each side of the gate was a\nsmall window, not above six inches from the ground; into that on the\nleft side the king's smith conveyed four score and eleven chains, like\nthose that hang to a lady's watch in Europe, and almost as large, which\nwere locked to my left leg with six-and-thirty padlocks.\n\n[Illustration]\n\nOver against this temple, on the other side of the great highway, at\ntwenty feet distance, there was a turret at least five feet high. Here\nthe emperor ascended, with many principal lords of his court, to have an\nopportunity of viewing me, as I was told, for I could not see them. It\nwas reckoned that above an hundred thousand inhabitants came out of the\ntown upon the same errand; and, in spite of my guards, I believe there\ncould not be fewer than ten thousand, at several times, who mounted my\nbody, by the help of ladders. But a proclamation was soon issued, to\nforbid it, upon pain of death.\n\nWhen the workmen found it was impossible for me to break loose, they cut\nall the strings that bound me; whereupon I rose up, with as melancholy a\ndisposition as ever I had in my life. But the noise and astonishment of\nthe people, at seeing me rise and walk, are not to be expressed. The\nchains that held my left leg were about two yards long, and gave me not\nonly the liberty of walking backwards and forwards in a semi-circle,\nbut, being fixed within four inches of the gate, allowed me to creep in,\nand lie at my full length in the temple.\n\n[Illustration]\n\n\n\n\nCHAPTER II.\n\n THE EMPEROR OF LILLIPUT, ATTENDED BY SEVERAL OF THE NOBILITY, COMES\n TO SEE THE AUTHOR IN HIS CONFINEMENT. THE EMPEROR'S PERSON AND\n HABIT DESCRIBED. LEARNED MEN APPOINTED TO TEACH THE AUTHOR THEIR\n LANGUAGE. HE GAINS FAVOR BY HIS MILD DISPOSITION. HIS POCKETS ARE\n SEARCHED, AND HIS SWORD AND PISTOLS TAKEN FROM HIM.\n\n\nWhen I found myself on my feet, I looked about me, and must confess I\nnever beheld a more entertaining prospect. The country around, appeared\nlike a continued garden, and the enclosed fields, which were generally\nforty feet square, resembled so many beds of flowers. These fields were\nintermingled with woods of half a stang,[12] and the tallest trees, as I\ncould judge, appeared to be seven feet high. I viewed the town on my\nleft hand, which looked like the painted scene of a city in a theatre.\n\nThe emperor was already descended from the tower, and advancing on\nhorseback towards me, which had like to have cost him dear; for the\nbeast, though very well trained, yet wholly unused to such a sight,\nwhich appeared as if a mountain moved before him, reared up on his hind\nfeet. But that prince, who is an excellent horseman, kept his seat, till\nhis attendants ran in and held the bridle, while his majesty had time to\ndismount.\n\nWhen he alighted, he surveyed me round with great admiration, but kept\nwithout the length of my chain. He ordered his cooks and butlers, who\nwere already prepared, to give me victuals and drink, which they pushed\nforward in a sort of vehicles upon wheels, till I could reach them. I\ntook these vehicles, and soon emptied them all; twenty of them were\nfilled with meat; each afforded me two or three good mouthfuls. The\nempress and young princes of the blood of both sexes, attended by many\nladies, sat at some distance in their chairs;[13] but upon the accident\nthat happened to the emperor's horse, they alighted, and came near his\nperson, which I am now going to describe. He is taller, by almost the\nbreadth of my nail, than any of his court, which alone is enough to\nstrike an awe into the beholders. His features are strong and masculine,\nwith an Austrian lip and arched nose, his complexion olive, his\ncountenance erect, his body and limbs well proportioned, all his motions\ngraceful, and his deportment majestic. He was then past his prime, being\ntwenty-eight years and three-quarters old, of which he had reigned about\nseven in great felicity, and generally victorious. For the better\nconvenience of beholding him, I lay on my side, so that my face was\nparallel to his, and he stood but three yards off. However, I have had\nhim since many times in my hand, and therefore cannot be deceived in the\ndescription.\n\n[Illustration]\n\nHis dress was very plain and simple, and the fashion of it between the\nAsiatic and the European; but he had on his head a light helmet of gold,\nadorned with jewels, and a plume an the crest.[14] He held his sword\ndrawn in his hand, to defend himself, if I should happen to break loose;\nit was almost three inches long; the hilt and scabbard were gold,\nenriched with diamonds. His voice was shrill, but very clear and\narticulate, and I could distinctly hear it, when I stood up.\n\nThe ladies and courtiers were all most magnificently clad; so that the\nspot they stood upon seemed to resemble a petticoat spread on the\nground, embroidered with figures of gold and silver. His imperial\nmajesty spoke often to me, and I returned answers, but neither of us\ncould understand a syllable. There were several of his priests and\nlawyers present (as I conjectured by their habits), who were commanded\nto address themselves to me; and I spoke to them in as many languages as\nI had the least smattering of, which were, High and Low Dutch, Latin,\nFrench, Spanish, Italian, and Lingua Franca;[15] but all to no purpose.\n\nAfter about two hours the court retired, and I was left with a strong\nguard, to prevent the impertinence, and probably the malice of the\nrabble, who were very impatient to crowd about me as near as they durst;\nand some of them had the impudence to shoot their arrows at me, as I sat\non the ground by the door of my house, whereof one very narrowly missed\nmy left eye. But the colonel ordered six of the ring-leaders to be\nseized, and thought no punishment so proper as to deliver them bound\ninto my hands; which some of his soldiers accordingly did, pushing them\nforwards with the butt-ends of their pikes into my reach. I took them\nall on my right hand, put five of them into my coat-pocket; and as to\nthe sixth, I made a countenance as if I would eat him alive. The poor\nman squalled terribly, and the colonel and his officers were in much\npain, especially when they saw me take out my penknife; but I soon put\nthem out of fear, for, looking mildly, and immediately cutting the\nstrings he was bound with, I set him gently on the ground, and away he\nran. I treated the rest in the same manner, taking them one by one out\nof my pocket; and I observed both the soldiers and people were highly\ndelighted at this mark of my clemency, which was represented very much\nto my advantage at court.\n\n[Illustration]\n\nTowards night, I got with some difficulty into my house, where I lay on\nthe ground, and continued to do so about a fortnight, during which time\nthe emperor gave orders to have a bed prepared for me. Six hundred beds,\nof the common measure, were brought in carriages and worked up in my\nhouse; an hundred and fifty of their beds, sewn together, made up the\nbreadth and length; and these were four double, which, however, kept me\nbut very indifferently from the hardness of the floor, which was of\nsmooth stone. By the same computation, they provided me with sheets,\nblankets, and coverlets, which were tolerable enough for one who had\nbeen so long inured to hardships as I.\n\nAs the news of my arrival spread through the kingdom, it brought\nprodigious numbers of rich, idle, and curious people to see me; so that\nthe villages were almost emptied; and great neglect of tillage and\nhousehold affairs must have ensued, if his imperial majesty had not\nprovided, by several proclamations and orders of state, against this\ninconvenience. He directed that those who had already beheld me should\nreturn home, and not presume to come within fifty yards of my house\nwithout license from court; whereby the secretaries of state got\nconsiderable fees.\n\nIn the meantime, the emperor held frequent councils, to debate what\ncourse should be taken with me; and I was afterwards assured by a\nparticular friend, a person of great quality, who was as much in the\nsecret as any, that the court was under many difficulties concerning me.\nThey apprehended my breaking loose; that my diet would be very\nexpensive, and might cause a famine. Sometimes they determined to starve\nme, or at least to shoot me in the face and hands with poisoned arrows,\nwhich would soon despatch me: but again they considered that the stench\nof so large a carcase might produce a plague in the metropolis, and\nprobably spread through the whole kingdom.\n\nIn the midst of these consultations, several officers of the army went\nto the door of the great council-chamber, and two of them being\nadmitted, gave an account of my behavior to the six criminals\nabove-mentioned, which made so favorable an impression in the breast of\nhis majesty, and the whole board, in my behalf, that an imperial\ncommission was issued out, obliging all the villages nine hundred yards\nround the city to deliver in, every morning, six beeves, forty sheep,\nand other victuals, for my sustenance; together with a proportionable\nquantity of bread and wine, and other liquors; for the due payment of\nwhich his majesty gave assignments upon his treasury. For this prince\nlives chiefly upon his own demesnes, seldom, except upon great\noccasions, raising any subsidies upon his subjects, who are bound to\nattend him in his wars at their own expense. An establishment was also\nmade of six hundred persons, to be my domestics, who had board-wages\nallowed for their maintenance, and tents built for them very\nconveniently on each side of my door.\n\nIt was likewise ordered that three hundred tailors should make me a suit\nof clothes, after the fashion of the country; that six of his majesty's\ngreatest scholars should be employed to instruct me in their language;\nand lastly, that the emperor's horses, and those of the nobility and\ntroops of guards, should be frequently exercised in my sight, to\naccustom themselves to me.\n\nAll these orders were duly put in execution, and in about three weeks I\nmade a great progress in learning their language; during which time the\nemperor frequently honored me with his visits, and was pleased to assist\nmy masters in teaching me. We began already to converse together in some\nsort; and the first words I learnt were to express my desire that he\nwould please give me my liberty, which I every day repeated on my\nknees. His answer, as I could apprehend it, was, that this must be a\nwork of time, not to be thought on without the advice of his council,\nand that first I must _lumos kelmin pesso desmar lon emposo_; that is,\nswear a peace with him and his kingdom. However, that I should be used\nwith all kindness; and he advised me to acquire, by my patience and\ndiscreet behavior, the good opinion of himself and his subjects.\n\nHe desired I would not take it ill, if he gave orders to certain proper\nofficers to search me; for probably I might carry about me several\nweapons which must needs be dangerous things, if they answered the bulk\nof so prodigious a person. I said his majesty should be satisfied, for I\nwas ready to strip myself and turn up my pockets before him. This I\ndelivered, part in words, and part in signs.\n\nHe replied, that by the laws of the kingdom, I must be searched by two\nof his officers; that he knew this could not be done without my consent\nand assistance; that he had so good an opinion of my generosity and\njustice, as to trust their persons in my hands; that whatever they took\nfrom me should be returned when I left the country, or paid for at the\nrate which I should set upon them. I took up the two officers in my\nhands, put them first into my coat-pockets, and then into every other\npocket about me, except my two fobs and another secret pocket, which I\nhad no mind should be searched, wherein I had some little necessaries\nthat were of no consequence to any but myself. In one of my fobs there\nwas a silver watch, and in the other a small quantity of gold in a\npurse.\n\n[Illustration: \"THESE GENTLEMEN MADE AN EXACT INVENTORY OF EVERYTHING\nTHEY SAW\" P. 30.]\n\nThese gentlemen having pen, ink, and paper about them, made an exact\ninventory of everything they saw; and, when they had done, desired I\nwould set them down, that they might deliver it to the emperor. This\ninventory I afterwards translated into English, and is word for word as\nfollows:--\n\n_Imprimis_,[16] In the right coat-pocket of the great man-mountain (for\nso I interpret the words _quinbus flestrin_), after the strictest\nsearch, we found only one great piece of coarse cloth, large enough to\nbe a foot-cloth for your majesty's chief room of state. In the left\npocket, we saw a huge silver chest, with a cover of the same metal,\nwhich we the searchers were not able to lift. We desired it should be\nopened, and one of us stepping into it, found himself up to the mid-leg\nin a sort of dust, some part whereof flying up to our faces, set us both\na sneezing for several times together. In his right waistcoat pocket we\nfound a prodigious number of white thin substances folded one over\nanother, about the bigness of three men, tied with a strong cable, and\nmarked with black figures; which we humbly conceive to be writings,\nevery letter almost half as large as the palm of our hands. In the left,\nthere was a sort of engine, from the back of which were extended twenty\nlong poles, resembling the palisadoes before your majesty's court;\nwherewith we conjecture the man-mountain combs his head, for we did not\nalways trouble him with questions, because we found it a great\ndifficulty to make him understand us. In the large pocket on the right\nside of his middle cover (so I translate the word _ranfu-lo_, by which\nthey meant my breeches), we saw a hollow pillar of iron, about the\nlength of a man, fastened to a strong piece of timber, larger than the\npillar; and upon one side of the pillar were huge pieces of iron\nsticking out, cut into strange figures, which we know not what to make\nof. In the left pocket, another engine of the same kind. In the smaller\npocket on the right side were several round flat pieces of white and red\nmetal, of different bulk; some of the white, which seemed to be silver,\nwere so large and so heavy, that my comrade and I could hardly lift\nthem. In the left pocket, were two black pillars irregularly shaped; we\ncould not without difficulty reach the top of them, as we stood at the\nbottom of his pocket. One of them was covered, and seemed all of a\npiece; but at the upper end of the other, there appeared a white and\nround substance, about twice the bigness of our heads. Within each of\nthese was enclosed a prodigious plate of steel, which, by our orders, we\nobliged him to show us, because we apprehended they might be dangerous\nengines. He took them out of their cases, and told us that in his own\ncountry his practice was to shave his beard with one of these, and to\ncut his meat with the other. There were two pockets which we could not\nenter: these he called his fobs. Out of the right fob hung a great\nsilver chain, with a wonderful kind of engine at the bottom. We directed\nhim to draw out whatever was at the end of that chain, which appeared to\nbe a globe, half silver, and half of some transparent metal; for on the\ntransparent side we saw certain strange figures, circularly drawn, and\nthought we could touch them till we found our fingers stopped by that\nlucid substance.[17] He put this engine to our ears, which made an\nincessant noise, like that of a water-mill; and we conjecture it is\neither some unknown animal, or the god that he worships; but we are more\ninclined to the latter opinion, because he assured us (if we understood\nhim right, for he expressed himself very imperfectly), that he seldom\ndid anything without consulting it. He called it his oracle, and said it\npointed out the time for every action of his life. From the left fob he\ntook out a net almost large enough for a fisherman, but contrived to\nopen and shut like a purse, and served him for the same use; we found\ntherein several massy pieces of yellow metal, which, if they be real\ngold, must be of immense value.\n\nHaving thus, in obedience to your majesty's commands, diligently\nsearched all his pockets, we observed a girdle about his waist, made of\nthe hide of some prodigious animal, from which, on the left side, hung a\nsword of the length of five men; and on the right, a bag or pouch,\ndivided into two cells, each cell capable of holding three of your\nmajesty's subjects. In one of these cells were several globes, or balls,\nof a most ponderous metal, about the bigness of our heads, and required\na strong hand to lift them; the other cell contained a heap of certain\nblack grains, but of no great bulk or weight, for we could hold about\nfifty of them in the palms of our hands.\n\nThis is an exact inventory of what we found about the body of the\nman-mountain, who used us with great civility and due respect to your\nmajesty's commission. Signed and sealed, on the fourth day of the\neighty-ninth moon of your majesty's auspicious reign.\n\n CLEFRIN FRELOC.\n MARSI FRELOC.\n\nWhen this inventory was read over to the emperor, he directed me,\nalthough in very gentle terms, to deliver up the several particulars.\n\nHe first called for my scimitar, which I took out, scabbard and all. In\nthe meantime, he ordered three thousand of his choicest troops (who then\nattended him) to surround me at a distance, with their bows and arrows\njust ready to discharge; but I did not observe it, for mine eyes were\nwholly fixed upon his majesty. He then desired me to draw my scimitar,\nwhich, although it had got some rust by the sea-water, was in most parts\nexceedingly bright. I did so, and immediately all the troops gave a\nshout between terror and surprise; for the sun shone clear, and the\nreflection dazzled their eyes, as I waved the scimitar to and fro in my\nhand. His majesty, who is a most magnanimous prince, was less daunted\nthan I could expect; he ordered me to return it into the scabbard, and\ncast it on the ground as gently as I could, about six feet from the end\nof my chain.\n\nThe next thing he demanded was one of the hollow iron pillars, by which\nhe meant my pocket-pistols. I drew it out, and at his desire, as well as\nI could, expressed to him the use of it; and charging it only with\npowder, which, by the closeness of my pouch, happened to escape wetting\nin the sea (an inconvenience against which all prudent mariners take\nspecial care to provide), I first cautioned the emperor not to be\nafraid, and then let it off in the air.\n\nThe astonishment here was much greater than at the sight of my scimitar.\nHundreds fell down as if they had been struck dead; and even the\nemperor, although he stood his ground, could not recover himself in some\ntime I delivered up both my pistols, in the same manner as I had done\nmy scimitar, and then my pouch of powder and bullets, begging him that\nthe former might be kept from fire, for it would kindle with the\nsmallest spark, and blow up his imperial palace into the air.\n\n[Illustration]\n\nI likewise delivered up my watch, which the emperor was very curious to\nsee, and commanded two of his tallest yeomen of the guards[18] to bear\nit on a pole upon their shoulders, as draymen in England do a barrel of\nale. He was amazed at the continual noise it made and the motion of the\nminute-hand, which he could easily discern; for their sight is much more\nacute than ours. He asked the opinions of his learned men about it,\nwhich were various and remote, as the reader may well imagine without my\nrepeating; although, indeed, I could not very perfectly understand them.\n\nI then gave up my silver and copper money, my purse, with nine large\npieces of gold, and some smaller ones; my knife and razor, my comb and\nsilver snuffbox, my handkerchief and journal-book. My scimitar, pistols,\nand pouch were conveyed in carriages to his majesty's stores; but the\nrest of my goods were returned to me.\n\nI had, as I before observed, one private pocket, which escaped their\nsearch, wherein there was a pair of spectacles (which I sometimes use\nfor the weakness of mine eyes), a pocket perspective,[19] and some other\nlittle conveniences; which, being of no consequence to the emperor, I\ndid not think myself bound in honor to discover; and I apprehended they\nmight be lost or spoiled if I ventured them out of my possession.\n\n[Illustration]\n\n\n\n\nCHAPTER III.\n\n THE AUTHOR DIVERTS THE EMPEROR AND HIS NOBILITY OF BOTH SEXES IN A\n VERY UNCOMMON MANNER. THE DIVERSIONS OF THE COURT OF LILLIPUT\n DESCRIBED. THE AUTHOR HAS HIS LIBERTY GRANTED HIM UPON CERTAIN\n CONDITIONS.\n\n\nMy gentleness and good behavior had gained so far on the emperor and his\ncourt, and indeed upon the army and people in general, that I began to\nconceive hopes of getting my liberty in a short time, I took all\npossible methods to cultivate this favorable disposition. The natives\ncame by degrees to be less apprehensive of any danger from me. I would\nsometimes lie down, and let five or six of them dance on my hand, and at\nlast the boys and girls would venture to come and play at hide and seek\nin my hair. I had now made a good progress in understanding and speaking\ntheir language.\n\nThe emperor had a mind, one day, to entertain me with one of the country\nshows, wherein they exceed all nations I have known, both for dexterity\nand magnificence. I was diverted with none so much as that of the\nrope-dancers, performed upon a slender white thread, extended about two\nfeet, and twelve inches from the ground. Upon which I shall desire\nliberty, with the reader's patience, to enlarge a little.\n\n[Illustration]\n\nThis diversion is only practised by those persons who are candidates for\ngreat employments and high favor at court. They are trained in this art\nfrom their youth, and are not always of noble birth or liberal\neducation. When a great office is vacant, either by death or disgrace\n(which often happens) five or six of those candidates petition the\nemperor to entertain his majesty, and the court, with a dance on the\nrope, and whoever jumps the highest, without falling, succeeds in the\noffice. Very often the chief ministers themselves are commanded to show\ntheir skill, and to convince the emperor that they have not lost their\nfaculty. Flimnap, the treasurer, is allowed to cut a caper on the\nstraight rope, at least an inch higher than any lord in the whole\nempire. I have seen him do the summersault several times together upon a\ntrencher,[20] fixed on a rope, which is no thicker than a common\npackthread in England. My friend Reldresal, principal secretary for\nprivate affairs, is, in my opinion, if I am not partial, the second\nafter the treasurer; the rest of the great officers are much upon a par.\n\nThese diversions are often attended with fatal accidents, whereof great\nnumbers are on record. I myself have seen two or three candidates break\na limb. But the danger is much greater when the ministers themselves are\ncommanded to show their dexterity! for, by contending to excel\nthemselves and their fellows, they strain so far that there is hardly\none of them who hath not received a fall, and some of them two or three.\nI was assured that a year or two before my arrival, Flimnap would have\ninfallibly broke his neck if one of the king's cushions, that\naccidentally lay on the ground, had not weakened the force of his fall.\n\nThere is likewise another diversion, which is only shown before the\nemperor and empress and first minister, upon particular occasions. The\nemperor lays on the table three fine silken threads, of six inches long;\none is purple, the other yellow, and the third white. These threads are\nproposed as prizes for those persons whom the emperor hath a mind to\ndistinguish by a peculiar mark of his favor. The ceremony is performed\nin his majesty's great chamber of state, where the candidates are to\nundergo a trial of dexterity very different from the former, and such as\nI have not observed the least resemblance of in any other country of the\nold or new world.\n\nThe emperor holds a stick in his hands, both ends parallel to the\nhorizon, while the candidates, advancing one by one, sometimes leap over\nthe stick, sometimes creep under it, backwards and forwards several\ntimes, according as the stick is advanced or depressed. Sometimes the\nemperor holds one end of the stick, and his first minister the other:\nsometimes the minister has it entirely to himself. Whoever performs his\npart with most agility, and holds out the longest in leaping and\ncreeping, is rewarded with the blue-colored silk; the yellow is given to\nthe next, and the green to the third, which they all wear girt twice\nabout the middle; and you see few great persons round about this court\nwho are not adorned with one of these girdles.\n\nThe horses of the army, and those of the royal stables, having been\ndaily led before me, were no longer shy, but would come up to my very\nfeet without starting. The riders would leap them over my hand as I held\nit on the ground; and one of the emperor's huntsmen, upon a large\ncourser, took my foot, shoe and all, which was indeed a prodigious leap.\n\nI had the good fortune to divert the emperor one day after a very\nextraordinary manner. I desired he would order several sticks of two\nfeet high, and the thickness of an ordinary cane, to be brought me;\nwhereupon his majesty commanded the master of his woods to give\ndirections accordingly; and the next morning six wood-men arrived with\nas many carriages, drawn by eight horses to each.\n\nI took nine of these sticks, and fixing them firmly in the ground in a\nquadrangular figure, two feet and a half square, I took four other\nsticks and tied them parallel at each corner, about two feet from the\nground; then I fastened my handkerchief to the nine sticks that stood\nerect, and extended it on all sides, till it was as tight as the top of\na drum; and the four parallel sticks, rising about five inches higher\nthan the handkerchief, served as ledges on each side.\n\nWhen I had finished my work, I desired the emperor to let a troop of his\nbest horse, twenty-four in number, come and exercise upon this plain.\nHis majesty approved of the proposal, and I took them up one by one in\nmy hands, ready mounted and armed, with the proper officers to exercise\nthem. As soon as they got into order, they divided into two parties,\nperformed mock skirmishes, discharged blunt arrows, drew their swords,\nfled and pursued, attacked and retired, and, in short, discovered the\nbest military discipline I ever beheld. The parallel sticks secured them\nand their horses from falling over the stage: and the emperor was so\nmuch delighted that he ordered this entertainment to be repeated several\ndays, and once was pleased to be lifted up and give the word of command;\nand, with great difficulty, persuaded even the empress herself to let me\nhold her in her close chair within two yards of the stage, from whence\nshe was able to take a full view of the whole performance.\n\nIt was my good fortune that no ill accident happened in these\nentertainments; only once a fiery horse, that belonged to one of the\ncaptains, pawing with his hoof, struck a hole in my handkerchief, and\nhis foot slipping, he overthrew his rider and himself; but I immediately\nrelieved them both, and covering the hole with one hand, I set down the\ntroop with the other, in the same manner as I took them up. The horse\nthat fell was strained in the left shoulder, but the rider got no hurt,\nand I repaired my handkerchief as well as I could; however, I would not\ntrust to the strength of it any more in such dangerous enterprises.\n\nAbout two or three days before I was set at liberty, as I was\nentertaining the court with feats of this kind, there arrived an express\nto inform his majesty that some of his subjects riding near the place\nwhere I was first taken up, had seen a great black substance lying on\nthe ground, very oddly shaped, extending its edges round as wide as his\nmajesty's bed-chamber, and rising up in the middle as high as a man;\nthat it was no living creature, as they had at first apprehended, for it\nlay on the grass without motion; and some of them had walked round it\nseveral times; that, by mounting upon each other's shoulders, they had\ngot to the top, which was flat and even, and, stamping upon it, they\nfound it was hollow within; that they humbly conceived it might be\nsomething belonging to the man-mountain; and if his majesty pleased,\nthey would undertake to bring it with only five horses.\n\n[Illustration]\n\nI presently knew what they meant, and was glad at heart to receive this\nintelligence. It seems, upon my first reaching the shore after our\nshipwreck, I was in such confusion that, before I came to the place\nwhere I went to sleep, my hat, which I had fastened with a string to my\nhead while I was rowing, and had stuck on all the time I was swimming,\nfell off after I came to land; the string, as I conjecture, breaking by\nsome accident which I never observed, but thought my hat had been lost\nat sea. I intreated his imperial majesty to give orders it might be\nbrought to me as soon as possible, describing to him the use and nature\nof it; and the next day the wagoners arrived with it, but not in a very\ngood condition; they had bored two holes in the brim, within an inch and\na half of the edge, and fastened two hooks in the holes; these hooks\nwere tied by a long cord to the harness; and thus my hat was dragged\nalong for above half an English mile; but the ground in that country\nbeing extremely smooth and level, it received less damage than I\nexpected.\n\nTwo days after this adventure, the emperor, having ordered that part of\nthe army which quarters in and about his metropolis to be in readiness,\ntook a fancy of diverting himself in a very singular manner. He desired\nI would stand like a colossus, with my legs as far asunder as I\nconveniently could. He then commanded his general (who was an old,\nexperienced leader and a great patron of mine) to draw up the troops in\nclose order and march under me; the foot by twenty-four abreast and the\nhorse by sixteen, with drums beating, colors flying, and pikes advanced.\nThis body consisted of three thousand foot and a thousand horse.\n\nI had sent so many memorials and petitions for my liberty, that his\nmajesty at length mentioned the matter, first in the cabinet, and then\nin full council; where it was opposed by none, except Skyrris Bolgolam\nwho was pleased, without any provocation, to be my mortal enemy. But it\nwas carried against him by the whole board, and confirmed by the\nemperor. That minister was _galbet_, or admiral of the realm, very much\nin his master's confidence, and a person well versed in affairs, but of\na morose and sour complexion. However, he was at length persuaded to\ncomply; but prevailed, that the articles and conditions upon which I\nshould be set free, and to which I must swear, should be drawn up by\nhimself.\n\nThese articles were brought to me by Skyrris Bolgolam in person,\nattended by two under-secretaries, and several persons of distinction.\nAfter they were read, I was demanded to swear to the performance of\nthem, first in the manner of my own country, and afterwards in the\nmethod prescribed by their laws; which was, to hold my right foot in my\nleft hand, and to place the middle finger of my right hand on the crown\nof my head, and my thumb on the tip of my right ear.\n\nBut because the reader may be curious to have some idea of the style and\nmanner of expression peculiar to that people, as well as to know the\narticles upon which I recovered my liberty, I have made a translation of\nthe whole instrument, word for word, as near as I was able, which I here\noffer to the public.\n\n_Golbasto Momaren Evlame Gurdilo Shefin Mully Ully Gue_, Most Mighty\nEmperor of Lilliput, delight and terror of the universe, whose dominions\nextend five thousand _blustrugs_ (about twelve miles in circumference) to\nthe extremities of the globe; monarch of all monarchs, taller than the\nsons of men; whose feet press down to the centre, and whose head strikes\nagainst the sun; at whose nod the princes of the earth shake their\nknees; pleasant as the spring, comfortable as the summer, fruitful as\nautumn, dreadful as winter. His most sublime majesty proposeth to the\nman-mountain, lately arrived at our celestial dominions, the following\narticles, which by a solemn oath he shall be obliged to perform.\n\nFirst. The man-mountain shall not depart from our dominions without our\nlicense under our great seal.\n\nSecond. He shall not presume to come into our metropolis, without our\nexpress order, at which time the inhabitants shall have two hours\nwarning to keep within doors.\n\nThird. The said man-mountain shall confine his walks to our principal\nhigh roads, and not offer to walk or lie down in a meadow or field of\ncorn.[21]\n\nFourth. As he walks the said roads, he shall take the utmost care not to\ntrample upon the bodies of any of our loving subjects, their horses or\ncarriages, nor take any of our subjects into his hands without their own\nconsent.\n\nFifth. If an express requires extraordinary despatch, the man-mountain\nshall be obliged to carry in his pocket the messenger and horse a\nsix-days' journey once in every moon, and return the said messenger back\n(if so required) safe to our imperial presence.\n\nSixth. He shall be our ally against our enemies in the island of\nBlefuscu, and do his utmost to destroy their fleet, which is now\npreparing to invade us.\n\nSeventh. That the said man-mountain shall at his times of leisure be\naiding and assisting to our workmen, in helping to raise certain great\nstones, towards covering the wall of the principal park, and other our\nroyal buildings.\n\nEighth. That the said man-mountain shall, in two moons time, deliver in\nan exact survey of the circumference of our dominions, by a computation\nof his own paces round the coast.\n\nLastly. That upon his solemn oath to observe all the above articles, the\nsaid man-mountain shall have a daily allowance of meat and drink\nsufficient for the support of 1724 of our subjects, with free access to\nour royal person, and other marks of our favor. Given at our palace at\nBelfaborac, the twelfth day of the ninety-first moon of our reign.\n\nI swore and subscribed to the articles with great cheerfulness and\ncontent, although some of them were not so honorable as I could have\nwished; which proceeded wholly from the malice of Skyrris Bolgolam, the\nhigh admiral; whereupon my chains were immediately unlocked, and I was\nat full liberty. The emperor himself in person did me the honor to be by\nat the whole ceremony. I made my acknowledgments, by prostrating myself\nat his majesty's feet: but he commanded me to rise; and after many\ngracious expressions, which, to avoid the censure of vanity, I shall not\nrepeat, he added, that he hoped I should prove a useful servant, and\nwell deserve all the favors he had already conferred upon me, or might\ndo for the future.\n\nThe reader may please to observe, that, in the last article for the\nrecovery of my liberty, the emperor stipulates to allow me a quantity of\nmeat and drink sufficient for the support of 1724 Lilliputians. Some\ntime after, asking a friend at court, how they came to fix on that\ndeterminate number, he told me, that his majesty's mathematicians having\ntaken the height of my body by the help of a quadrant,[22] and finding\nit to exceed theirs in the proportion of twelve to one, they concluded,\nfrom the similarity of their bodies, that mine must contain at least\n1724 of theirs, and consequently would require as much food as was\nnecessary to support that number of Lilliputians. By which the reader\nmay conceive an idea of the ingenuity of that people, as well as the\nprudent and exact economy of so great a prince.\n\n\n\n\nCHAPTER IV.\n\n MILENDO, THE METROPOLIS OF LILLIPUT, DESCRIBED TOGETHER WITH THE\n EMPEROR'S PALACE. A CONVERSATION BETWEEN THE AUTHOR AND A PRINCIPAL\n SECRETARY, CONCERNING THE AFFAIRS OF THAT EMPIRE. THE AUTHOR OFFERS\n TO SERVE THE EMPEROR IN HIS WARS.\n\n\nThe first request I made, after I had obtained my liberty, was, that I\nmight have license to see Milendo, the metropolis; which the emperor\neasily granted me, but with a special charge to do no hurt, either to\nthe inhabitants or their houses. The people had notice, by proclamation,\nof my design to visit the town.\n\nThe wall, which encompassed it, is two feet and a half high, and at\nleast eleven inches broad, so that a coach and horses may be driven very\nsafely round it; and it is flanked with strong towers at ten feet\ndistance. I stept over the great western gate, and passed very gently,\nand sideling, through the two principal streets, only in my short\nwaistcoat, for fear of damaging the roofs and eaves of the houses with\nthe skirts[23] of my coat. I walked with the utmost circumspection, to\navoid treading on any stragglers who might remain in the streets;\nalthough the orders were very strict, that all people should keep in\ntheir houses at their own peril. The garret-windows and tops of houses\nwere so crowded with spectators, that I thought in all my travels I had\nnot seen a more populous place.\n\nThe city is an exact square, each side of the wall being five hundred\nfeet long. The two great streets, which run across and divide it into\nfour quarters, are five feet wide. The lanes and alleys, which I could\nnot enter, but only viewed them as I passed, are from twelve to eighteen\ninches. The town is capable of holding five hundred thousand souls; the\nhouses are from three to five stories; the shops and markets well\nprovided.\n\nThe emperor's palace is in the centre of the city, where the two great\nstreets meet. It is enclosed by a wall of two foot high, and twenty foot\ndistant from the buildings. I had his majesty's permission to step over\nthis wall; and the space being so wide between that and the palace, I\ncould easily view it on every side.\n\nThe outward court is a square of forty feet, and includes two other\ncourts; in the inmost are the royal apartments, which I was very\ndesirous to see, but found it extremely difficult; for the great gates\nfrom one square into another were but eighteen inches high, and seven\ninches wide. Now the buildings of the outer court were at least five\nfeet high, and it was impossible for me to stride over them without\ninfinite damage to the pile, though the walls were strongly built of\nhewn stone, and four inches thick.\n\nAt the same time, the emperor had a great desire that I should see the\nmagnificence of his palace; but this I was not able to do till three\ndays after, which I spent in cutting down, with my knife, some of the\nlargest trees in the royal park, about an hundred yards distance from\nthe city. Of these trees I made two stools, each about three feet high,\nand strong enough to bear my weight.\n\n[Illustration: \"HER IMPERIAL MAJESTY WAS PLEASED TO SMILE VERY GRACIOUSLY\nUPON ME\" P. 50.]\n\nThe people having received notice a second time, I went again through\nthe city to the palace, with my two stools in my hands. When I came to\nthe side of the outer court, I stood upon one stool, and took the other\nin my hand; this I lifted over the roof, and gently set it down on the\nspace between the first and second court, which was eight feet wide. I\nthen stept over the building very conveniently, from one stool to the\nother, and drew up the first after me with a hooked stick. By this\ncontrivance I got into the inmost court; and, lying down upon my side, I\napplied my face to the windows of the middle stories, which were left\nopen on purpose, and discovered the most splendid apartments that can be\nimagined. There I saw the empress and the young princes in their several\nlodgings, with their chief attendants about them. Her imperial majesty\nwas pleased to smile very graciously upon me, and gave me out of the\nwindow her hand to kiss.\n\nBut I shall not anticipate the reader with farther descriptions of this\nkind, because I reserve them for a greater work, which is now almost\nready for the press, containing a general description of this empire,\nfrom its first erection, through a long series of princes, with a\nparticular account of their wars and politics, laws, learning, and\nreligion, their plants and animals, their peculiar manners and customs,\nwith other matters very curious and useful; my chief design, at present,\nbeing only to relate such events and transactions as happened to the\npublic, or to myself, during a residence of about nine months in that\nempire.\n\nOne morning, about a fortnight after I had obtained my liberty,\nReldresal, principal secretary (as they style him) for private affairs,\ncame to my house, attended only by one servant. He ordered his coach to\nwait at a distance, and desired I would give him an hour's audience;\nwhich I readily consented to, on account of his quality and personal\nmerits, as well as of the many good offices he had done me during my\nsolicitations at court. I offered to lie down, that he might the more\nconveniently reach my ear; but he chose rather to let me hold him in my\nhand during our conversation.\n\nHe began with compliments on my liberty; said he might pretend to some\nmerit in it. But however, added, that if it had not been for the present\nsituation of things at court, perhaps I might not have obtained it so\nsoon. For, said he, as flourishing a condition as we may appear to be in\nto foreigners, we labor under two mighty evils: a violent faction at\nhome, and the danger of an invasion, by a most potent enemy, from\nabroad. As to the first, you are to understand, that, for above seventy\nmoons past, there have been two struggling parties in this empire, under\nthe names of _Tramecksan_ and _Slamecksan_, from the high and low heels\nof their shoes, by which they distinguish themselves. It is alleged,\nindeed, that the high heels are most agreeable to our ancient\nconstitution; but, however this may be, his majesty hath determined to\nmake use only of low heels in the administration of the government, and\nall offices in the gift of the crown, as you cannot but observe: and\nparticularly, that his majesty's imperial heels are lower, at least by a\n_drurr_, than any of his court (_drurr_ is a measure about the\nfourteenth part of an inch). The animosities between these two parties\nrun so high, that they will neither eat nor drink nor talk with each\nother. We compute the _Tramecksan_, or high heels, to exceed us in\nnumber; but the power is wholly on our side. We apprehend his imperial\nhighness, the heir to the crown, to have some tendency towards the high\nheels; at least, we can plainly discover that one of his heels is higher\nthan the other, which gives him a hobble in his gait. Now, in the midst\nof these intestine disquiets, we are threatened with an invasion from\nthe island of Blefuscu, which is the other great empire of the universe,\nalmost as large and powerful as this of his majesty. For, as to what we\nhave heard you affirm, that there are other kingdoms and states in the\nworld, inhabited by human creatures as large as yourself, our\nphilosophers are in much doubt, and would rather conjecture that you\ndropped from the moon or one of the stars, because it is certain, that\nan hundred mortals of your bulk would, in a short time, destroy all the\nfruits and cattle of his majesty's dominions. Besides, our histories of\nsix thousand moons make no mention of any other regions than the two\ngreat empires of Lilliput and Blefuscu. Which two mighty powers have, as\nI was going to tell you, been engaged in a most obstinate war for\nsix-and-thirty moons past. It began upon the following occasion: It is\nallowed on all hands, that the primitive way of breaking eggs, before we\neat them, was upon the larger end; but his present majesty's\ngrandfather, while he was a boy, going to eat an egg, and breaking it\naccording to the ancient practice, happened to cut one of his fingers.\nWhereupon the emperor, his father, published an edict, commanding all\nhis subjects, upon great penalties, to break the smaller end of their\neggs. The people so highly resented this law, that our histories tell\nus, there have been six rebellions raised on that account, wherein one\nemperor lost his life, and another his crown. These civil commotions\nwere constantly fomented by the monarchs of Blefuscu; and when they\nwere quelled, the exiles always fled for refuge to that empire. It is\ncomputed, that eleven thousand persons have, at several times, suffered\ndeath, rather than submit to break their eggs at the smaller end. Many\nhundred large volumes have been published upon this controversy, but the\nbooks of the Big-endians have been long forbidden, and the whole party\nrendered incapable, by law, of holding employments. During the course of\nthese troubles, the Emperors of Blefuscu did frequently expostulate, by\ntheir ambassadors, accusing us of making a schism in religion, by\noffending against a fundamental doctrine of our great prophet Lustrog,\nin the fifty-fourth chapter of the Blundecral (which is their\nAlcoran)[24] This, however, is thought to be a mere strain upon the\ntext; for the words are these: That all true believers break their eggs\nat the convenient end. And which is the convenient end, seems, in my\nhumble opinion, to be left to every man's conscience, or, at least, in\nthe power of the chief magistrate to determine. Now, the Big-endian\nexiles have found so much credit in the emperor of Blefuscu's court, and\nso much private assistance and encouragement from their party here at\nhome, that a bloody war hath been carried on between the two empires for\nsix-and-thirty moons, with various success; during which time we have\nlost forty capital ships, and a much greater number of smaller vessels,\ntogether with thirty thousand of our best seamen and soldiers; and the\ndamage received by the enemy is reckoned to be somewhat greater than\nours. However, they have now equipped a numerous fleet, and are just\npreparing to make a descent upon us; and his imperial majesty, placing\ngreat confidence in your valor and strength, hath commanded me to lay\nthis account of his affairs before you.\n\n[Illustration]\n\n[Illustration]\n\nI desired the secretary to present my humble duty to the emperor, and to\nlet him know that I thought it would not become me, who was a foreigner,\nto interfere with parties; but I was ready, with the hazard of my life,\nto defend his person and state against all invaders.\n\n\n\n\nCHAPTER V.\n\n THE AUTHOR, BY AN EXTRAORDINARY STRATAGEM, PREVENTS AN INVASION. A\n HIGH TITLE OF HONOR IS CONFERRED UPON HIM. AMBASSADORS ARRIVE FROM\n THE EMPEROR OF BLEFUSCU, AND SUE FOR PEACE. THE EMPRESS'S APARTMENT\n ON FIRE, BY ACCIDENT; THE AUTHOR INSTRUMENTAL IN SAVING THE REST OF\n THE PALACE.\n\n\nThe empire of Blefuscu is an island, situate to the north northeast of\nLilliput, from whence it is parted only by a channel of eight hundred\nyards wide. I had not yet seen it; and upon this notice of an intended\ninvasion, I avoided appearing on that side of the coast, for fear of\nbeing discovered by some of the enemy's ships, who had received no\nintelligence of me, all intercourse between the two empires having been\nstrictly forbidden during the war, upon the pain of death, and an\nembargo[25] laid by our emperor upon all vessels whatsoever.\n\nI communicated to his majesty a project I had formed, of seizing the\nenemy's whole fleet; which, as our scouts assured us, lay at anchor in\nthe harbor, ready to sail with the first fair wind. I consulted the most\nexperienced seamen upon the depth of the channel, which they had often\nplumbed; who told me, that in the middle, at high water, it was seventy\n_glumgluffs_ deep, which is about six feet of European measure; and the\nrest of it fifty _glumgluffs_ at most. I walked towards the northeast\ncoast, over against Blefuscu; where, lying down behind a hillock, I took\nout my small perspective glass, and viewed the enemy's fleet at anchor,\nconsisting of about fifty men-of-war, and a great number of transports;\nI then came back to my house, and gave orders (for which I had a\nwarrant) for a great quantity of the strongest cable and bars of iron.\nThe cable was about as thick as packthread, and the bars of the length\nand size of a knitting needle. I trebled the cable, to make it stronger;\nand, for the same reason, I twisted three of the iron bars together,\nbending the extremities into a hook.\n\nHaving thus fixed fifty hooks to as many cables, I went back to the\nnortheast coast, and putting off my coat, shoes, and stockings, walked\ninto the sea in my leathern jerkin, about half an hour before\nhigh-water. I waded with what haste I could, and swam in the middle\nabout thirty yards, till I felt ground; I arrived at the fleet in less\nthan half an hour. The enemy were so frightened, when they saw me, that\nthey leaped out of their ships, and swam to shore, where there could not\nbe fewer than thirty thousand souls: I then took my tackling, and\nfastening a hook to the hole at the prow of each, I tied all the cords\ntogether at the end.\n\nWhile I was thus employed, the enemy discharged several thousand arrows,\nmany of which stuck in my hands and face; and, besides the excessive\nsmart, gave me much disturbance in my work. My greatest apprehension was\nfor mine eyes, which I should have infallibly lost, if I had not\nsuddenly thought of an expedient. I kept, among other little\nnecessaries, a pair of spectacles, in a private pocket, which, as I\nobserved before, had escaped the emperor's searchers. These I took out,\nand fastened as strongly as I could upon my nose, and thus armed, went\non boldly with my work, in spite of the enemy's arrows, many of which\nstruck against the glasses of my spectacles, but without any other\neffect, farther than a little to discompose them.[26] I had now fastened\nall the hooks, and, taking the knot in my hand, began to pull: but not a\nship would stir, for they were all too fast held by their anchors; so\nthat the boldest part of my enterprise remained. I therefore let go the\ncord, and, leaving the hooks fixed to the ships, I resolutely cut with\nmy knife the cables that fastened the anchors, receiving above two\nhundred shots in my face and hands; then I took up the knotted end of\nthe cables, to which my hooks were tied, and, with great ease, drew\nfifty of the enemy's largest men-of-war after me.\n\nThe Blefuscudians, who had not the least imagination of what I intended,\nwere at first confounded with astonishment. They had seen me cut the\ncables, and thought my design was only to let the ships run adrift, or\nfall foul on each other: but when they perceived the whole fleet moving\nin order, and saw me pulling at the end, they set up such a scream of\ngrief and despair as it is almost impossible to describe or conceive.\nWhen I had got out of danger, I stopped awhile to pick out the arrows\nthat stuck in my hands and face: and rubbed on some of the same ointment\nthat was given me at my first arrival, as I have formerly mentioned. I\nthen took off my spectacles, and waiting about an hour, till the tide\nwas a little fallen, I waded through the middle with my cargo, and\narrived safe at the royal port of Lilliput.\n\nThe emperor and his whole court stood on the shore, expecting the issue\nof this great adventure. They saw the ships move forward in a large\nhalf-moon, but could not discern me, who was up to my breast in water.\nWhen I advanced to the middle of the channel, they were yet more in\npain, because I was under water to my neck. The emperor concluded me to\nbe drowned, and that the enemy's fleet was approaching in an hostile\nmanner: but he was soon eased of his fears; for the channel growing\nshallower every step I made, I came in a short time within hearing; and\nholding up the end of the cable, by which the fleet was fastened, I\ncried in a loud voice, Long live the most puissant[27] emperor of\nLilliput! This great prince received me at my landing, with all possible\nencomiums, and created me a _nardac_ upon the spot, which is the highest\ntitle of honor among them.\n\nHis majesty desired I would take some other opportunity of bringing all\nthe rest of his enemy's ships into his ports. And so immeasurable is the\nambition of princes, that he seemed to think of nothing less than\nreducing the whole empire of Blefuscu into a province, and governing it\nby viceroy; of destroying the Big-endian exiles, and compelling that\npeople to break the smaller end of their eggs, by which he would remain\nthe sole monarch of the whole world. But I endeavored to divert him from\nthis design, by many arguments, drawn from the topics of policy, as well\nas justice. And I plainly protested, that I would never be an instrument\nof bringing a free and brave people into slavery. And when the matter\nwas debated in council, the wisest part of the ministry were of my\nopinion.\n\n[Illustration: \"AND CREATED ME A _NARDAC_ UPON THE SPOT.\" P. 58.]\n\nThis open, bold declaration of mine was so opposite to the schemes and\npolitics of his imperial majesty, that he could never forgive me; he\nmentioned it, in a very artful manner, at council, where, I was told,\nthat some of the wisest appeared, at least by their silence, to be of my\nopinion; but others, who were my secret enemies, could not forbear some\nexpressions, which by a side-wind reflected on me. And, from this time\nbegan an intrigue between his majesty and a junto[28] of ministers\nmaliciously bent against me, which broke out in less than two months,\nand had like to have ended in my utter destruction. Of so little weight\nare the greatest services to princes, when put into the balance with a\nrefusal to gratify their passions.\n\nAbout three weeks after this exploit, there arrived a solemn embassy\nfrom Blefuscu, with humble offers of peace; which was soon concluded,\nupon conditions very advantageous to our emperor, wherewith I shall not\ntrouble the reader. There were six ambassadors, with a train of about\nfive hundred persons; and their entry was very magnificent, suitable to\nthe grandeur of their master, and the importance of their business. When\ntheir treaty was finished, wherein I did them several good offices, by\nthe credit I now had, or at least appeared to have at court, their\nexcellencies, who were privately told how much I had been their friend,\nmade me a visit in form. They began with many compliments upon my valor\nand generosity, invited me to that kingdom, in the emperor their\nmaster's name, and desired me to show some proofs of my prodigious\nstrength, of which they had heard so many wonders; wherein I readily\nobliged them, but shall not trouble the reader with the particulars.\n\n[Illustration]\n\nWhen I had for some time entertained their Excellencies, to their\ninfinite satisfaction and surprise, I desired they would do me the honor\nto present my most humble respects to the emperor their master, the\nrenown of whose virtues had so justly filled the whole world with\nadmiration, and whose royal person I resolved to attend, before I\nreturned to my own country. Accordingly, the next time I had the honor\nto see our emperor, I desired his general license to wait on the\nBlefuscudian monarch, which he was pleased to grant me, as I could\nplainly perceive, in a very cold manner; but could not guess the reason,\ntill I had a whisper from a certain person, that Flimnap and Bolgolam\nhad represented my intercourse with those ambassadors as a mark of\ndisaffection, from which, I am sure, my heart was wholly free. And this\nwas the first time I began to conceive some imperfect idea of courts and\nministers.\n\nIt is to be observed, that these ambassadors spoke to me by an\ninterpreter, the languages of both empires differing as much from each\nother as any two in Europe, and each nation priding itself upon the\nantiquity, beauty, and energy of its own tongue, with an avowed contempt\nfor that of its neighbor; yet our emperor, standing upon the advantage\nhe had got by the seizure of their fleet, obliged them to deliver their\ncredentials, and make their speech in the Lilliputian tongue.\n\nAnd it must be confessed, that, from the great intercourse of trade and\ncommerce between both realms; from the continual reception of exiles,\nwhich is mutual among them; and from the custom in each empire, to send\ntheir young nobility, and richer gentry, to the other, in order to\npolish themselves, by seeing the world, and understanding men and\nmanners; there are few persons of distinction, or merchants, or, seamen,\nwho dwell in the maritime parts, but what can hold conversation in both\ntongues, as I found some weeks after, when I went to pay my respects to\nthe Emperor of Blefuscu, which, in the midst of great misfortunes,\nthrough the malice of my enemies, proved a very happy adventure to me,\nas I shall relate in its proper place.\n\nThe reader may remember, that when I signed those articles, upon which I\nrecovered my liberty, there were some which I disliked, upon account of\ntheir being too servile; neither could anything but an extreme necessity\nhave forced me to submit. But, being now a _nardac_ of the highest rank\nin that empire, such offices were looked upon as below my dignity, and\nthe emperor, to do him justice, never once mentioned them to me.\nHowever, it was not long before I had an opportunity of doing his\nmajesty, at least as I then thought, a most signal service. I was\nalarmed at midnight with the cries of many hundred people at my door, by\nwhich, being suddenly awaked, I was in some kind of terror. I heard the\nword _burglum_ repeated incessantly.\n\nSeveral of the emperor's court, making their way through the crowd,\nentreated me to come immediately to the palace, where her imperial\nmajesty's apartment was on fire, by the carelessness of a maid of honor,\nwho fell asleep while she was reading a romance. I got up in an instant;\nand orders being given to clear the way before me, and it being likewise\na moonshine night, I made a shift to get to the palace, without\ntrampling on any of the people. I found they had already applied ladders\nto the walls of the apartment, and were well provided with buckets, but\nthe water was at some distance. These buckets were about the size of a\nlarge thimble, and the poor people supplied me with them as fast as they\ncould; but the flame was so violent that they did little good. I might\neasily have stifled it with my coat, which I unfortunately left behind\nme for haste, and came away only in my leathern jerkin. The case seemed\nwholly desperate and deplorable, and this magnificent palace would have\ninfallibly been burnt down to the ground, if, by a presence of mind\nunusual to me, I had not suddenly thought of an expedient by which in\nthree minutes the fire was wholly extinguished, and the rest of that\nnoble pile, which had cost so many ages in erecting, preserved from\ndestruction.\n\n[Illustration]\n\nIt was now daylight, and I returned to my house, without waiting to\ncongratulate with the emperor; because, although I had done a very\neminent piece of service, yet I could not tell how his majesty might\nresent the manner by which I had performed it: for, by the fundamental\nlaws of the realm, it is capital in any man, of what quality soever, to\neven touch the empress or the royal princesses without invitation. But I\nwas a little comforted by a message from his majesty, that he would give\norders to the grand justiciary for passing my pardon in form, which,\nhowever, I could not obtain. And I was privately assured that the\nempress, conceiving the greatest abhorrence of me, and, in the presence\nof her chief confidants, could not forbear vowing revenge.\n\n\n\n\nCHAPTER VI.\n\n OF THE INHABITANTS OF LILLIPUT; THEIR LEARNING, LAWS, AND CUSTOMS;\n THE MANNER OF EDUCATING THEIR CHILDREN. THE AUTHOR'S WAY OF LIVING\n IN THAT COUNTRY.\n\n\nAlthough I intend to leave the description of this empire to a\nparticular treatise, yet, in the meantime, I am content to gratify the\ncurious reader with some general ideas. As the common size of the\nnatives is somewhat under six inches high, so there is an exact\nproportion in all other animals, as well as plants and trees: for\ninstance, the tallest horses and oxen are between four and five inches\nin height, the sheep an inch and a half, more or less; their geese about\nthe bigness of a sparrow, and so the several gradations downwards, till\nyou come to the smallest, which, to my sight, were almost invisible; but\nnature hath adapted the eyes of the Lilliputians to all objects proper\nfor their view; they see with great exactness, but at no great distance.\nAnd, to show the sharpness of their sight, towards objects that are\nnear, I have been much pleased with observing a cook pulling[29] a lark,\nwhich was not so large as a common fly; and a young girl threading an\ninvisible needle with invisible silk.\n\nTheir tallest trees are about seven feet high; I mean some of those in\nthe great royal park, the tops whereof I could but just reach with my\nfist clenched. The other vegetables are in the same proportion; but this\nI leave to the reader's imagination.\n\nI shall say but little at present of their learning, which, for many\nages, hath flourished in all its branches among them: but their manner\nof writing is very peculiar, being neither from the left to the right\nlike the Europeans; nor from the right to the left, like the Arabians;\nnor from up to down, like the Chinese, but aslant, from one corner of\nthe paper to the other, like ladies in England.\n\nThey bury their dead with their heads directly downwards, because they\nhold an opinion, that in eleven thousand moons they are all to rise\nagain, in which period the earth (which they conceive to be flat) will\nturn upside down, and by this means they shall, at the resurrection, be\nfound ready, standing on their feet. The learned among them confess the\nabsurdity of this doctrine, but the practice still continues, in\ncompliance to the vulgar.\n\nThere are some laws and customs in this empire very peculiar; and, if\nthey were not so directly contrary to those of my own dear country, I\nshould be tempted to say a little in their justification. It is only to\nbe wished they were as well executed. The first I shall mention relates\nto informers. All crimes against the state are punished here with the\nutmost severity; but, if the person accused maketh his innocence plainly\nto appear upon his trial, the accuser is immediately put to an\nignominious death; and, out of his goods, or lands, the innocent person\nis quadruply recompensed for the loss of his time, for the danger he\nunderwent, for the hardship of his imprisonment, and for all the charges\nhe hath been at in making his defence, or, it that fund be deficient,\nit is largely supplied by the crown. The emperor also confers on him\nsome public mark of his favor, and proclamation is made of his innocence\nthrough the whole city.\n\nThey look upon fraud as a greater crime than theft, and therefore seldom\nfail to punish it with death; for they allege, that care and vigilance,\nwith a very common understanding, may preserve a man's goods from\nthieves, but honesty has no fence against superior cunning; and, since\nit is necessary that there should be a perpetual intercourse of buying\nand selling, and dealing upon credit, where fraud is permitted and\nconnived at, or hath no law to punish it, the honest dealer is always\nundone, and the knave gets the advantage. I remember, when I was once\ninterceding with the king for a criminal, who had wronged his master of\na great sum of money, which he had received by order, and run away with,\nand happening to tell his majesty, by way of extenuation, that it was\nonly a breach of trust, the emperor thought it monstrous in me, to offer\nas a defence the greatest aggravation of the crime; and, truly, I had\nlittle to say in return, farther than the common answer, that different\nnations had different customs; for, I confess, I was heartily ashamed.\n\nAlthough we usually call reward and punishment the two hinges upon which\nall government turns, yet I could never observe this maxim to be put in\npractice by any nation except that of Lilliput. Whoever can there bring\nsufficient proof that he hath strictly observed the laws of his country\nfor seventy-three moons, hath a claim to certain privileges, according\nto his quality and condition of life, with a proportionable sum of out\nof a fund appropriated for that use; he likewise acquires the title of\n_snillpall_, or _legal_, which is added to his name, but doth not\ndescend to his posterity. And these people thought it a prodigious\ndefect of policy among us, when I told them that our laws were enforced\nonly by penalties, without any mention of reward. It is upon this\naccount that the image of Justice, in their courts of judicature, is\nformed with six eyes, two before, as many behind, and on each side one,\nto signify circumspection, with a bag of gold open in her right hand,\nand a sword sheath in her left, to show she was more disposed to reward\nthan to punish.\n\nIn choosing persons for all employments, they have more regard to good\nmorals than to great abilities; for, since government is necessary to\nmankind, they believe that the common size of human understanding is\nfitted to some station or other, and that Providence never intended to\nmake the management of public affairs a mystery, to be comprehended only\nby a few persons of sublime genius, of which there seldom are three born\nin an age; but they suppose truth, justice, temperance, and the like, to\nbe in every man's power, the practice of which virtues, assisted by\nexperience, and a good intention, would qualify any man for the service\nof his country, except where a course of study is required. But they\nthought the want of moral virtues was so far from being supplied by\nsuperior endowments of the mind, that employments could never be put\ninto such dangerous hands as those of persons so qualified; and at\nleast, that the mistakes committed by ignorance, in a virtuous\ndisposition, would never be of such fatal consequences to the public\nweal as the practices of a man whose inclinations led him to be corrupt,\nand who had great abilities to manage, to multiply, and defend his\ncorruptions.\n\nIn like manner, the disbelief of a Divine Providence renders a man\nincapable of holding any public station; for, since kings avow\nthemselves to be the deputies of Providence, the Lilliputians think\nnothing can be more absurd than for a prince to employ such men as\ndisown the authority under which he acts.\n\nIn relating these and the following laws, I would only be understood to\nmean the original institutions, and not the most scandalous corruptions\ninto which these people are fallen, by the degenerate nature of man.\nFor, as to that infamous practice of acquiring great employments by\ndancing on the ropes, or badges of favor and distinction by leaping over\nsticks, and creeping under them, the reader is to observe, that they\nwere first introduced by the grandfather of the emperor, now reigning,\nand grew to the present height by the gradual increase of party and\nfaction.\n\nIngratitude is, among them, a capital crime, as we read it to have been\nin some other countries; for they reason thus, that whoever makes ill\nreturns to his benefactor, must needs be a common enemy to the rest of\nmankind, from whom he hath received no obligation, and therefore such a\nman is not fit to live.\n\nTheir notions relating to the duties of parents and children differ\nextremely from ours. Their opinion is, that parents are the last of all\nothers to be trusted with the education of their own children; and,\ntherefore, they have, in every town, public nurseries, where all\nparents, except cottagers and laborers, are obliged to send their\ninfants of both sexes to be reared and educated, when they come to the\nage of twenty moons, at which time they are supposed to have some\nrudiments of docility. These schools are of several kinds, suited to\ndifferent qualities, and to both sexes. They have certain professors,\nwell skilled in preparing children for such a condition of life as\nbefits the rank of their parents, and their own capacities as well as\ninclinations. I shall first say something of the male nurseries, and\nthen of the female.\n\nThe nurseries for males of noble or eminent birth are provided with\ngrave and learned professors, and their several deputies. The clothes\nand food of the children are plain and simple. They are bred up in the\nprinciples of honor, justice, courage, modesty, clemency, religion, and\nlove of their country; they are always employed in some business, except\nin the times of eating and sleeping, which are very short, and two hours\nfor diversions, consisting of bodily exercises. They are dressed by men\ntill four years of age, and then are obliged to dress themselves,\nalthough their quality be ever so great; and the women attendants, who\nare aged proportionably to ours at fifty, perform only the most menial\noffices. They are never suffered to converse with servants, but go\ntogether in smaller or greater numbers to take their diversions, and\nalways in the presence of a professor, or one of his deputies; whereby\nthey avoid those early bad impressions of folly and vice, to which our\nchildren are subject. Their parents are suffered to see them only twice\na year; the visit to last but an hour; they are allowed to kiss the\nchild at meeting and parting; but a professor, who always stands by on\nthose occasions, will not suffer them to whisper, or use any fondling\nexpressions, or bring any presents of toys, sweetmeats, and the like.\n\nThe pension from each family, for the education and entertainment of a\nchild, upon failure of due payment, is levied by the emperor's officers.\n\nThe nurseries for children of ordinary gentlemen, merchants, traders,\nand handicrafts, are managed proportionally after the same manner; only\nthose designed for trades are put out apprentices at eleven years old,\nwhereas those persons of quality continue in their exercises till\nfifteen, which answers to twenty-one with us; but the confinement is\ngradually lessened for the last three years.\n\nIn the female nurseries, the young girls of quality are educated much\nlike the males, only they are dressed by orderly servants of their own\nsex; but always in the presence of a professor or deputy, till they come\nto dress themselves, which is at five years old. And if it be found that\nthese nurses ever presume to entertain the girls with frightful or\nfoolish stories, or the common follies practised by the chambermaids\namong us, they are publicly whipped thrice about the city, imprisoned\nfor a year, and banished for life to the most desolate part of the\ncountry. Thus, the young ladies there are as much ashamed of being\ncowards and fools as the men, and despise all personal ornaments beyond\ndecency and cleanliness: neither did I perceive any difference in their\neducation, made by their difference of sex, only that the exercises of\nthe women were not altogether so robust, and that some rules were given\nthem relating to domestic life, and a smaller compass of learning was\nenjoined them: for their maxim is that, among people of quality, a wife\nshould be always a reasonable and agreeable companion, because she\ncannot always be young. When the girls are twelve years old, which\namong them is the marriageable age, their parents or guardians take\nthem home, with great expressions of gratitude to the professors, and\nseldom without tears of the young lady and her companions.\n\nIn the nurseries of females of the meaner sort, the children are\ninstructed in all kinds of works proper for their sex and their several\ndegrees; those intended for apprentices are dismissed at seven years\nold, the rest are kept to eleven.\n\nThe meaner[30] families who have children at these nurseries are\nobliged, besides their annual pension, which is as low as possible, to\nreturn to the steward of the nursery a small monthly share of their\ngettings, to be a portion[31] for the child; and, therefore, all parents\nare limited in their expenses by the law. For the Lilliputians think\nnothing can be more unjust than for people to leave the burden of\nsupporting their children on the public. As to persons of quality, they\ngive security to appropriate a certain sum for each child, suitable to\ntheir condition; and these funds are always managed with good husbandry\nand the most exact justice.\n\nThe cottagers and laborers keep their children at home, their business\nbeing only to till and cultivate the earth, and therefore their\neducation is of little consequence to the public; but the old and\ndiseased among them are supported by hospitals; for begging is a trade\nunknown in this empire.\n\nAnd here it may perhaps divert the curious reader to give some account\nof my domestic,[32] and my manner of living in this country, during a\nresidence of nine months and thirteen days. Having a head for\nmechanics, and being likewise forced by necessity, I had made for myself\na table and chair, convenient enough, out of the largest trees in the\nroyal park. Two hundred sempstresses were employed to make me shirts,\nand linen for my bed and table, all of the strongest and coarsest kind\nthey could get; which, however, they were forced to quilt together in\nseveral folds, for the thickest was some degrees finer than lawn. Their\nlinen is usually three inches wide, and three feet make a piece.\n\nThe sempstresses took my measure as I lay on the ground, one standing at\nmy neck, and another at my mid-leg, with a strong cord extended that\neach held by the end, while a third measured the length of the cord with\na rule of an inch long. Then they measured my right thumb, and desired\nno more; for, by a mathematical computation, that twice round the thumb\nis once round the wrist, and so on to the neck and the waist, and by the\nhelp of my old shirt, which I displayed on the ground before them for a\npattern, they fitted me exactly. Three hundred tailors were employed in\nthe same manner to make me clothes; but they had another contrivance for\ntaking my measure. I kneeled down, and they raised a ladder from the\nground to my neck; upon this ladder one of them mounted, and let fall a\nplumb-line from my collar to the floor, which just answered the length\nof my coat; but my waist and arms I measured myself. When my clothes\nwere finished, which was done in my house (for the largest of theirs\nwould not have been able to hold them), they looked like the patchwork\nmade by the ladies in England, only that mine were all of a color.\n\n[Illustration: \"THREE HUNDRED TAILORS WERE EMPLOYED TO MAKE ME CLOTHES\"\nP. 74.]\n\nI had three hundred cooks to dress my victuals, in little convenient\nhuts built about my house, where they and their families lived, and\nprepared me two dishes a-piece. I took up twenty waiters in my hand, and\nplaced them on the table; an hundred more attended below on the ground,\nsome with dishes of meat, and some with barrels of wine and other\nliquors, flung on their shoulders; all of which the waiters above drew\nup, as I wanted, in a very ingenious manner, by certain cords, as we\ndraw the bucket up a well in Europe. A dish of their meat was a good\nmouthful, and a barrel of their liquor a reasonable draught. Their\nmutton yields to ours, but their beef is excellent, I have had a sirloin\nso large that I have been forced to make three bites of it; but this is\nrare. My servants were astonished to see me eat it, bones and all, as in\nour country we do the leg of a lark. Their geese and turkeys I usually\neat at a mouthful, and I must confess they far exceed ours. Of their\nsmaller fowl, I could take up twenty or thirty at the end of my knife.\n\nOne day his imperial majesty, being informed of my way of living,\ndesired that himself and his royal consort, with the young princes of\nthe blood of both sexes, might have the happiness, as he was pleased to\ncall it, of dining with me. They came accordingly, and I placed them in\nchairs of state upon my table, just over against me, with their guards\nabout them. Flimnap, the lord high treasurer, attended there likewise,\nwith his white staff; and I observed he often looked on me with a sour\ncountenance, which I would not seem to regard, but eat more than usual,\nin honor to my dear country, as well as to fill the court with\nadmiration. I have some private reasons to believe that this visit from\nhis majesty gave Flimnap an opportunity of doing me ill offices to his\nmaster. That minister had always been my secret enemy, though he\noutwardly caressed me more than was usual to the moroseness of his\nnature. He represented to the emperor the low condition of his treasury;\nthat he was forced to take up money at a great discount; that exchequer\nbills[33] would not circulate under nine per cent, below par; that I had\ncost his majesty above a million and a half of _sprugs_ (their greatest\ngold coin, about the bigness of a spangle); and, upon the whole, that it\nwould be advisable in the emperor to take the first fair occasion of\ndismissing me.\n\n[Illustration: \"THE HAPPINESS ... OF DINING WITH ME.\" P. 76.]\n\n[Illustration]\n\n[Illustration]\n\n\n\n\nCHAPTER VII.\n\n THE AUTHOR, BEING INFORMED OF A DESIGN TO ACCUSE HIM OF HIGH\n TREASON, MAKES HIS ESCAPE TO BLEFUSCU. HIS RECEPTION THERE.\n\n\nBefore I proceed to give an account of my leaving this kingdom, it may\nbe proper to inform the reader of a private intrigue which had been for\ntwo months forming against me.\n\nI had been hitherto all my life a stranger to courts, for which I was\nunqualified by the meanness of my condition. I had indeed heard and read\nenough of the dispositions of great princes and ministers, but never\nexpected to have found such terrible effects of them in so remote a\ncountry, governed, as I thought, by very different maxims from those in\nEurope.\n\nWhen I was just preparing to pay my attendance on the emperor of\nBlefuscu, a considerable person at court (to whom I had been very\nserviceable, at a time when he lay under the highest displeasure of his\nimperial majesty) came to my house very privately at night, in a close\nchair,[34] and without sending his name, desired admittance. The\nchairmen were dismissed; I put the chair, with his lordship in it, into\nmy coat-pocket; and, giving orders to a trusty servant to say I was\nindisposed and gone to sleep, I fastened the door of my house, placed\nthe chair on the table, according to my usual custom, and sat down by\nit. After the common salutations were over, observing his lordship's\ncountenance full of concern, and inquiring into the reason, he desired I\nwould hear him with patience, in a matter that highly concerned my honor\nand my life. His speech was to the following effect, for I took notes of\nit as soon as he left me:--\n\nYou are to know, said he, that several committees of council have been\nlately called in the most private manner on your account; and it is but\ntwo days since his majesty came to a full resolution.\n\nYou are very sensible that Skyrris Bolgolam (_galbet_ or high-admiral)\nhath been your mortal enemy almost ever since your arrival: his original\nreasons I know not; but his hatred is increased since your great success\nagainst Blefuscu, by which his glory, as admiral, is much obscured. This\nlord, in conjunction with Flimnap the high treasurer, whose enmity\nagainst you is notorious, Limtoc the general, Lalcon the chamberlain,\nand Balmuff the grand justiciary, have prepared articles of impeachment\nagainst you, for treason, and other capital crimes.\n\nThis preface made me so impatient, being conscious of my own merits and\ninnocence, that I was going to interrupt; when he entreated me to be\nsilent, and thus proceeded.\n\n[Illustration: \"HE DESIRED I WOULD HEAR HIM WITH PATIENCE.\" P. 80.]\n\nOut of gratitude for the favors you have done for me, I procured\ninformation of the whole proceedings, and a copy of the articles;\nwherein I venture my head for your service.\n\nARTICLES OF IMPEACHMENT AGAINST QUINBUS FLESTRIN, THE MAN-MOUNTAIN.\n\nARTICLE I.\n\n Whereas, by a statute made in the reign of his Imperial Majesty\n Calin Deffar Plune, it is enacted, That whoever shall lay hands\n upon the empress, or upon any of the royal children, shall be\n liable to the pains and penalties of high treason. Notwithstanding,\n the said Quinbus Flestrin, in open breach of the said law, under\n color of extinguishing the fire kindled in the apartment of his\n Majesty's most dear imperial consort, did maliciously, and\n traitorously, pull her by the arms, and lift her high in the air in\n both his hands, against the statute in that case provided, &c.,\n against the duty, &c.\n\n ARTICLE II.\n\n That the said Quinbus Flestrin, having brought the imperial fleet\n of Blefuscu into the royal port, and being afterwards commanded by\n his imperial majesty to seize all the other ships of the said\n empire of Blefuscu, and reduce that empire to a province, to be\n governed by a viceroy from hence, and to destroy and put to death,\n not only all the Big-endian exiles, but likewise all the people of\n that empire who would not immediately forsake the Big-endian\n heresy. He, the said Flestrin, like a false traitor against his\n most auspicious, serene, imperial majesty, did petition to be\n excused from the said service, upon pretence of unwillingness to\n force the consciences or destroy the liberties and lives of an\n innocent people.\n\n ARTICLE III.\n\n That, whereas certain ambassadors arrived from the court of\n Blefuscu, to sue for peace in his majesty's court; he, the said\n Flestrin, did, like a false traitor, aid, abet, comfort, and divert\n the said ambassadors, although he knew them to be servants t\n prince who was lately an open enemy to his imperial majesty, and in\n open war against his said majesty.\n\n ARTICLE IV.\n\n That the said Quinbus Flestrin, contrary to the duty of a faithful\n subject, is now preparing to make a voyage to the court and empire\n of Blefuscu, for which he hath received only verbal license from\n his imperial majesty; and under color of the said license, doth\n falsely and traitorously intend to take the said voyage, and\n thereby to aid, comfort, and abet the emperor of Blefuscu, so late\n an enemy, and in open war with his imperial majesty aforesaid.\n\nThere are some other articles, but these are the most important, of\nwhich I have read you an abstract.\n\nIn the several debates upon this impeachment, it must be confessed that\nhis majesty gave many marks of his great lenity, often urging the\nservices you had done him, and endeavoring to extenuate your crimes. The\ntreasurer and admiral insisted that you should be put to the most\npainful and ignominious death, by setting fire on your house at night;\nand the general was to attend, with twenty thousand men armed with\npoisoned arrows, to shoot you on the face and hands. Some of your\nservants were to have private orders to strew a poisonous juice on your\nshirts and sheets, which would soon make you tear your own flesh, and\ndie in the utmost torture. The general came into the same opinion; so\nthat for a long time there was a majority against you: but his majesty\nresolving, if possible, to spare your life, at last brought off the\nchamberlain.\n\nUpon this incident, Reldresal, principal secretary for private affairs,\nwho always approved himself your true friend, was commanded by the\nemperor to deliver his opinion, which he accordingly did; and therein\njustified the good thoughts you have of him. He allowed your crimes to\nbe great, but that still there was room for mercy, the most commendable\nvirtue in a prince, and for which his majesty was so justly celebrated.\nHe said, the friendship between you and him was so well known to the\nworld, that perhaps the most honorable board might think him partial;\nhowever, in obedience to the command he had received, he would freely\noffer his sentiments; that if his majesty, in consideration of your\nservices, and pursuant to his own merciful disposition, would please to\nspare your life, and only give orders to put out both your eyes, he\nhumbly conceived that, by this expedient, justice might in some measure\nbe satisfied, and all the world would applaud the lenity of the emperor,\nas well as the fair and generous proceedings of those who have the honor\nto be his counsellors: that the loss of your eyes would be no impediment\nto your bodily strength, by which you might still be useful to his\nmajesty: that blindness is an addition to courage, by concealing dangers\nfrom us: that the fear you had for your eyes was the greatest difficulty\nin bringing over the enemy's fleet: and it would be sufficient for you\nto see by the eyes of the ministers, since the greatest princes do no\nmore.\n\n[Illustration]\n\nThis proposal was received with the utmost disapprobation by the whole\nboard. Bolgolam, the admiral, could not preserve his temper, but rising\nup in fury, said he wondered how the secretary durst presume to give his\nopinion for preserving the life of a traitor: that the services you had\nperformed were, by all true reasons of state, the great aggravation of\nyour crimes: that you, who extinguished the fire in that unprincipled\nmanner, might at another time inundate and drown the whole palace; and\nthe same strength, which enabled you to bring over the enemy's fleet,\nmight serve, upon the first discontent, to carry it back: that he had\ngood reasons to think you were a Big-endian in your heart; and, as\ntreason begins in the heart, before it appears in overt acts, so he\naccused you as a traitor on that account, and therefore insisted you\nshould be put to death.\n\nThe treasurer was of the same opinion. He showed to what straits his\nmajesty's revenue was reduced, by the charge of maintaining you, which\nwould soon grow insupportable. That the secretary's expedient of putting\nout your eyes was so far from being a remedy against this evil, that it\nwould probably increase it, as is manifest from the common practice of\nblinding some sort of fowls, after which they fed the faster, and grew\nsooner fat. That his sacred majesty, and the council, who are your\njudges, were to their own consciences fully convinced of your guilt,\nwhich was a sufficient argument to condemn you to death without the\nformal proofs required by the strict letter of the law.\n\nBut his imperial majesty, fully determined against capital punishment,\nwas graciously pleaded to say, that since the council thought the loss\nof your eyes too easy a censure, some other might be inflicted\nhereafter. And your friend, the secretary, humbly desiring to be heard\nagain, in answer to what the treasurer had objected concerning the great\ncharge his majesty was at in maintaining you, said that his excellency,\nwho had the sole disposal of the emperor's revenue, might easily provide\nagainst that evil, by gradually lessening your establishment; by which,\nfor want of sufficient food, you would grow weak and faint, and lose\nyour appetite, and consume in a few months; neither would the stench of\nyour carcase be then so dangerous when it should become more than half\ndiminished; and, immediately upon your death, five or six thousand of\nhis majesty's subjects might in two or three days cut your flesh from\nyour bones, take it away by cart-loads, and bury it in distant parts, to\nprevent infection, leaving the skeleton as a monument of admiration to\nposterity.\n\nThus, by the great friendship of the secretary, the whole affair was\ncompromised. It was strictly enjoined that the project of starving you\nby degrees should be kept a secret, but the sentence of putting out your\neyes was entered on the books, none dissenting except Bolgolam, the\nadmiral, who, being a creature of the empress, was perpetually\ninstigated by her majesty to insist upon your death, she having borne\nperpetual malice against you, on account of that illegal method you took\nto remove her and her children the night of the fire.\n\nIn three days, your friend the secretary will be directed to come to\nyour house and read before you the articles of impeachment; and then to\nsignify the great lenity and favor of his majesty and council, whereby\nyou are only condemned to the loss of your eyes, which his majesty doth\nnot question you will gratefully and humbly submit to; and twenty of his\nmajesty's surgeons will attend, in order to see the operation well\nperformed, by discharging very sharp-pointed arrows into the balls of\nyour eyes as you lie on the ground.\n\nI leave to your prudence what measures you will take; and, to avoid\nsuspicion, I must immediately return, in as private a manner as I came.\n\nHis lordship did so, and I remained alone, under many doubts and\nperplexities of mind.\n\nIt was a custom, introduced by this prince and his ministry (very\ndifferent, as I have been assured, from the practices of former times),\nthat after the court had decreed any cruel execution either to gratify\nthe monarch's resentment or the malice of a favorite, the emperor always\nmade a speech to his whole council, expressing his great lenity and\ntenderness, as qualities known and confessed by all the world. This\nspeech was immediately published through the kingdom; nor did anything\nterrify the people so much as those encomiums on his majesty's mercy;\nbecause it was observed that, the more these praises were enlarged and\ninsisted on, the more inhuman was the punishment, and the sufferer more\ninnocent. Yet, as to myself, I must confess, having never been designed\nfor a courtier, either by my birth or education, I was so ill a judge of\nthings that I could not discover the lenity and favor of this sentence,\nbut conceived it (perhaps erroneously) rather to be rigorous than\ngentle, I sometimes thought of standing my trial; for although I could\nnot deny the facts alleged in the several articles, yet I hoped they\nwould admit of some extenuation. But having in my life perused many\nstate-trials, which I ever observed to terminate as the judges thought\nfit to direct, I durst not rely on so dangerous a decision, in so\ncritical a juncture, and against such powerful enemies. Once I was\nstrongly bent upon resistance, for, while I had liberty, the whole\nstrength of that empire could hardly subdue me, and I might easily with\nstones pelt the metropolis to pieces; but I soon rejected that project\nwith horror, by remembering the oath I had made to the emperor, the\nfavors I received from him, and the high title of _nardac_ he conferred\nupon me. Neither had I so soon learned the gratitude of courtiers as to\npersuade myself that his majesty's present seventies acquitted me of all\npast obligations.\n\nAt last I fixed upon a resolution, for which it is probable I may incur\nsome censure, and not unjustly; for I confess I owe the preserving mine\neyes, and consequently my liberty, to my own great rashness and want of\nexperience; because if I had then known the nature of princes and\nministers, which I have since observed in many other courts, and their\nmethods of treating criminals less obnoxious than myself, I should with\ngreat alacrity and readiness have submitted to so easy a punishment.\nBut, hurried on by the precipitancy of youth, and having his imperial\nmajesty's license to pay my attendance upon the emperor of Blefuscu, I\ntook this opportunity, before the three days were elapsed, to send a\nletter to my friend the secretary, signifying my resolution of setting\nout that morning for Blefuscu pursuant to the leave I had got; and,\nwithout waiting for an answer, I went to that side of the island where\nour fleet lay. I seized a large man-of-war, tied a cable to the prow,\nand lifting up the anchors, I stript myself, put my clothes (together\nwith my coverlet, which I carried under my arm) into the vessel, and\ndrawing it after me, between wading and swimming arrived at the royal\nport of Blefuscu, where the people had long expected me; they lent me\ntwo guides to direct me to the capital city, which is of the same name.\nI held them in my hands until I came within two hundred yards of the\ngate, and desired them to signify my arrival to one of the secretaries,\nand let him know I there waited his majesty's command. I had an answer\nin about an hour, that his majesty, attended by the royal family and\ngreat officers of the court, was coming out to receive me. I advanced a\nhundred yards. The emperor and his train alighted from their horses, the\nempress and ladies from their coaches, and I did not perceive they were\nin any fright or concern. I lay on the ground to kiss his majesty's and\nthe empress's hand.\n\n[Illustration]\n\nI told his majesty that I was come, according to my promise, and with\nthe license of the emperor, my master, to have the honor of seeing so\nmighty a monarch, and to offer him any service in my power consistent\nwith my duty to my own prince, not mentioning a word of my disgrace,\nbecause I had hitherto no regular information of it, and might suppose\nmyself wholly ignorant of any such design; neither could I reasonably\nconceive that the emperor would discover the secret while I was out of\nhis power, wherein however it soon appeared I was deceived.\n\nI shall not trouble the reader with the particular account of my\nreception at this court, which was suitable to the generosity of so\ngreat a prince; nor of the difficulties I was in for want of a house and\nbed, being forced to lie on the ground, wrapped up in my coverlet.\n\n[Illustration]\n\n\n\n\nCHAPTER VIII.\n\n THE AUTHOR, BY A LUCKY ACCIDENT, FINDS MEANS TO LEAVE BLEFUSCU, AND\n AFTER SOME DIFFICULTIES, RETURNS SAFE TO HIS NATIVE COUNTRY.\n\n\nThree days after my arrival, walking out of curiosity to the northeast\ncoast of the island, I observed, about half a league off in the sea,\nsomewhat that looked like a boat overturned. I pulled off my shoes and\nstockings, and wading two or three hundred yards, I found the object to\napproach nearer by force of the tide; and then plainly saw it to be a\nreal boat, which I supposed might by some tempest have been driven from\na ship: whereupon I returned immediately towards the city, and desired\nhis imperial majesty to lend me twenty of the tallest vessels he had\nleft after the loss of his fleet, and three thousand seamen under the\ncommand of his vice-admiral. This fleet sailed round, while I went back"
}
] | 11 |
rezon99/deocclusion-demo | https://github.com/rezon99/deocclusion-demo | 3bc8aab1981791f4f4467d12a432970e68f2d93a | c8da2e914a8106599fbd998af7f052117091fe97 | 161f126b456d4993a1535024918e63032afb9a2f | refs/heads/master | 2022-12-18T18:18:16.827964 | 2020-09-18T13:45:00 | 2020-09-18T13:45:00 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.711950957775116,
"alphanum_fraction": 0.7160367965698242,
"avg_line_length": 37.39215850830078,
"blob_id": "94bd1f1c7a1df0bd5b8d610b4a7e30be7f2508bb",
"content_id": "eb13f05273df0a4be9329fd2650ceaf93ce77738",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1958,
"license_type": "permissive",
"max_line_length": 245,
"num_lines": 51,
"path": "/README.md",
"repo_name": "rezon99/deocclusion-demo",
"src_encoding": "UTF-8",
"text": "## About\n\nThis repo is the image manipulation demo of \"[Self-Supervised Scene De-occlusion](https://github.com/XiaohangZhan/deocclusion)\".\n\n* Below is the demo.\n\n<img src=\"manipulation.gif\" width=500>\n\nFor further information, please contact [Xiaohang Zhan](https://xiaohangzhan.github.io/).\n\n## Usage\n\n1. Clone the repo, install dependencies.\n\n ```shell\n git clone https://github.com/XiaohangZhan/deocclusion-demo\n pip install PyQt5, opencv-python\n ```\n\n2. Run the demo.\n\n ```shell\n python main.py\n ```\n\n3. Interactions.\n\n * Click `Open` to open an image from `decomposition/image_*.png`.\n * Click `De-occlusion` to load decomposed components.\n * Use mouse to drag objects.\n * Mouse right click to change ordering or save the object.\n * Click `Show Objects` to show each object in order.\n * Click `Reset` to reset to the original status.\n * Click `Insert` and open an image from `materials` to insert it.\n * Push `Up` or `Down` arrow button to zoom out or zoom in the object.\n * Push `Left` or `Right` arrow button to rotate the object.\n * Click `Save As` to save the re-composed image.\n\n4. Try new images.\n\n* First of all, you should launch the jupyter notebooks [here](https://github.com/XiaohangZhan/deocclusion/blob/master/demos/), e.g., `demo_cocoa.ipynb`.\n\n* Second, run the notebook up to the last cell. In the last cell, change the `False` under `# save` to `True`. In this way, the completed objects as well as the background are saved following the topological order under `outputs/decomposition/`.\n\n* Third, copy the image as well as the folder containing the decomposed components under `decomposition` in this repo. Then enjoy yourself to re-compose the image.\n\n## Notice\n\nThere are still some bugs. Since I have no time to fix them, you are welcome to raise pull request to fix them. The bugs are below:\n\n* When you click `Open` or `Insert` to browse a folder, but choose cancel, the program crash.\n"
},
{
"alpha_fraction": 0.499620646238327,
"alphanum_fraction": 0.5394537448883057,
"avg_line_length": 31.14634132385254,
"blob_id": "cb3ed337102ba3db9a2edbb964bd3484cbe9d760",
"content_id": "0fdb8ae3ecdc750e2a48e2b32f81981f8275d389",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2636,
"license_type": "permissive",
"max_line_length": 112,
"num_lines": 82,
"path": "/utils.py",
"repo_name": "rezon99/deocclusion-demo",
"src_encoding": "UTF-8",
"text": "import cv2\nimport numpy as np\nfrom scipy import ndimage\n\nfrom PyQt5 import QtGui\n\ndef bbox_iou(b1, b2):\n '''\n b: (x1,y1,x2,y2)\n '''\n lx = max(b1[0], b2[0])\n rx = min(b1[2], b2[2])\n uy = max(b1[1], b2[1])\n dy = min(b1[3], b2[3])\n if rx <= lx or dy <= uy:\n return 0.\n else:\n interArea = (rx-lx)*(dy-uy)\n a1 = float((b1[2] - b1[0]) * (b1[3] - b1[1]))\n a2 = float((b2[2] - b2[0]) * (b2[3] - b2[1]))\n return interArea / (a1 + a2 - interArea)\n\ndef crop_padding(img, roi, pad_value):\n '''\n img: HxW or HxWxC np.ndarray\n roi: (x,y,w,h)\n pad_value: [b,g,r, (a)]\n '''\n need_squeeze = False\n if len(img.shape) == 2:\n img = img[:,:,np.newaxis]\n need_squeeze = True\n assert len(pad_value) == img.shape[2]\n x,y,w,h = roi\n x,y,w,h = int(x),int(y),int(w),int(h)\n H, W = img.shape[:2]\n output = np.tile(np.array(pad_value), (h, w, 1)).astype(img.dtype)\n if bbox_iou((x,y,x+w,y+h), (0,0,W,H)) > 0:\n output[max(-y,0):min(H-y,h), max(-x,0):min(W-x,w), :] = img[max(y,0):min(y+h,H), max(x,0):min(x+w,W), :]\n if need_squeeze:\n output = np.squeeze(output)\n return output\n\ndef resize_with_center(img, center, ratio):\n cx, cy = center\n h, w = img.shape[:2]\n nh, nw = int(h * ratio), int(w * ratio)\n center_move_x = cx * (ratio - 1)\n center_move_y = cy * (ratio - 1)\n newimg = cv2.resize(img, (nw, nh), interpolation=cv2.INTER_LINEAR)\n #newimg[:,:,3][newimg[:,:,3] < 255] = 0\n bbox = [center_move_x, center_move_y, w, h]\n newimg = crop_padding(newimg, bbox, pad_value=tuple([0] * img.shape[2]))\n return newimg\n\ndef rotate_with_center(img, center, degree):\n cx, cy = map(int, center)\n h, w, ch = img.shape\n bbox_centered = [0, 0, 2 * cx, 2 * cy]\n img_c = crop_padding(img, bbox_centered, pad_value=tuple([0] * ch))\n img_r = ndimage.rotate(img_c, degree, reshape=False)\n bbox_recover = [0, 0, w, h]\n return crop_padding(img_r, bbox_recover, pad_value=tuple([0] * ch))\n\ndef mask_to_bbox(mask):\n mask = (mask == 1)\n if np.all(~mask):\n return [0, 0, 0, 0]\n assert len(mask.shape) == 2\n rows = np.any(mask, axis=1)\n cols = np.any(mask, axis=0)\n rmin, rmax = np.where(rows)[0][[0, -1]]\n cmin, cmax = np.where(cols)[0][[0, -1]]\n return [cmin.item(), rmin.item(), cmax.item() + 1 - cmin.item(), rmax.item() + 1 - rmin.item()] # xywh\n\ndef compute_center(img):\n assert img.shape[2] == 4\n mask = img[:,:,3] > 128\n bbox = mask_to_bbox(mask)\n center_x = bbox[0] + bbox[2] // 2\n center_y = bbox[1] + bbox[3] // 2\n return [center_x, center_y]\n"
},
{
"alpha_fraction": 0.7400000095367432,
"alphanum_fraction": 0.7400000095367432,
"avg_line_length": 15.666666984558105,
"blob_id": "3847bd57ef7dc5d3a31f8c458d8cc3353883ac9f",
"content_id": "fbb663d7bf92852dd56cb5e0649d0d1801769214",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 50,
"license_type": "permissive",
"max_line_length": 20,
"num_lines": 3,
"path": "/source.sh",
"repo_name": "rezon99/deocclusion-demo",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\nsource ~/.bashrc\nsource activate pyqt\n"
},
{
"alpha_fraction": 0.6103833317756653,
"alphanum_fraction": 0.6162057518959045,
"avg_line_length": 38.132911682128906,
"blob_id": "609522edab5cad5b16b14c088edd5f83f358ca9c",
"content_id": "28f6a4deaa92b235c8307c957d6c2ec23a867f60",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6183,
"license_type": "permissive",
"max_line_length": 135,
"num_lines": 158,
"path": "/main.py",
"repo_name": "rezon99/deocclusion-demo",
"src_encoding": "UTF-8",
"text": "import sys\nimport os\nimport time\nfrom glob import glob\nimport cv2\n\nfrom PIL import Image\nimport numpy as np\n\nfrom PyQt5.QtWidgets import (QAction, QApplication, QDockWidget, QFileDialog, QMainWindow, QLabel, QDesktopWidget, QListWidget)\nfrom PyQt5.QtGui import (QImage, QImageWriter, QKeySequence, QPixmap)\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtTest import QTest\n\nimport deocc_app\n\nclass MainWindow(QMainWindow):\n\n def __init__(self):\n super(MainWindow, self).__init__()\n\n self.debug = False\n screen = QDesktopWidget().screenGeometry()\n #self.swidth, self.sheight = screen.width(), screen.height()\n self.swidth, self.sheight = 800, 560\n self.setGeometry(0, 0, self.swidth, self.sheight)\n\n # UI\n self.filename = None\n self.addMainApp()\n\n # log\n if self.debug:\n logDockWidget =QDockWidget('Log', self)\n logDockWidget.setObjectName('LogDockWidget')\n logDockWidget.setAllowedAreas(Qt.LeftDockWidgetArea|Qt.RightDockWidgetArea)\n self.listWidget = QListWidget()\n logDockWidget.setWidget(self.listWidget)\n self.addDockWidget(Qt.RightDockWidgetArea, logDockWidget)\n\n # action\n fileOpenAction = self.createAction(\n '&Open...', slot=self.fileOpen, shortcut=QKeySequence.Open,\n tip='open an existing image file')\n #fileSaveAction = self.createAction(\n # '&Save...', slot=self.fileSave, shortcut=QKeySequence.Save,\n # tip='save image file')\n fileSaveAsAction = self.createAction(\n 'Save &As...', slot=self.fileSaveAs, shortcut=QKeySequence.SaveAs,\n tip='save image file using a new name')\n fileQuitAction = self.createAction(\n '&Quit...', slot=self.close, shortcut='Ctrl + Q',\n tip='Close the Application')\n\n editDeoccAction = self.createAction(\n 'Deocclusion', slot=self.editDeocc, shortcut='Ctrl+E', tip='perform de-occlusion')\n editResetAction = self.createAction(\n 'Reset', slot=self.mainApp.reset, shortcut='Ctrl+R', tip='reset image')\n\n # menu\n self.fileMenu = self.menuBar().addMenu('&File')\n self.fileMenu.addAction(fileOpenAction)\n #self.fileMenu.addAction(fileSaveAction)\n self.fileMenu.addAction(fileSaveAsAction)\n self.fileMenu.addSeparator()\n self.fileMenu.addAction(fileQuitAction)\n\n self.editMenu = self.menuBar().addMenu('&Edit')\n self.editMenu.addAction(editDeoccAction)\n self.editMenu.addAction(editResetAction)\n\n self.setWindowTitle('De-Occlusion')\n #self.showMaximized()\n self.show()\n\n def addMainApp(self):\n self.mainApp = deocc_app.Application(self, (self.swidth, self.sheight), self.debug)\n self.setCentralWidget(self.mainApp)\n self.keyPressEvent = self.mainApp.keyPressEvent\n \n def createAction(self, text, slot=None, shortcut=None, tip=None, checkable=False, signal='triggered'):\n action = QAction(text, self)\n if shortcut is not None:\n action.setShortcut(shortcut)\n if tip is not None:\n action.setToolTip(tip)\n action.setStatusTip(tip)\n if slot is not None:\n action.triggered.connect(slot)\n if checkable:\n action.setCheckable(True)\n return action\n\n def editDeocc(self):\n file_dir = self.filename[:-4]\n obj_fns = sorted(glob(\"{}/obj_*.png\".format(file_dir)))[::-1]\n #obj_list = os.path.join(file_dir, \"objects.txt\")\n #with open(obj_list, 'r') as f:\n # lines = f.readlines()\n #obj_fns = [os.path.join(file_dir, l.strip()) for l in lines]\n bkg = np.array(Image.open(os.path.join(file_dir, \"bkg.png\")))\n objects = [np.array(Image.open(fn)) for fn in obj_fns]\n self.mainApp.init_components(bkg, objects)\n\n def insertObject(self):\n filename, _ = QFileDialog.getOpenFileName(self, 'Select an object: ', '.', filter='*.png')\n if filename is None:\n return\n new_object = np.array(Image.open(filename)) # RGBA\n self.mainApp.insert_object(new_object)\n\n def fileOpen(self):\n self.filename, _ = QFileDialog.getOpenFileName(self, 'Select an image file: ', filter='*.jpg *.png')\n if self.filename is None or len(self.filename) == 0:\n return\n image_ori = np.array(Image.open(self.filename).convert('RGB'))\n self.mainApp.init_image(image_ori)\n\n def fileSave(self):\n if self.mainApp.canvas_show.isNull():\n return\n if self.filename is None:\n self.fileSaveAs()\n else:\n self.mainApp.canvas_show.save(self.filename, None)\n\n def fileSaveAs(self):\n if self.mainApp.canvas_show.isNull():\n return\n fname = self.filename if self.filename else '.'\n formats = ['{0}'.format(str(format).lower()) for format in QImageWriter.supportedImageFormats()]\n formats = ['*.{0}'.format(format[2:5]) for format in formats]\n fname, _ = QFileDialog.getSaveFileName(self, 'De-occlusion - Save Image', fname, 'Image files ({0})'.format(' '.join(formats)))\n if fname:\n if '.' not in fname:\n fname += '.png'\n self.filename = fname\n self.fileSave()\n\n def objectSaveAs(self, obj):\n formats = ['{0}'.format(str(format).lower()) for format in QImageWriter.supportedImageFormats()]\n formats = ['*.{0}'.format(format[2:5]) for format in formats]\n fname, _ = QFileDialog.getSaveFileName(self, 'De-occlusion - Save object', '.', 'Image files ({0})'.format(' '.join(formats)))\n if fname:\n if '.' not in fname:\n fname += '.png'\n obj = np.concatenate([obj[:,:,:3][:,:,::-1], obj[:,:,3:4]], axis=2)\n cv2.imwrite(fname, obj)\n\n def updateStatus(self, message):\n self.statusBar().showMessage(message, 5000)\n self.listWidget.addItem(message)\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n app.setApplicationName(\"De-Occlusion\")\n form = MainWindow()\n sys.exit(app.exec_())\n"
},
{
"alpha_fraction": 0.5661705732345581,
"alphanum_fraction": 0.5799328088760376,
"avg_line_length": 38.17868423461914,
"blob_id": "d89e70747a8304d10f26daa649d2db6a2a918eee",
"content_id": "86759170186dc98885cb5ba51042173eda516d4e",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 12498,
"license_type": "permissive",
"max_line_length": 127,
"num_lines": 319,
"path": "/deocc_app.py",
"repo_name": "rezon99/deocclusion-demo",
"src_encoding": "UTF-8",
"text": "import numpy as np\nfrom PyQt5.QtWidgets import (QAction, QLabel, QWidget, QVBoxLayout, QHBoxLayout, QMenu, QPushButton, QGridLayout, QApplication)\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import (QImage, QPixmap)\nfrom PyQt5.QtTest import QTest\n\nimport utils\n\nimport time\n\nclass Application(QWidget):\n\n def __init__(self, parent, dims, debug=False):\n super().__init__(parent)\n swidth, sheight = dims\n self.main_width, self.main_height = swidth * 0.9, sheight * 0.9\n self.debug = debug\n\n self.imageLabel = QLabel(self)\n\n # buttons\n btnsWidth = 120\n self.btnGrid = QGridLayout()\n self.openBtn = QPushButton(\"Open\")\n self.openBtn.setFixedWidth(btnsWidth)\n self.openBtn.clicked.connect(self.window().fileOpen)\n self.deoccBtn = QPushButton(\"De-occlusion\")\n self.deoccBtn.setFixedWidth(btnsWidth)\n self.deoccBtn.clicked.connect(self.window().editDeocc)\n self.showBtn = QPushButton(\"Show Objects\")\n self.showBtn.setFixedWidth(btnsWidth)\n self.showBtn.clicked.connect(self.paste_isolated)\n self.insertBtn = QPushButton(\"Insert\")\n self.insertBtn.setFixedWidth(btnsWidth)\n self.insertBtn.clicked.connect(self.window().insertObject)\n self.resetBtn = QPushButton(\"Reset\")\n self.resetBtn.setFixedWidth(btnsWidth)\n self.resetBtn.clicked.connect(self.reset)\n self.saveasBtn = QPushButton(\"Save As\")\n self.saveasBtn.setFixedWidth(btnsWidth)\n self.saveasBtn.clicked.connect(self.window().fileSaveAs)\n self.btnGrid.addWidget(self.openBtn, 0, 0, Qt.AlignRight)\n self.btnGrid.addWidget(self.deoccBtn, 1, 0, Qt.AlignRight)\n self.btnGrid.addWidget(self.showBtn, 2, 0, Qt.AlignRight)\n self.btnGrid.addWidget(self.resetBtn, 3, 0, Qt.AlignRight)\n self.btnGrid.addWidget(self.insertBtn, 4, 0, Qt.AlignRight)\n self.btnGrid.addWidget(self.saveasBtn, 5, 0, Qt.AlignRight)\n\n picLayout = QHBoxLayout()\n picLayout.addWidget(self.imageLabel, Qt.AlignCenter)\n picLayout.addLayout(self.btnGrid, Qt.AlignLeft)\n self.setLayout(picLayout)\n self.imageLabel.mousePressEvent = self.mousePressEventPic\n self.imageLabel.mouseMoveEvent = self.mouseMoveEventPic\n self.imageLabel.mouseReleaseEvent = self.mouseReleaseEventPic\n self.imageLabel.contextMenuEvent = self.contextMenuEventPic\n\n #self.imageLabel.setMouseTracking(True)\n\n # \n self.canvas = None\n self.mask = None\n self.canvas_show = QImage()\n\n # status\n self.deocc_flag = False\n\n def init_image(self, image_ori):\n self.deocc_flag = False\n self.image_ori = image_ori\n self.image_height = self.image_ori.shape[0]\n self.image_width = self.image_ori.shape[1]\n self.canvas = self.image_ori.copy()\n self.mask = np.zeros((self.image_height, self.image_width), dtype=np.int)\n self.showCanvas()\n QApplication.setOverrideCursor(Qt.ArrowCursor)\n\n def reset(self):\n self.objects = [o.copy() for o in self.objects_ori]\n self.shift = [[0, 0] for o in self.objects_ori]\n self.scale = [1. for o in self.objects_ori]\n self.degree = [0. for o in self.objects_ori]\n self.center = [utils.compute_center(o) for o in self.objects_ori]\n self.order = np.arange(len(self.objects))\n self.paste_all()\n\n def paste_isolated(self):\n self.paste(self.bkg)\n QTest.qWait(1000)\n for i in range(len(self.objects)):\n ind = self.order[i]\n self.paste(self.bkg)\n self.paste(self.objects[ind], ind + 1)\n self.showCanvas()\n QTest.qWait(1000)\n self.paste_all()\n\n def init_components(self, bkg, objs):\n self.bkg = bkg\n self.objects_ori = objs\n self.deocc_flag = True\n QApplication.setOverrideCursor(Qt.WaitCursor)\n QTest.qWait(500)\n self.reset()\n QApplication.setOverrideCursor(Qt.OpenHandCursor)\n\n def pad(self, obj):\n h, w = obj.shape[:2]\n obj_canvas = np.zeros((self.image_height, self.image_width, 4), dtype=np.uint8)\n offy = (self.image_height - h) // 2\n offx = (self.image_width - w) // 2\n obj_canvas[offy : offy + h, offx : offx + w, :] = obj\n return obj_canvas\n\n def insert_object(self, obj):\n if not self.deocc_flag:\n return\n obj = self.pad(obj)\n self.objects_ori.append(obj)\n self.objects.append(obj.copy())\n self.shift.append([0, 0])\n self.scale.append(1.)\n self.degree.append(0.)\n self.center.append(utils.compute_center(obj))\n self.order = np.array(self.order.tolist() + [len(self.objects) - 1])\n self.paste_all()\n\n def paste_all(self):\n self.paste(self.bkg, 0)\n for i in range(len(self.objects)):\n ind = self.order[i]\n self.paste(self.objects[ind], ind + 1) # ind=0 is background\n self.showCanvas()\n\n def getObject(self, coord):\n x, y = coord\n x /= self.ratio\n y /= self.ratio\n return self.mask[int(y), int(x)]\n\n def mousePressEventPic(self, event):\n x, y = event.pos().x(), event.pos().y()\n if event.button() == Qt.LeftButton:\n QApplication.setOverrideCursor(Qt.ClosedHandCursor)\n if not self.deocc_flag:\n return\n if x >= self.pixmap_scope[0] or y >= self.pixmap_scope[1]:\n return\n this_obj = self.getObject((x, y))\n if self.debug:\n self.window().updateStatus(\"left: {}, {}, {}\".format(x, y, this_obj))\n self.this_obj = this_obj\n self.this_pos = (x, y)\n\n def mouseMoveEventPic(self, event):\n x, y = event.pos().x(), event.pos().y()\n if event.buttons() == Qt.LeftButton:\n if not self.deocc_flag or self.this_obj == 0:\n return\n QApplication.setOverrideCursor(Qt.ClosedHandCursor)\n move_x = (x - self.this_pos[0]) / self.ratio\n move_y = (y - self.this_pos[1]) / self.ratio\n self.this_pos = (x, y)\n self.shift[self.this_obj - 1][0] += move_x\n self.shift[self.this_obj - 1][1] += move_y\n self.center[self.this_obj - 1][0] += move_x\n self.center[self.this_obj - 1][1] += move_y\n self.manipulate()\n #elif event.buttons() == Qt.NoButton:\n # if x >= self.pixmap_scope[0] or y >= self.pixmap_scope[1]:\n # QApplication.restoreOverrideCursor()\n # else:\n # tmp_obj = self.getObject((x, y))\n # if tmp_obj == 0:\n # QApplication.restoreOverrideCursor()\n # else:\n # QApplication.setOverrideCursor(Qt.OpenHandCursor)\n\n def mouseReleaseEventPic(self, event):\n QApplication.setOverrideCursor(Qt.OpenHandCursor)\n\n def objectForward(self):\n pos = np.where(self.order == self.this_obj - 1)[0].item()\n if pos < self.order.shape[0] - 1:\n tmp = self.order[pos + 1]\n self.order[pos + 1] = self.this_obj - 1\n self.order[pos] = tmp\n self.paste_all()\n\n def objectBackward(self):\n pos = np.where(self.order == self.this_obj - 1)[0].item()\n if pos > 0:\n tmp = self.order[pos - 1]\n self.order[pos - 1] = self.this_obj - 1\n self.order[pos] = tmp\n self.paste_all()\n \n def objectFront(self):\n pos = np.where(self.order == self.this_obj - 1)[0].item()\n if pos < self.order.shape[0] - 1:\n self.order = np.concatenate(\n [self.order[:pos], self.order[pos + 1:],\n np.array([self.this_obj - 1], dtype=np.int64)])\n self.paste_all()\n\n def objectBottom(self):\n pos = np.where(self.order == self.this_obj - 1)[0].item()\n if pos > 0:\n self.order = np.concatenate(\n [np.array([self.this_obj - 1], dtype=np.int64),\n self.order[:pos], self.order[pos + 1:]])\n self.paste_all()\n\n def objectSave(self):\n obj = self.objects[self.this_obj - 1]\n crop_obj = utils.crop_padding(\n obj, utils.mask_to_bbox(obj[:,:,3]), pad_value=(0,0,0,0))\n self.window().objectSaveAs(crop_obj)\n\n def contextMenuEventPic(self, event):\n if not self.deocc_flag:\n return\n x, y = event.pos().x(), event.pos().y()\n this_obj = self.getObject((x, y))\n if self.debug:\n self.window().updateStatus(\"right: {}, {}, {}\".format(x, y, this_obj))\n if this_obj == 0:\n return\n self.this_obj = this_obj\n\n menu = QMenu()\n fwAction = QAction(\"Bring forward\", self)\n fwAction.triggered.connect(self.objectForward)\n bwAction = QAction(\"Send backward\", self)\n bwAction.triggered.connect(self.objectBackward)\n frtAction = QAction(\"Bring to front\", self)\n frtAction.triggered.connect(self.objectFront)\n btmAction = QAction(\"Send to bottom\", self)\n btmAction.triggered.connect(self.objectBottom)\n saveAction = QAction(\"Save object\", self)\n saveAction.triggered.connect(self.objectSave)\n\n menu.addAction(fwAction)\n menu.addAction(bwAction)\n menu.addAction(frtAction)\n menu.addAction(btmAction)\n menu.addAction(saveAction)\n menu.exec_(self.mapToGlobal(event.pos()))\n \n def moveObject(self, image, move_x, move_y):\n bbox = [-move_x, -move_y, image.shape[1], image.shape[0]]\n return utils.crop_padding(image, bbox, pad_value=(0,0,0,0))\n\n def resizeObject(self, image, ratio):\n if ratio == 1:\n return image\n else:\n return utils.resize_with_center(image, self.center[self.this_obj - 1], ratio)\n\n def rotateObject(self, image, degree):\n if degree == 0:\n return image\n else:\n return utils.rotate_with_center(image, self.center[self.this_obj - 1], degree)\n\n def keyPressEvent(self, event):\n if event.key() == Qt.Key_Up and self.scale[self.this_obj - 1] > 0.2:\n self.scale[self.this_obj - 1] -= 0.05\n elif event.key() == Qt.Key_Down:\n self.scale[self.this_obj - 1] += 0.05\n elif event.key() == Qt.Key_Left:\n self.degree[self.this_obj - 1] += 3\n elif event.key() == Qt.Key_Right:\n self.degree[self.this_obj - 1] -= 3\n else:\n return\n self.manipulate()\n\n def manipulate(self):\n # move\n self.objects[self.this_obj - 1] = self.moveObject(\n self.objects_ori[self.this_obj - 1],\n self.shift[self.this_obj - 1][0], self.shift[self.this_obj - 1][1])\n # resize\n self.objects[self.this_obj - 1] = self.resizeObject(\n self.objects[self.this_obj - 1], self.scale[self.this_obj - 1])\n # rotate\n self.objects[self.this_obj - 1] = self.rotateObject(\n self.objects[self.this_obj - 1], self.degree[self.this_obj - 1])\n\n self.paste_all()\n\n def paste(self, image, ind=None):\n if image.shape[2] == 4:\n alpha = image[:,:,3:4].astype(np.float32) / 255\n region = np.where(image[:,:,3] > 0)\n self.canvas[region[0], region[1], :] = \\\n self.canvas[region[0], region[1], :] * (1 - alpha[region[0], region[1], :]) + \\\n image[region[0], region[1], :3] * alpha[region[0], region[1], :]\n self.mask[region[0], region[1]] = ind\n else:\n self.canvas[...] = image.copy()\n self.mask.fill(0)\n\n def showCanvas(self):\n if self.canvas is not None:\n self.canvas_show = QImage(\n self.canvas.data, self.image_width, self.image_height,\n 3 * self.image_width, QImage.Format_RGB888)\n else:\n self.canvas_show = QImage()\n pixmap = QPixmap.fromImage(self.canvas_show)\n #pixmap = pixmap.scaled(self.main_width, self.main_height, Qt.KeepAspectRatio)\n self.pixmap_scope = (pixmap.size().width(), pixmap.size().height())\n self.ratio = pixmap.size().height() / float(self.image_height)\n self.imageLabel.setFixedHeight(pixmap.size().height())\n self.imageLabel.setFixedWidth(pixmap.size().width())\n self.imageLabel.setPixmap(pixmap)\n self.imageLabel.show()\n"
}
] | 5 |
RabidGuy/tbn | https://github.com/RabidGuy/tbn | 678947051a04627f40953ac8c0a3d0fcfda8a01e | 005abdadcaeccaf4a2737dc5c1b76870165bfa1a | 49aa5da7edb41445ef05db18ffba01a6ad0e4f60 | refs/heads/master | 2020-06-17T08:42:05.779863 | 2019-08-26T15:22:56 | 2019-08-26T15:22:56 | 195,866,220 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5820895433425903,
"alphanum_fraction": 0.5820895433425903,
"avg_line_length": 15.75,
"blob_id": "c42030eebe853f02a670080a72f594014ad701f8",
"content_id": "3c7873eb23dff31765489b9df607c2db4c77d82a",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 134,
"license_type": "permissive",
"max_line_length": 47,
"num_lines": 8,
"path": "/tbn/member.py",
"repo_name": "RabidGuy/tbn",
"src_encoding": "UTF-8",
"text": "import binarytree\n\n\nclass Member:\n\n def __init__(self):\n super().__init__()\n self._genome = binarytree.GeneticTree()\n"
},
{
"alpha_fraction": 0.4805825352668762,
"alphanum_fraction": 0.4920797049999237,
"avg_line_length": 27.992591857910156,
"blob_id": "47dd8097022538ac3e9eda3e500bbf930862dded",
"content_id": "3e4563642f30c6dbf165a678d29433eb5c9d3ac4",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3914,
"license_type": "permissive",
"max_line_length": 69,
"num_lines": 135,
"path": "/tbn/binarytree.py",
"repo_name": "RabidGuy/tbn",
"src_encoding": "UTF-8",
"text": "import math\nimport random\n\nfrom tbn import constants\n\n\nclass BinaryTree:\n\n def __init__(self, tree=None):\n super().__init__()\n self._tree = tree if tree else []\n\n def left(self, n):\n \"\"\"Left-child of node n\"\"\"\n # When n is large enough that l of n would be out of bounds,\n # return -1.\n assert n >= 0\n l = 2 * (n + 1) - 1\n if l >= len(self):\n return -1\n else:\n return l\n\n def right(self, n):\n \"\"\"Right-child of node n\"\"\"\n # When n is large enough that r of n would be out of bounds,\n # return -1.\n assert n >= 0\n r = 2 * (n + 1)\n if r >= len(self):\n return -1\n else:\n return r\n\n def parent(self, n):\n \"\"\"Parent of node n\"\"\"\n # When n equals zero, there is no parent as zero is root.\n # Returns -1.\n\n assert n >= 0\n return math.floor((n + 1) / 2) - 1\n\n def flatten(self):\n return self._flatten(0)\n\n def _flatten(self, n):\n if not len(self):\n return []\n content = [self._tree[n]]\n left = self.left(n)\n if left > 0 and self[left] is not None:\n flat_left = self._flatten(left)\n flat_left.extend(content)\n content = flat_left\n right = self.right(n)\n if right > 0 and self[right] is not None:\n flat_right = self._flatten(right)\n content.extend(flat_right)\n return content\n\n def __getitem__(self, n):\n # Able to index off right end; returns None.\n # Not able to index off left end.\n assert n >= 0\n if n >= len(self):\n return None\n else:\n return self._tree[n]\n\n def __len__(self):\n return len(self._tree)\n\n\nclass GeneticTree(BinaryTree):\n\n def __init__(self, tree=None):\n super().__init__(tree)\n\n def breed(self, mate):\n g1 = self._tree\n g2 = mate._tree\n\n g3 = self._merge(g1, g2)\n g4 = self._mutate(g3)\n\n return GeneticTree(g4)\n\n def _merge(g1, g2, choicefn=random.choice):\n genome = []\n length = max(len(g1), len(g2))\n for n in range(length):\n genome.append(choicefn([g1[n], g2[n]]))\n # Remove trailing Nones.\n while genome[-1] is None:\n del genome[-1]\n return genome\n\n def _mutate(genome, randomfn=random.random):\n # randomfn exposed for testability.\n mutant = []\n n = 0\n while n < len(g1):\n if randomfn() < constants.chancer_pointer_deviation:\n r = randomfn()\n d = 0\n # Take the first row that is greater than r.\n for row in constants.pointer_deviation_table:\n if r < row[0]:\n d = row[1]\n break\n # Don't go past left end.\n if (n + d) < 0:\n n = 0\n # Do go past right end.\n elif (n + d) >= len(genome):\n # Don't return an empty mutant.\n if len(mutant) < 1:\n continue\n # Done copying.\n else:\n return mutant\n # Adjust read index.\n else:\n n += d\n mutant.append(genome[n])\n n += 1\n # XXX Add transcription errors. A transcription error causes\n # the wrong gene to be written into the mutant without\n # deviating the read index. The result of a transcription\n # error may need to be determined by the genes themselves\n # as the binary tree does not know anything about the\n # data it stores. This can be done immediately before\n # writing to mutant or as a second pass once mutant's\n # final length has been determined.\n return mutant\n"
},
{
"alpha_fraction": 0.6428571343421936,
"alphanum_fraction": 0.6428571343421936,
"avg_line_length": 7.400000095367432,
"blob_id": "61175e7490db50612f530b2980fda8c7a691ed1a",
"content_id": "53e39b988bbbfc1830bfae11f36bc40533867931",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 42,
"license_type": "permissive",
"max_line_length": 19,
"num_lines": 5,
"path": "/tbn/app.py",
"repo_name": "RabidGuy/tbn",
"src_encoding": "UTF-8",
"text": "import cmd\n\n\nclass App(cmd.Cmd):\n pass\n"
},
{
"alpha_fraction": 0.573306143283844,
"alphanum_fraction": 0.588715136051178,
"avg_line_length": 27.108280181884766,
"blob_id": "af22c0eb622b66211b5c0742bdd2749c97c37b06",
"content_id": "c2173a691b4eb551d5ddf91af6a44831b51b2a55",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4413,
"license_type": "permissive",
"max_line_length": 84,
"num_lines": 157,
"path": "/tests/unit/test_binarytree.py",
"repo_name": "RabidGuy/tbn",
"src_encoding": "UTF-8",
"text": "import unittest\nimport unittest.mock as mock\n\nfrom tbn.binarytree import BinaryTree, GeneticTree\n\n\nclass TestBinaryTree(unittest.TestCase):\n\n # TEST __init__\n ###\n\n def test_init_with_no_argument_sets_tree_to_empty_list(self):\n t = BinaryTree()\n self.assertEqual(t._tree, [])\n\n def test_init_with_argument_sets_tree_to_argument(self):\n a = [1, 2, 3]\n t = BinaryTree(a)\n self.assertIs(t._tree, a)\n\n # TEST left\n ###\n\n def test_left_returns_correct_child(self):\n t = BinaryTree([4, 5, 6])\n self.assertEqual(t.left(0), 1)\n\n def test_left_out_of_bounds_returns_negative_one(self):\n t = BinaryTree()\n self.assertEqual(t.left(0), -1)\n\n def test_left_raises_assertionerror_when_argument_below_zero(self):\n t = BinaryTree()\n with self.assertRaises(AssertionError):\n t.left(-1)\n\n # TEST right\n ###\n\n def test_right_returns_correct_child(self):\n t = BinaryTree([4, 5, 6])\n self.assertEqual(t.right(0), 2)\n\n def test_right_out_of_bounds_returns_negative_one(self):\n t = BinaryTree()\n self.assertEqual(t.right(0), -1)\n\n def test_right_raises_assertionerror_when_argument_below_zero(self):\n t = BinaryTree()\n with self.assertRaises(AssertionError):\n t.right(-1)\n\n # TEST parent\n ###\n\n def test_parent_returns_correct_parent(self):\n t = BinaryTree([4, 5, 6, 7])\n self.assertEqual(t.parent(3), 1)\n\n def test_parent_returns_negative_one_as_parent_of_root(self):\n t = BinaryTree()\n self.assertEqual(t.parent(0), -1)\n\n def test_parent_raises_assertionerror_when_argument_below_zero(self):\n t = BinaryTree()\n with self.assertRaises(AssertionError):\n t.parent(-1)\n\n # TEST flatten\n ###\n\n def test_flatten_returns_proper_sequence(self):\n t = BinaryTree([4, 2, 6, 1, 3, 5, 7])\n ft = [1, 2, 3, 4, 5, 6, 7]\n self.assertEqual(t.flatten(), ft)\n\n def test_flatten_returns_empty_sequence_when_empty(self):\n t = BinaryTree()\n self.assertEqual(t.flatten(), [])\n\n def test_flatten_ignores_pruned_branches(self):\n t = BinaryTree([4, None, 6, 1, 3, 5, 7])\n ft = [4, 5, 6, 7]\n self.assertEqual(t.flatten(), ft)\n\n # TEST __getitem__ => binarytree[n]\n ###\n\n def test_getitem_returns_correct_element(self):\n t = BinaryTree([4, 5, 6])\n self.assertEqual(t[1], 5)\n\n def test_getitem_returns_none_when_index_too_high(self):\n t = BinaryTree()\n self.assertIsNone(t[0])\n\n def test_getitem_raises_assertionerror_when_argument_below_zero(self):\n t = BinaryTree()\n with self.assertRaises(AssertionError):\n t[-1]\n\n # TEST __len__ => len(binarytree)\n ###\n\n def test_len_returns_correct_value(self):\n t = BinaryTree([4, 5, 6])\n self.assertEqual(len(t), 3)\n\n\nclass TestGeneticTree(unittest.TestCase):\n\n def create_mock_random_dot_random(self, return_value):\n def fn(*args, **kwargs):\n return return_value\n return fn\n\n def create_mock_random_dot_choice(self):\n def fn(seq, *args, **kwargs):\n return seq[0]\n return fn\n\n def setUp(self):\n self.tree = GeneticTree(['1', '2', '3'])\n self.mate = GeneticTree(['a', 'b', 'c'])\n\n def test_breed(self):\n # Expected behavior:\n # * accept argument: mate\n # * call _merge with own tree and tree of mate\n # * call _mutate with result of _merge\n # * return result of _mutate\n pass\n\n def test_underscore_merge_calls_random_dot_choice_with_correct_gene_pairs(self):\n expected_gene_pairs = [mock.call([self.tree[i], self.mate[i]])\n for i in range(len(self.tree))]\n\n @mock.Mock\n def mock_choice(seq, *args, **kwargs):\n return seq[0]\n # mock_choice = mock.Mock(wrap=mock_choice)\n\n merged_tree = self.tree._merge(self.mate._tree, choicefn=mock_choice)\n\n mock_choice.assert_has_calls(expected_gene_pairs)\n\n def test_underscore_merge_performs_merge(self):\n pass\n # XXX Write test.\n\n def test_underscore_merge_handles_genomes_of_different_lengths(self):\n pass\n # XXX Write test.\n\n def test_underscore_merge_removes_trailing_nones(self):\n pass\n # XXX Write test.\n"
},
{
"alpha_fraction": 0.5536105036735535,
"alphanum_fraction": 0.6345732808113098,
"avg_line_length": 25.882352828979492,
"blob_id": "90bb4a60de96731d44823756a238bd187f33a423",
"content_id": "fb1727893a6b9592ee452f3de1086d6f4f7d93e7",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 457,
"license_type": "permissive",
"max_line_length": 68,
"num_lines": 17,
"path": "/tbn/constants.py",
"repo_name": "RabidGuy/tbn",
"src_encoding": "UTF-8",
"text": "# Chance that the read pointer will deviate, forward or backward,\n# while writing to a genome. This drift causes mutations in the form\n# of duplications and deletions.\nchance_pointer_deviation = 0.1\n\n# A deviation is equal to the integer paired with the lowest decimal\n# that is greater than random().\npointer_deviation_table = [\n (0.0015, -4),\n (0.025, -3),\n (0.16, -2),\n (0.5, -1),\n (0.84, 1),\n (0.975, 2),\n (0.9985, 3),\n (1, 4)\n]\n"
},
{
"alpha_fraction": 0.7209302186965942,
"alphanum_fraction": 0.7209302186965942,
"avg_line_length": 7.599999904632568,
"blob_id": "fa7fe5f4d3e3f19d3f66d663a285a60326c55a80",
"content_id": "83ed6b36c747d23473b8b08f3502258b8d539ec6",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 43,
"license_type": "permissive",
"max_line_length": 17,
"num_lines": 5,
"path": "/tbn/population.py",
"repo_name": "RabidGuy/tbn",
"src_encoding": "UTF-8",
"text": "import member\n\n\nclass Population:\n pass\n"
},
{
"alpha_fraction": 0.8080251812934875,
"alphanum_fraction": 0.8088119626045227,
"avg_line_length": 104.91666412353516,
"blob_id": "6dbe8a1535193d0d5c0b891a0cee4ed3c6a3c44d",
"content_id": "dda4f2151b0e649ec135fb3f8da60ca7721354ca",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1271,
"license_type": "permissive",
"max_line_length": 743,
"num_lines": 12,
"path": "/README.md",
"repo_name": "RabidGuy/tbn",
"src_encoding": "UTF-8",
"text": "# tbn\ntbn is a name generator intended for naming characters in games. It creates names by offering the user a population of names which they can prune, generation after generation, until a suitable name is found amid the jumble.\n\nInternally, each name is represented by a binary tree. The algorithm breeds these trees and applies minor mutations to generate new names from pre-existing names. Over time, the population will yield more desirable names.\n\nThe design of this application intentionally leaves the user with minimal control. They cannot choose breeding pairs and cannot see the entire population at any one time. It is safe to assume that a person that knows what they want would simply write that name down, therefore any person using this software must not know what they want. By designing the application with this in mind, the user is left with only the ability to select one or more names for elimination before the next breeding round. This allows them to sway the results with their specific bias without allowing them to steer toward a desired outcome. The hope is that a user will find interesting letter combinations or sounds that they would not have explored on their own.\n\n## Testing\n\nFrom the project folder, run\n\n\tpython3 -m unittest discover\n"
},
{
"alpha_fraction": 0.6354794502258301,
"alphanum_fraction": 0.639919638633728,
"avg_line_length": 24.42178726196289,
"blob_id": "775b35d16d14d068ba1eb6698907cdf6cf3f59ff",
"content_id": "66ce248a69a30a6823fd30537db89ad8e6524b32",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9459,
"license_type": "permissive",
"max_line_length": 104,
"num_lines": 358,
"path": "/tbn/prototype.py",
"repo_name": "RabidGuy/tbn",
"src_encoding": "UTF-8",
"text": "import cmd\r\nfrom random import choice, randint, random, sample\r\nfrom string import ascii_lowercase as letters\r\nimport sys\r\n\r\n\r\nclass App(cmd.Cmd):\r\n\r\n\tdef __init__(self):\r\n\t\tsuper().__init__()\r\n\t\tself.prompt = \"Cmd > \"\r\n\t\tself.population = Population()\r\n\t\tself.do_sample()\r\n\r\n\tdef do_exit(self, args):\r\n\t\tsys.exit()\r\n\r\n\tdef do_sample(self, args=\"\"):\r\n\t\tsample = self.population.get_sample()\r\n\t\tkeys = list(sample.keys())\r\n\t\tkeys.sort()\r\n\t\tfor key in keys:\r\n\t\t\tprint(\"%s) %s\" % (key, sample[key]))\r\n\r\n\tdef do_k(self, args):\r\n\t\tself.do_kill(args)\r\n\r\n\tdef do_kill(self, args):\r\n\t\targlist = args.split()\r\n\t\ttry:\r\n\t\t\tmember = self.population.get_member(arglist[0])\r\n\t\texcept IndexError:\r\n\t\t\tprint(\"error: kill expects one argument\")\r\n\t\texcept KeyError:\r\n\t\t\tprint(\"error: not a valid index\")\r\n\t\telse:\r\n\t\t\tself.population.kill(member)\r\n\t\t\tself.population.select_sample()\r\n\t\t\tself.do_sample()\r\n\r\n\tdef do_b(self, args):\r\n\t\tself.do_breed(args)\r\n\r\n\tdef do_breed(self, args):\r\n\t\targlist = args.split()\r\n\t\ttry:\r\n\t\t\tpa = self.population.get_member(arglist[0])\r\n\t\t\tpb = self.population.get_member(arglist[1])\r\n\t\texcept IndexError:\r\n\t\t\tprint(\"error: breed expects two arguments\")\r\n\t\texcept KeyError:\r\n\t\t\tprint(\"error: not a valid index\")\r\n\t\telse:\r\n\t\t\tif pa is pb:\r\n\t\t\t\tprint(\"error: cannot breed member with itself\")\r\n\t\t\tself.population.breed(pa, pb)\r\n\t\t\tself.population.select_sample()\r\n\t\t\tself.do_sample()\r\n\t\t# print(self.population._population)\r\n\r\n\tdef do_new(self, args):\r\n\t\tself.population = Population()\r\n\t\tself.do_sample()\r\n\r\n\r\nclass Population:\r\n\r\n\tdef __init__(self, start_population=None):\r\n\t\tself._size = 32\r\n\t\tself._population = None # List\r\n\t\tself._sample_size = 10\r\n\t\tself._sample = None # Dict {index string: member}\r\n\t\tself._index_strings = [str(i + 1) for i in range(self._sample_size)]\r\n\r\n\t\tself.randomize_population(start_population or [])\r\n\t\tself.select_sample()\r\n\r\n\tdef randomize_population(self, start_population=[]):\r\n\t\t# Copy start population into working population.\r\n\t\tself._population = [m for m in start_population]\r\n\t\t# If population too large, cut it down.\r\n\t\tself._population = self._population[:self._size]\r\n\t\t# If population too small, fill it up.\r\n\t\twhile len(self._population) < self._size:\r\n\t\t\tself._population.append(Member())\r\n\r\n\tdef get_member(self, index_string):\r\n\t\treturn self._sample[index_string]\r\n\r\n\tdef select_sample(self):\r\n\t\t# Clean sample.\r\n\t\tself._sample = {}\r\n\t\t# Get sample from population.\r\n\t\tpicks = sample(self._population, self._sample_size)\r\n\t\t# Map sample members to input strings.\r\n\t\tfor idx in range(self._sample_size):\r\n\t\t\tkey = self._index_strings[idx]\r\n\t\t\tvalue = picks[idx]\r\n\t\t\tself._sample[key] = value\r\n\r\n\tdef get_sample(self):\r\n\t\treturn self._sample.copy()\r\n\r\n\tdef kill(self, member):\r\n\t\t# Remove member from population.\r\n\t\tself._population.remove(member)\r\n\t\t# Breed new member from population and append.\r\n\t\tpa, pb = sample(self._population, 2)\r\n\t\tself._population.append(Member(pa, pb))\r\n\r\n\tdef breed(self, pa, pb):\r\n\t\t# Remove random member from population.\r\n\t\tself._population.remove(choice(self._population))\r\n\t\t# Breed new member from selected member and append.\r\n\t\tself._population.append(Member(pa, pb))\r\n\r\n\r\nclass Member:\r\n\r\n\tdef __init__(self, *args):\r\n\t\tassert len(args) in [0, 2]\r\n\t\t# Two args will breed, else returns randomized node.\r\n\t\t# self._mutation_rate = .25\r\n\t\tself._mutation_rate = 1\r\n\t\tself._root = None\r\n\t\ttry:\r\n\t\t\tself._breed(args[0], args[1])\r\n\t\texcept IndexError:\r\n\t\t\tself._new()\r\n\r\n\t@property\r\n\tdef root(self):\r\n\t\treturn self._root\r\n\r\n\tdef __str__(self):\r\n\t\treturn str(self.root)\r\n\r\n\tdef _new(self):\r\n\t\tc = [choice(letters) for _ in range(7)]\r\n\t\tself._root = BTNode()\r\n\t\tself._root.char = c[0]\r\n\t\tself._root.left = BTNode()\r\n\t\tself._root.left.char = c[1]\r\n\t\tself._root.right = BTNode()\r\n\t\tself._root.right.char = c[2]\r\n\r\n\t\tself._root.left.left = BTNode()\r\n\t\tself._root.left.left.char = c[3]\r\n\t\tself._root.left.right = BTNode()\r\n\t\tself._root.left.right.char = c[4]\r\n\r\n\t\tself._root.right.left = BTNode()\r\n\t\tself._root.right.left.char = c[5]\r\n\t\tself._root.right.right = BTNode()\r\n\t\tself._root.right.right.char = c[6]\r\n\r\n\r\n\tdef _breed(self, pa, pb):\r\n\t\tself._root = pa.root.breed(pb.root)\r\n\t\tif random() < self._mutation_rate:\r\n\t\t\t# pass # XXX Select an equally weighted node and perform on it some mutation.\r\n\t\t\tpath = self._get_random_node_path()\r\n\t\t\tprint(self._root, [node.char for node in path], end=' ')\r\n\r\n\t\t\t# mutation = randint(1, 5)\r\n\t\t\tmutation = randint(1, 4)\r\n\t\t\tif mutation == 1: self._mutation_transcription(path)\r\n\t\t\tif mutation == 2: self._mutation_swap(path)\r\n\t\t\tif mutation == 3: self._mutation_duplication(path)\r\n\t\t\tif mutation == 4: self._mutation_insertion(path)\r\n\t\t\tif mutation == 5: self._mutation_deletion(path)\r\n\t\t\tprint(self._root)\r\n\r\n\tdef _get_random_node_path(self):\r\n\t\tall_nodes = self._flatten(self._root)\r\n\t\ttarget_node = choice(all_nodes)\r\n\t\tqueue = [self._root]\r\n\t\tparents = {self._root: None}\r\n\t\twhile target_node not in parents:\r\n\t\t\tnode = queue.pop()\r\n\t\t\tif node.right:\r\n\t\t\t\tparents[node.right] = node\r\n\t\t\t\tqueue.append(node.right)\r\n\t\t\tif node.left:\r\n\t\t\t\tparents[node.left] = node\r\n\t\t\t\tqueue.append(node.left)\r\n\t\tpath = [target_node]\r\n\t\twhile parents[path[-1]] is not None:\r\n\t\t\tpath.append(parents[path[-1]])\r\n\t\treturn path\r\n\r\n\tdef _flatten(self, node):\r\n\t\tnodes = [node]\r\n\t\tif node.left:\r\n\t\t\tnodes.extend(self._flatten(node.left))\r\n\t\tif node.right:\r\n\t\t\tnodes.extend(self._flatten(node.right))\r\n\t\treturn nodes\r\n\r\n\tdef _mutation_transcription(self, path):\r\n\t\tnode = path[0]\r\n\t\tnode.char = choice(letters)\r\n\r\n\tdef _mutation_swap(self, path):\r\n\t\tnode = path[0]\r\n\t\tnode.left, node.right = node.right, node.left\r\n\r\n\tdef _mutation_duplication(self, path):\r\n\t\tnode = path[0]\r\n\t\tdupe = BTNode()\r\n\t\tdupe.char = node.char\r\n\t\tif choice(['left', 'right']) == 'left':\r\n\t\t\tdupe.left = node.left\r\n\t\t\tnode.left = dupe\r\n\t\telse:\r\n\t\t\tdupe.right = node.right\r\n\t\t\tnode.right = dupe\r\n\r\n\tdef _mutation_insertion(self, path):\r\n\t\tnode = path[0]\r\n\t\tgrowth = BTNode()\r\n\t\tgrowth.char = choice(letters)\r\n\t\tif choice(['left', 'right']) == 'left':\r\n\t\t\tgrowth.left = node.left\r\n\t\t\tnode.left = growth\r\n\t\telse:\r\n\t\t\tgrowth.right = node.right\r\n\t\t\tnode.right = growth\r\n\r\n\tdef _mutation_deletion(self, path):\r\n\t\tnode = path[0]\r\n\t\tleft = node.left\r\n\t\tright = node.right\r\n\t\tif len(path) > 1:\r\n\t\t\tparent = path[1]\r\n\t\telse:\r\n\t\t\tparent = None\r\n\t\tprint(node, left, right, parent)\r\n\t\tif choice(['left', 'right']) == 'left':\r\n\t\t\tif node is self._root:\r\n\t\t\t\tself._root = node.left\r\n\t\t\t\tself._rightmost(node.left).right = node.right\r\n\t\t\telse:\r\n\t\t\t\tif parent.left is node:\r\n\t\t\t\t\tparent.left = node.left\r\n\t\t\t\telse:\r\n\t\t\t\t\tparent.right = node.left\r\n\t\t\t\tself._rightmost(node.left).right = node.right\r\n\t\telse:\r\n\t\t\tif node is self._root:\r\n\t\t\t\tself._root = node.right\r\n\t\t\t\tself._leftmost(node.right).left = node.left\r\n\t\t\telse:\r\n\t\t\t\tif parent.left is node:\r\n\t\t\t\t\tparent.left = node.right\r\n\t\t\t\telse:\r\n\t\t\t\t\tparent.right = node.right\r\n\t\t\t\tself._leftmost(node.right).left = node.left\r\n\r\n\tdef _leftmost(self, node):\r\n\t\twhile hasattr(node, \"left\"):\r\n\t\t\tnode = node.left\r\n\t\tprint(node)\r\n\t\treturn node\r\n\r\n\tdef _rightmost(self, node):\r\n\t\twhile hasattr(node, \"right\"):\r\n\t\t\tnode = node.right\r\n\t\tprint(node)\r\n\t\treturn node\r\n\r\n\r\nclass BTNode:\r\n\r\n\tdef __init__(self):\r\n\t\tself._char = None\r\n\t\tself._left = None\r\n\t\tself._right = None\r\n\r\n\tdef __str__(self):\r\n\t\tl = str(self.left) if self.left else \"\"\r\n\t\tr = str(self.right) if self.right else \"\"\r\n\t\treturn ''.join([l, self.char, r])\r\n\r\n\t@property\r\n\tdef char(self):\r\n\t\treturn self._char\r\n\r\n\[email protected]\r\n\tdef char(self, a):\r\n\t\tself._char = a\r\n\r\n\t@property\r\n\tdef left(self):\r\n\t\treturn self._left\r\n\r\n\[email protected]\r\n\tdef left(self, node):\r\n\t\tself._left = node\r\n\r\n\t@property\r\n\tdef right(self):\r\n\t\treturn self._right\r\n\r\n\[email protected]\r\n\tdef right(self, node):\r\n\t\tself._right = node\r\n\r\n\tdef breed(self, partner):\r\n\t\t# XXX Compare self to partner and return new node with new children.\r\n\t\t# XXX If it has one or two children, pass corresponding partner children and send to each.\r\n\t\t# XXX If partner is None or partner child is None, act accordingly.\r\n\t\t# XXX If own child is None, pass responsibility to partner if partner has child, else\r\n\t\t# XXX return new node with child set to None.\r\n\t\tnode = BTNode()\r\n\r\n\t\tif partner:\r\n\t\t\tnode.char = choice([self.char, partner.char])\r\n\t\telse:\r\n\t\t\tnode.char = choice([self.char, None])\r\n\r\n\t\tif not node.char:\r\n\t\t\t# This node failed to breed against a leaf. It and all of its children have been pruned.\r\n\t\t\treturn None\r\n\r\n\t\t# XXX Consider combining the `left` if-block with the `right` if-block for legibility and maintenance.\r\n\t\tif self.left and partner and partner.left:\r\n\t\t\t# Both children are valid.\r\n\t\t\tnode.left = self.left.breed(partner.left)\r\n\t\telif self.left:\r\n\t\t\t# Our left is valid and theirs is not.\r\n\t\t\tnode.left = self.left.breed(None)\r\n\t\telif partner and partner.left:\r\n\t\t\t# Our left is not valid and theirs is.\r\n\t\t\tnode.left = partner.left.breed(None)\r\n\t\telse:\r\n\t\t\t# Neither children are valid.\r\n\t\t\tnode.left = None\r\n\r\n\t\tif self.right and partner and partner.right:\r\n\t\t\t# Both children are valid.\r\n\t\t\tnode.right = self.right.breed(partner.right)\r\n\t\telif self.right:\r\n\t\t\t# Our right is valid and theirs is not.\r\n\t\t\tnode.right = self.right.breed(None)\r\n\t\telif partner and partner.right:\r\n\t\t\t# Our right is not valid and theirs is.\r\n\t\t\tnode.right = partner.right.breed(None)\r\n\t\telse:\r\n\t\t\t# Neither children are valid.\r\n\t\t\tnode.right = None\r\n\r\n\t\treturn node\r\n\r\n\r\nif __name__ == '__main__':\r\n\tapp = App()\r\n\tapp.cmdloop()\r\n"
}
] | 8 |
lewiscj97/pi-football-initial | https://github.com/lewiscj97/pi-football-initial | 923bb11558b3f601d70a05ad2bf05274b30ffa58 | 98b02d5eb0a4ce3c2cd3c2e9a90d86688013ecee | 73faf5a38ba6304463241cbb1e573f0bd0af8da3 | refs/heads/main | 2023-08-11T00:11:08.208335 | 2021-10-06T16:09:58 | 2021-10-06T16:09:58 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5418012142181396,
"alphanum_fraction": 0.5446717143058777,
"avg_line_length": 38.53191375732422,
"blob_id": "2742fc78847f344db64584bd7927f8da8e55353f",
"content_id": "729f00c233f18b2088c46d9a6cb821496cb89f22",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5574,
"license_type": "no_license",
"max_line_length": 150,
"num_lines": 141,
"path": "/src/BBCSportScraper.py",
"repo_name": "lewiscj97/pi-football-initial",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python\n\nfrom bs4 import BeautifulSoup\nfrom selenium import webdriver\nimport pandas as pd\nimport datetime\nimport time\n\n\nclass Scraper:\n def __init__(self):\n self.link = \"https://www.bbc.co.uk/sport/football/scores-fixtures\"\n self.browser = webdriver.Chrome('/Users/lewisjones/PycharmProjects/Bits/chromedriver')\n self.block = \"\"\n self.matches = []\n self.home_team = []\n self.away_team = []\n self.home_score = []\n self.away_score = []\n self.time_list = []\n\n def open_pages(self):\n self.browser.get(self.link)\n time.sleep(1)\n content = self.browser.page_source\n soup = BeautifulSoup(content, features='html.parser')\n self.browser.close()\n return soup\n\n def get_match_blocks(self, soup):\n match_blocks = soup.find_all('div', class_='qa-match-block')\n return match_blocks\n\n def identify_block(self, all_blocks, league):\n for block in all_blocks:\n if block.h3.text.strip() == league:\n self.block = block\n return self.block\n\n def find_all_matches(self, container):\n self.matches = container.find_all('li', class_='gs-o-list-ui__item gs-u-pb-')\n return self.matches\n\n def get_team_names(self, matches):\n team_names = []\n\n for match in matches:\n if \"sp-c-fixture__number sp-c-fixture__number--home sp-c-fixture__number--live-sport\" in str(match):\n team_name = match.find_all('span',\n class_=\"gs-u-display-none gs-u-display-block@m qa-full-team-name sp-c-fixture__team-name-trunc\")\n team_names.append(team_name)\n\n elif \"sp-c-fixture__number sp-c-fixture__number--home sp-c-fixture__number--ft\" in str(match):\n team_name = match.find_all('span',\n class_=\"gs-u-display-none gs-u-display-block@m qa-full-team-name sp-c-fixture__team-name-trunc\")\n team_names.append(team_name)\n\n for x in range(len(team_names)):\n self.home_team.append(team_names[x][0].text)\n self.away_team.append(team_names[x][1].text)\n\n # print(home_team)\n # print(away_team)\n\n def get_scores(self, matches):\n home_scores = []\n away_scores = []\n yet_to_start = []\n\n for match in range(len(matches)):\n # In play\n if \"sp-c-fixture__number sp-c-fixture__number--home sp-c-fixture__number--live-sport\" in str(\n matches[match]):\n home_scores.append(matches[match].find_all('span',\n class_=\"sp-c-fixture__number sp-c-fixture__number--home sp-c-fixture__number--live-sport\"))\n away_scores.append(matches[match].find_all('span',\n class_=\"sp-c-fixture__number sp-c-fixture__number--away sp-c-fixture__number--live-sport\"))\n\n # Full time\n elif \"sp-c-fixture__number sp-c-fixture__number--home sp-c-fixture__number--ft\" in str(matches[match]):\n home_scores.append(matches[match].find_all('span',\n class_=\"sp-c-fixture__number sp-c-fixture__number--home sp-c-fixture__number--ft\"))\n away_scores.append(matches[match].find_all('span',\n class_=\"sp-c-fixture__number sp-c-fixture__number--away sp-c-fixture__number--ft\"))\n\n # Yet to start\n elif \"sp-c-fixture__number sp-c-fixture__number--time\" in str(matches[match]):\n yet_to_start.append(matches[match].find_all('span',\n class_=\"sp-c-fixture__number sp-c-fixture__number--time\"))\n\n # Home\n for x in range(len(home_scores)):\n self.home_score.append(home_scores[x][0].text)\n\n # Away\n for x in range(len(away_scores)):\n self.away_score.append(away_scores[x][0].text)\n\n # print(home_score)\n # print(away_score)\n # print(yet_to_start)\n\n def get_times(self, matches):\n times = []\n\n for match in matches:\n if \"sp-c-fixture__number sp-c-fixture__number--home sp-c-fixture__number--live-sport\" in str(match):\n time = match.find_all('span',\n class_=\"sp-c-fixture__status gel-brevier sp-c-fixture__status--live-sport\")\n times.append(time)\n\n elif \"sp-c-fixture__number sp-c-fixture__number--home sp-c-fixture__number--ft\" in str(match):\n time = match.find_all('span',\n class_=\"sp-c-fixture__status sp-c-fixture__status--ft gel-minion\")\n times.append(time)\n\n for time in times:\n self.time_list.append(time[0].text)\n\n # print(time_list)\n\n def print_results(self):\n for x in range(len(self.home_team)):\n print(f\"{self.home_team[x]:>17} {self.home_score[x]} - {self.away_score[x]} {self.away_team[x]:17}\\n\"\n f\"{self.time_list[x]:^42}\")\n print()\n\n\ndef main(league):\n s = Scraper()\n s1 = s.open_pages()\n blocks = s.get_match_blocks(s1)\n league_block = s.identify_block(blocks, league)\n matches = s.find_all_matches(league_block)\n s.get_team_names(matches)\n s.get_scores(matches)\n s.get_times(matches)\n s.print_results()\n\n\nmain(\"Turkish Super Lig\")\n"
}
] | 1 |
zbxzc35/milCNN | https://github.com/zbxzc35/milCNN | 2cf60b2f3145dfa8583ea796cc346912247db417 | 7cde3ea5e39ea27b69b2b3981c4d90d2ddc25188 | 103b4b50bcbe5990fea07fa5e88902034ae0735a | refs/heads/master | 2020-03-10T16:32:28.905199 | 2017-09-02T20:37:00 | 2017-09-02T20:37:00 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5772420763969421,
"alphanum_fraction": 0.5910649299621582,
"avg_line_length": 34.05038833618164,
"blob_id": "18337935ecfc160244126245aaf0e618d3691e0b",
"content_id": "5f89dc078f04d84561d0ddad4762b5ea3296ded1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 18086,
"license_type": "no_license",
"max_line_length": 225,
"num_lines": 516,
"path": "/milCNN.py",
"repo_name": "zbxzc35/milCNN",
"src_encoding": "UTF-8",
"text": "import sys\nimport os\nimport numpy as np\nimport pdb\nfrom keras.models import Sequential\nfrom keras.layers.core import Dense, Dropout, Activation, Flatten\n#from keras.layers.merge import Concatenate\nfrom keras.layers.normalization import BatchNormalization\nfrom keras.layers.advanced_activations import PReLU, LeakyReLU\nfrom keras.optimizers import SGD, RMSprop, Adadelta, Adagrad, Adam\nfrom keras.layers import normalization, Lambda, GlobalMaxPooling2D, Lambda, GlobalMaxPooling1D\nfrom keras.layers import LSTM, Bidirectional, Reshape\nfrom keras.layers.embeddings import Embedding\nfrom keras.layers.convolutional import Conv2D, MaxPooling2D,Conv1D, MaxPooling1D\nfrom keras.callbacks import ModelCheckpoint, EarlyStopping\nfrom keras.utils import to_categorical\nfrom customlayers import Recalc, ReRank, ExtractDim, SoftReRank, ActivityRegularizerOneDim, RecalcExpand, Softmax4D\nfrom keras.constraints import maxnorm\nfrom sklearn.preprocessing import LabelEncoder\nfrom sklearn.preprocessing import StandardScaler, MinMaxScaler\nfrom keras import objectives\nfrom keras import backend as K\nfrom keras.utils import np_utils, plot_model\nfrom sklearn.metrics import roc_curve, auc, roc_auc_score\nfrom utils import doublet_shuffle, split_training_validation\nimport random\nimport gzip\nimport pickle\n# import tensorflow as tf\n# os.environ[\"CUDA_VISIBLE_DEVICES\"]=\"1\"\n# from keras import backend as K\n# config = tf.ConfigProto()\n# config.gpu_options.allow_growth=True\n# sess = tf.Session(config=config)\n# K.set_session(sess)\ndef padding_sequence_new(seq, max_len = 101, repkey = 'N'):\n seq_len = len(seq)\n new_seq = seq\n if seq_len < max_len:\n gap_len = max_len -seq_len\n new_seq = seq + repkey * gap_len\n return new_seq\n\ndef read_rna_dict(rna_dict = 'rna_dict'):\n odr_dict = {}\n with open(rna_dict, 'r') as fp:\n for line in fp:\n values = line.rstrip().split(',')\n for ind, val in enumerate(values):\n val = val.strip()\n odr_dict[val] = ind\n \n return odr_dict\n\ndef get_6_trids():\n nucle_com = []\n chars = ['A', 'C', 'G', 'U']\n base=len(chars)\n end=len(chars)**6\n for i in range(0,end):\n n=i\n ch0=chars[n%base]\n n=n/base\n ch1=chars[n%base]\n n=n/base\n ch2=chars[n%base]\n n=n/base\n ch3=chars[n%base]\n n=n/base\n ch4=chars[n%base]\n n=n/base\n ch5=chars[n%base]\n nucle_com.append(ch0 + ch1 + ch2 + ch3 + ch4 + ch5)\n return nucle_com \n\ndef get_embed_dim_new(embed_file):\n with open(embed_file) as f:\n pepEmbedding = pickle.load(f)\n \n embedded_dim = pepEmbedding[0].shape\n print embedded_dim\n n_aa_symbols, embedded_dim = embedded_dim\n print n_aa_symbols, embedded_dim\n # = embedded_dim[0]\n embedding_weights = np.zeros((n_aa_symbols + 1,embedded_dim))\n embedding_weights[1:,:] = pepEmbedding[0]\n \n return embedded_dim, pepEmbedding[0], n_aa_symbols\n\ndef split_overlap_seq(seq):\n window_size = 101\n overlap_size = 20\n #pdb.set_trace()\n bag_seqs = []\n seq_len = len(seq)\n if seq_len >= window_size:\n num_ins = (seq_len - 101)/(window_size - overlap_size) + 1\n remain_ins = (seq_len - 101)%(window_size - overlap_size)\n else:\n num_ins = 0\n bag = []\n end = 0\n for ind in range(num_ins):\n start = end - overlap_size\n if start < 0:\n start = 0\n end = start + window_size\n subseq = seq[start:end]\n bag_seqs.append(subseq)\n if num_ins == 0:\n seq1 = seq\n pad_seq = padding_sequence_new(seq1)\n bag_seqs.append(pad_seq)\n else:\n if remain_ins > 10:\n #pdb.set_trace()\n #start = len(seq) -window_size\n seq1 = seq[-window_size:]\n pad_seq = padding_sequence_new(seq1)\n bag_seqs.append(pad_seq)\n return bag_seqs\n \ndef get_6_nucleotide_composition(tris, seq, ordict):\n seq_len = len(seq)\n tri_feature = []\n k = len(tris[0])\n #tmp_fea = [0] * len(tris)\n for x in range(len(seq) + 1- k):\n kmer = seq[x:x+k]\n if kmer in tris:\n ind = tris.index(kmer)\n tri_feature.append(ordict[str(ind)])\n else:\n tri_feature.append(-1)\n #tri_feature = [float(val)/seq_len for val in tmp_fea]\n #pdb.set_trace() \n return np.asarray(tri_feature)\n\ndef read_seq_graphprot(seq_file, label = 1):\n seq_list = []\n labels = []\n seq = ''\n with open(seq_file, 'r') as fp:\n for line in fp:\n if line[0] == '>':\n name = line[1:-1]\n else:\n seq = line[:-1].upper()\n seq = seq.replace('T', 'U')\n seq_list.append(seq)\n labels.append(label)\n \n return seq_list, labels\n\ndef get_RNA_concolutional_array(seq, motif_len = 4):\n seq = seq.replace('U', 'T')\n alpha = 'ACGT'\n #for seq in seqs:\n #for key, seq in seqs.iteritems():\n row = (len(seq) + 2*motif_len - 2)\n new_array = np.zeros((row, 4))\n for i in range(motif_len-1):\n new_array[i] = np.array([0.25]*4)\n \n for i in range(row-3, row):\n new_array[i] = np.array([0.25]*4)\n \n #pdb.set_trace()\n for i, val in enumerate(seq):\n i = i + motif_len-1\n if val not in 'ACGT':\n new_array[i] = np.array([0.25]*4)\n continue\n try:\n index = alpha.index(val)\n new_array[i][index] = 1\n except:\n pdb.set_trace()\n #data[key] = new_array\n return new_array\n\ndef load_graphprot_data(protein, train = True, path = '../GraphProt_CLIP_sequences/'):\n data = dict()\n tmp = []\n listfiles = os.listdir(path)\n \n key = '.train.'\n if not train:\n key = '.ls.'\n mix_label = []\n mix_seq = []\n mix_structure = [] \n for tmpfile in listfiles:\n if protein not in tmpfile:\n continue\n if key in tmpfile:\n if 'positive' in tmpfile:\n label = 1\n else:\n label = 0\n seqs, labels = read_seq_graphprot(os.path.join(path, tmpfile), label = label)\n #pdb.set_trace()\n mix_label = mix_label + labels\n mix_seq = mix_seq + seqs\n \n data[\"seq\"] = mix_seq\n data[\"Y\"] = np.array(mix_label)\n \n return data\n\ndef loaddata_graphprot(protein, train = True, ushuffle = True):\n #pdb.set_trace()\n data = load_graphprot_data(protein, train = train)\n label = data[\"Y\"]\n rna_array = []\n #trids = get_6_trids()\n #nn_dict = read_rna_dict()\n for rna_seq in data[\"seq\"]:\n #rna_seq = rna_seq_dict[rna]\n rna_seq = rna_seq.replace('T', 'U')\n \n seq_array = get_RNA_seq_concolutional_array(seq)\n #tri_feature = get_6_nucleotide_composition(trids, rna_seq_pad, nn_dict)\n rna_array.append(seq_array)\n \n return np.array(rna_array), label\n\ndef read_fasta_file(fasta_file):\n seq_dict = {} \n fp = open(fasta_file, 'r')\n name = ''\n for line in fp:\n #let's discard the newline at the end (if any)\n line = line.rstrip()\n #distinguish header from sequence\n if line[0]=='>': #or line.startswith('>')\n #it is the header\n name = line[1:] #discarding the initial >\n seq_dict[name] = ''\n else:\n #it is sequence\n seq_dict[name] = seq_dict[name] + line.upper()\n fp.close()\n \n return seq_dict\n\ndef load_rnacomend_data(datadir = '../data/'):\n pair_file = datadir + 'interactions_HT.txt'\n #rbp_seq_file = datadir + 'rbps_HT.fa'\n rna_seq_file = datadir + 'utrs.fa'\n \n rna_seq_dict = read_fasta_file(rna_seq_file)\n\n inter_pair = {}\n with open(pair_file, 'r') as fp:\n for line in fp:\n values = line.rstrip().split()\n protein = values[0]\n rna = values[1]\n inter_pair.setdefault(protein, []).append(rna)\n \n return inter_pair, rna_seq_dict\n\ndef get_rnarecommend(rnas, rna_seq_dict):\n data = {}\n label = []\n rna_seqs = []\n for rna in rnas:\n rna_seq = rna_seq_dict[rna]\n rna_seq = rna_seq.replace('T', 'U')\n label.append(1)\n rna_seqs.append(rna_seq)\n label.append(0)\n shuff_seq = doublet_shuffle(rna_seq)\n rna_seqs.append(shuff_seq)\n data[\"seq\"] = rna_seqs\n data[\"Y\"] = np.array(label)\n \n return data\n \n\ndef get_bag_data(seqs, labels):\n bags = []\n #seqs = data[\"seq\"]\n #labels = data[\"Y\"]\n longlen = 0\n for seq in seqs:\n #pdb.set_trace()\n bag_seqs = split_overlap_seq(seq)\n #flat_array = []\n bag_subt = []\n for bag_seq in bag_seqs:\n tri_fea = get_RNA_concolutional_array(bag_seq)\n bag_subt.append(tri_fea)\n data = np.array(bag_subt)\n if longlen < data.shape[0]:\n longlen = data.shape[0]\n # print(data.shape, type(data.shape))\n bags.append(data) #np.reshape(data, [1]+list(data.shape)))\n padbags = []\n for data in bags:\n paddata = np.zeros([longlen]+list(data.shape[1:]))\n paddata[:data.shape[0], :, :] = np.array(data)\n paddata = np.reshape(paddata, [1]+list(paddata.shape))\n padbags.append(paddata)\n return padbags, labels # bags,\n\ndef mil_squared_error(y_true, y_pred):\n return K.tile(K.square(K.max(y_pred) - K.max(y_true)), 5)\n\ndef custom_objective(y_true, y_pred):\n #prediction = Flatten(name='flatten')(dense_3)\n #prediction = ReRank(k=k, label=1, name='output')(prediction)\n #prediction = SoftReRank(softmink=softmink, softmaxk=softmaxk, label=1, name='output')(prediction)\n '''Just another crossentropy'''\n #y_true = K.clip(y_true, _EPSILON, 1.0-_EPSILON)\n y_true = K.max(y_true)\n #y_armax_index = numpy.argmax(y_pred)\n y_new = K.max(y_pred)\n #y_new = max(y_pred)\n '''\n if y_new >= 0.5:\n y_new_label = 1\n else:\n y_new_label = 0\n cce = abs(y_true - y_new_label)\n '''\n logEps=1e-8\n cce = - (y_true * K.log(y_new+logEps) + (1 - y_true)* K.log(1-y_new + logEps))\n return cce\n\ndef set_cnn_model(ninstance=4, input_dim = 4, input_length = 107):\n nbfilter = 16\n model = Sequential() # #seqs * seqlen * 4\n #model.add(brnn)\n model.add(Conv2D(input_shape=(ninstance, input_length, input_dim),\n filters=nbfilter,\n kernel_size=(1,10),\n padding=\"valid\",\n #activation=\"relu\",\n strides=(1,3))) # 4 33 16\n model.add(Activation('relu'))\n # model.add(Conv2D(filters=nbfilter*4, kernel_size=(1,5), padding='valid', activation='relu', strides=(1,2))) # 4 94 64\n # model.add(MaxPooling2D(pool_size=(1,3))) # 4 31 64\n # model.add(Dropout(0.25)) # will be better\n model.add(Conv2D(filters=nbfilter*2*4*2*2*2, kernel_size=(1,3), padding='valid', activation='relu', strides=(1,1))) # 4 31 128\n # model.add(Flatten())\n #model.add(Softmax4D(axis=1))\n\n #model.add(MaxPooling1D(pool_length=3))\n #model.add(Flatten())\n #model.add(Recalc(axis=1))\n # model.add(Flatten())\n # model.add(Dense(nbfilter*2, activation='relu'))\n # model.add(Dropout(0.25))\n model.add(Conv2D(filters=2, kernel_size=(1,31), padding='valid', activation='softmax', strides=(1,1)))\n model.add(Lambda(lambda x: x[:,:,:,1], output_shape=(1, 1, 1)))\n\n return model\n \ndef get_all_mildata(protein, dataset = 'graphprot'):\n data = load_graphprot_data(protein)\n #seqs = data[\"seq\"]\n #labels = data[\"Y\"]\n #pdb.set_trace()\n train_bags, label = get_bag_data(data[\"seq\"], data[\"Y\"])\n #pdb.set_trace()\n\n test_data = load_graphprot_data(protein, train = False)\n test_bags, true_y = get_bag_data(test_data[\"seq\"], test_data[\"Y\"]) \n \n return train_bags, label, test_bags, true_y\n\ndef get_all_rna_mildata(rnas, seq_dict):\n data = get_rnarecommend(rnas, seq_dict)\n labels = data[\"Y\"]\n seqs = data[\"seq\"]\n training_val_indice, train_val_label, test_indice, test_label = split_training_validation(labels)\n \n train_seqs = []\n for val in training_val_indice:\n train_seqs.append(seqs[val])\n \n train_bags, label = get_bag_data(train_seqs, train_val_label)\n \n test_seqs = []\n for val in test_indice:\n test_seqs.append(seqs[val]) \n\n #test_data = load_graphprot_data(test_seqs, test_label)\n test_bags, true_y = get_bag_data(test_seqs, test_label) \n \n return train_bags, label, test_bags, true_y\n\ndef run_network(model, total_hid, train_bags, test_bags, y_bags):\n # model.add(Dense(1)) # binary classification\n # model.add(Activation('softmax')) # #instance * 2\n model.add(GlobalMaxPooling1D()) # max pooling multi instance \n\n model.summary()\n savemodelpng = 'net.png'\n #plot_model(model, to_file=savemodelpng, show_shapes=True)\n # print(len(train_bags), len(test_bags), len(y_bags), train_bags[0].shape, y_bags[0].shape, len(train_bags[0]))\n #categorical_crossentropy, binary_crossentropy, mil_squared_error\n #sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True) \n #model.compile(loss=mil_squared_error, optimizer='rmsprop') \n # print 'model training'\n #nb_epos= 5\n #model.fit(train_bags, y_bags, batch_size = 60, epochs=nb_epos, verbose = 0)\n \n #categorical_crossentropy, binary_crossentropy\n #sgd = SGD(lr=0.01, decay=1e-6, momentum=0.9, nesterov=True) custom_objective\n model.compile(loss='binary_crossentropy', optimizer='rmsprop')\n #model.compile(loss=custom_objective, optimizer='rmsprop')\n print 'model training'\n nb_epos= 8\n # y_bags = to_categorical(y_bags, 2)\n # for iterate in range(nb_epos):\n print 'train epoch', nb_epos\n # for training, y in zip(train_bags, y_bags):\n # tmp_size = len(training)\n #pdb.set_trace()\n #ys = np.array(tmp_size *[y]) # make the labels in the bag all have the same labels, maybe not correct?\n # ys = np.zeros((tmp_size,2))\n # ys[:, y] = 1 # binary class ############################################################################### one hot encoding\n # ys = y*np.ones((4,)) # I do not understand the correspondence of ys and tarining, need to confirm ####\n # trainingreshap = np.reshape(training, (1, training.shape[0], training.shape[1], training.shape[2]))\n # print(training.shape, y.shape)\n model.fit(train_bags, y_bags, batch_size = 100, epochs=nb_epos, verbose = 1)\n #model.reset_states()\n #ys = np_utils.to_categorical(ys)\n #model.train_on_batch(training, ys)\n print 'predicting' \n # predictions = []\n # for testing in test_bags:\n\t# pdb.set_trace()\n pred = model.predict_proba(test_bags, verbose = 0)\n # predictions.append(pred[0][0])\n return pred\n\ndef run_graphprot_milcnn():\n\n data_dir = '../GraphProt_CLIP_sequences/'\n\n fw = open('result_micnn_mil', 'w')\n print(len(os.listdir(data_dir)))\n print(os.listdir(data_dir))\n finished_protein = set()\n for protein in os.listdir(data_dir):\n \n protein = protein.split('.')[0]\n\n if protein in finished_protein:\n continue\n finished_protein.add(protein)\n print protein\n fw.write(protein + '\\t')\n train_bags, train_labels, test_bags, test_labels = get_all_mildata(protein)\n train_bags_arr = np.asarray(train_bags).squeeze()\n train_labels_arr = np.array(train_labels)\n test_bags_arr = np.array(test_bags).squeeze()\n test_labels_arr = np.array(test_labels)\n print(train_bags[0].shape, train_labels[0], train_bags_arr.shape, train_labels_arr.shape, test_bags_arr.shape, test_labels_arr.shape)\n net = set_cnn_model(ninstance=train_bags[0].shape[1])\n \n #seq_auc, seq_predict = calculate_auc(seq_net)\n hid = 16\n predict = run_network(net, hid, train_bags_arr, test_bags_arr, train_labels_arr)\n \n auc = roc_auc_score(test_labels_arr, predict)\n print 'AUC:', auc\n fw.write(str(auc) + '\\n')\n mylabel = \"\\t\".join(map(str, test_labels))\n myprob = \"\\t\".join(map(str, predict)) \n fw.write(mylabel + '\\n')\n fw.write(myprob + '\\n')\n \n fw.close()\n\ndef run_rnacomend_milcnn():\n inter_pair_dict, rna_seq_dict = load_rnacomend_data()\n fw = open('result_rna_micnn_mil', 'w')\n \n for protein, rnas in inter_pair_dict.iteritems():\n if len(rnas) < 2000:\n continue\n print protein\n fw.write(protein + '\\t')\n train_bags, train_labels, test_bags, test_labels = get_all_rna_mildata(rnas, rna_seq_dict)\n train_bags_arr = np.asarray(train_bags).squeeze()\n train_labels_arr = np.array(train_labels)\n test_bags_arr = np.array(test_bags).squeeze()\n test_labels_arr = np.array(test_labels)\n print(train_bags[0].shape, train_labels[0], train_bags_arr.shape, train_labels_arr.shape, test_bags_arr.shape, test_labels_arr.shape)\n net = set_cnn_model(ninstance=train_bags[0].shape[1])\n \n #seq_auc, seq_predict = calculate_auc(seq_net)\n hid = 16\n predict = run_network(net, hid, train_bags_arr, test_bags_arr, train_labels_arr)\n \n auc = roc_auc_score(test_labels_arr, predict)\n print 'AUC:', auc\n fw.write(str(auc) + '\\n')\n mylabel = \"\\t\".join(map(str, test_labels))\n myprob = \"\\t\".join(map(str, predict)) \n fw.write(mylabel + '\\n')\n fw.write(myprob + '\\n')\n \n fw.close() \n \n #run_mil_classifier(train_bags, train_labels, test_bags, test_labels)\n#run_graphprot_milcnn()\nrun_rnacomend_milcnn()\n#seq= 'TTATCTCCTAGAAGGGGAGGTTACCTCTTCAAATGAGGAGGCCCCCCAGTCCTGTTCCTCCACCAGCCCCACTACGGAATGGGAGCGCATTTTAGGGTGGTTACTCTGAAACAAGGAGGGCCTAGGAATCTAAGAGTGTGAAGAGTAGAGAGGAAGTACCTCTACCCACCAGCCCACCCGTGCGGGGGAAGATGTAGCAGCTTCTTCTCCGAACCAA'\n#print len(seq)\n#split_overlap_seq(seq)\n"
},
{
"alpha_fraction": 0.5912616848945618,
"alphanum_fraction": 0.596802294254303,
"avg_line_length": 32.42327880859375,
"blob_id": "2f2f5f3bb1fdb7d0eb44d5ef719136d8dc2ef69e",
"content_id": "48fdcdb284fee9979031b61c36916e2f6d2bc42c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6317,
"license_type": "no_license",
"max_line_length": 150,
"num_lines": 189,
"path": "/utils.py",
"repo_name": "zbxzc35/milCNN",
"src_encoding": "UTF-8",
"text": "import random\nimport sys\nimport numpy as np\ndef form_seq_graph(seq):\n graph = {}\n for i, s in enumerate(seq[:-1]): \n if s not in graph:\n graph[s] = []\n graph[s].append(seq[i+1]) \n return graph\n\n# sample a random last edge graph\ndef sample_le_graph(graph, last_nt):\n le_graph = {}\n for vx in graph:\n le_graph[vx] = []\n if vx not in last_nt:\n le_graph[vx].append(random.choice(graph[vx]))\n return le_graph \n\n# check whether there exists an Eulerian walk\n# from seq[0] to seq[-1] in the shuffled\n# sequence\ndef check_le_graph(le_graph, last_nt):\n for vx in le_graph:\n if vx not in last_nt:\n if not find_path(le_graph, vx, last_nt):\n return False\n return True \n\n# function from: http://www.python.org/doc/essays/graphs/\n# check whether there is a path between two nodes in a \n# graph\ndef find_path(graph, start, end, path=[]):\n path = path + [start]\n if start == end:\n return path\n if not graph.has_key(start):\n return None\n for node in graph[start]:\n if node not in path:\n newpath = find_path(graph, node, end, path)\n if newpath: return newpath\n return None \n \n# generate a new seq graph based on the last edge graph\n# while randomly permuting all other edges \ndef form_new_graph(graph, le_graph, last_nt):\n new_graph = {}\n for vx in graph:\n new_graph[vx] = []\n temp_edges = graph[vx]\n if vx not in last_nt:\n temp_edges.remove(le_graph[vx][0])\n random.shuffle(temp_edges) \n for ux in temp_edges:\n new_graph[vx].append(ux)\n if vx not in last_nt: \n new_graph[vx].append(le_graph[vx][0])\n return new_graph \n \n# walk through the shuffled graph and make the\n# new sequence \ndef form_shuffled_seq(new_graph, init_nt, len_seq):\n is_done = False\n new_seq = init_nt\n while not is_done:\n last_nt = new_seq[-1]\n new_seq += new_graph[last_nt][0]\n new_graph[last_nt].pop(0)\n if len(new_seq) >= len_seq:\n is_done = True\n return new_seq \n\n# verify the nucl\ndef verify_counts(seq, shuf_seq):\n kmers = {}\n # Forming the k-mer library\n kmer_range = range(1,3)\n for k in kmer_range:\n for tk in itert.product('ACGTN', repeat=k):\n tkey = ''.join(i for i in tk)\n kmers[tkey] = [0,0]\n \n kmers[seq[0]][0] = 1\n kmers[shuf_seq[0]][1] = 1 \n for k in kmer_range:\n for l in range(len(seq)-k+1):\n tkey = seq[l:l+k]\n kmers[tkey][0] += 1\n tkey = shuf_seq[l:l+k]\n kmers[tkey][1] += 1\n for tk in kmers:\n if kmers[tk][0] != kmers[tk][1]:\n return False \n return True\n\n_preprocess_seq = ['N']*256;\n_preprocess_seq[ord('a')] = _preprocess_seq[ord('A')] = 'A'; # Map A => A\n_preprocess_seq[ord('c')] = _preprocess_seq[ord('C')] = 'C'; # Map C => C\n_preprocess_seq[ord('g')] = _preprocess_seq[ord('G')] = 'G'; # Map G => G\n_preprocess_seq[ord('t')] = _preprocess_seq[ord('T')] = 'T'; # Map T => T\n_preprocess_seq[ord('u')] = _preprocess_seq[ord('U')] = 'T'; # Map U => T\n_preprocess_seq = \"\".join(_preprocess_seq)\n \ndef preprocess_seq(seq):\n return seq.translate(_preprocess_seq) \n\ndef doublet_shuffle(seq, verify=False):\n seq = preprocess_seq(seq)\n last_nt = seq[-1]\n graph = form_seq_graph(seq)\n # sample a random last edge graph\n is_ok = False\n while not is_ok:\n le_graph = sample_le_graph(graph, last_nt)\n # check the last edge graph\n is_ok = check_le_graph(le_graph, last_nt)\n new_graph = form_new_graph(graph, le_graph, last_nt)\n shuf_seq = form_shuffled_seq(new_graph, seq[0], len(seq))\n if verify:\n assert(verify_counts(seq, shuf_seq))\n return shuf_seq\n\n\ndef kmer_former(seq, kmerlen):\n kmers = {}\n for j in range(len(seq) - kmerlen + 1):\n tkey = seq[j:j+kmerlen]\n if tkey not in kmers:\n kmers[tkey] = True\n return kmers\n\ndef verify_kmer(shuf_seq, kmers, kmerlen):\n for j in range(len(shuf_seq) - kmerlen + 1):\n tkey = shuf_seq[j:j+kmerlen]\n if tkey in kmers:\n return False\n return True\n\ndef split_training_validation(classes, validation_size = 0.2, shuffle = False):\n \"\"\"split sampels based on balnace classes\"\"\"\n num_samples=len(classes)\n classes=np.array(classes)\n classes_unique=np.unique(classes)\n num_classes=len(classes_unique)\n indices=np.arange(num_samples)\n #indices_folds=np.zeros([num_samples],dtype=int)\n training_indice = []\n training_label = []\n validation_indice = []\n validation_label = []\n for cl in classes_unique:\n indices_cl=indices[classes==cl]\n num_samples_cl=len(indices_cl)\n\n # split this class into k parts\n if shuffle:\n random.shuffle(indices_cl) # in-place shuffle\n \n # module and residual\n num_samples_each_split=int(num_samples_cl*validation_size)\n res=num_samples_cl - num_samples_each_split\n \n training_indice = training_indice + [val for val in indices_cl[num_samples_each_split:]]\n training_label = training_label + [cl] * res\n \n validation_indice = validation_indice + [val for val in indices_cl[:num_samples_each_split]]\n validation_label = validation_label + [cl]*num_samples_each_split\n\n training_index = np.arange(len(training_label))\n random.shuffle(training_index)\n training_indice = np.array(training_indice)[training_index]\n training_label = np.array(training_label)[training_index]\n \n validation_index = np.arange(len(validation_label))\n random.shuffle(validation_index)\n validation_indice = np.array(validation_indice)[validation_index]\n validation_label = np.array(validation_label)[validation_index] \n \n \n return training_indice, training_label, validation_indice, validation_label \n\n\nif __name__ == \"__main__\":\n\tseq= 'TTATCTCCTAGAAGGGGAGGTTACCTCTTCAAATGAGGAGGCCCCCCAGTCCTGTTCCTCCACCAGCCCCACTACGGAATGGGAGCGCATTTTAGGGTGGTTACTCTGAAACAAGGAGGGCCTAGGAATCTAAGAGTGTGAA'\n\tprint seq\n\tsssq = doublet_shuffle(seq)\n\tprint sssq\n"
}
] | 2 |
hacertilbec/Protein-Vectorization | https://github.com/hacertilbec/Protein-Vectorization | 385fc485eaab71a188c06594c2756ef86459d494 | d72b0580fd397b7cf9c0ecbd138731204b668bd4 | 25e2ff053a307b9d11ae854387c5d9dce4d3909e | refs/heads/master | 2020-03-29T22:27:26.168752 | 2019-09-19T14:32:02 | 2019-09-19T14:32:02 | 150,421,709 | 2 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.6199269890785217,
"alphanum_fraction": 0.6344133615493774,
"avg_line_length": 34.88492202758789,
"blob_id": "0f687ac6960dd67619fcfc9d88d4200f332f4571",
"content_id": "97d5552d3bf34fa2c3276173bc2ce1aaaa94d55e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9043,
"license_type": "no_license",
"max_line_length": 134,
"num_lines": 252,
"path": "/notebooks/pys/knnclassifier-scaled.py",
"repo_name": "hacertilbec/Protein-Vectorization",
"src_encoding": "UTF-8",
"text": "#from autoencoders import *\nfrom pdb_utils import *\nfrom autoencoders import *\nimport pickle\nimport numpy as np\nimport random\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib.layers import fully_connected\nfrom functools import partial\nimport sys\n\nfrom Bio import PDB\nimport numpy as np\nimport os\nimport cv2\n\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score\nfrom sklearn.metrics import *\n\ndef top5score(index_dict,neighbors,testY):\n score = 0\n for i,nb in enumerate(neighbors):\n y = testY[i]\n for n in nb:\n if index_dict[n]==y:\n score+=1\n break\n return(score/float(len(neighbors)))\n\nfilter_size=64\nstrategy = \"strategy1\"\nencoding_size = 128\nbatch_size = 100\nnum_iters = 100\ninput_size=2016\n\n# LOAD LABEL DICTIONARIES\nwith open('pickle files/label_dict.pkl', 'rb') as f:\n label_dict = pickle.load(f)\nwith open('pickle files/test_labels.pkl', 'rb') as f:\n scop_label_dict = pickle.load(f)\n\ndef scale_features(features,mean,std_dev):\n return (np.array(features)-mean)/std_dev\n\n# SCOP TEST PDBs\nstructures = []\nfor pdb in os.listdir(\"SCOP_Test/\"):\n if not pdb.endswith(\".pdb\"):\n continue\n pdb_path = os.path.join(\"SCOP_Test\", pdb)\n parser = PDB.PDBParser()\n structure = parser.get_structure(pdb, pdb_path)\n structures.append(structure)\n\nmatrixdict = DistanceMatrixDict(structures, resize_strategy=strategy, resize_to=(filter_size,filter_size),removeSymmetry=True)\nscop_pdb_samples, scop_features = list(matrixdict.keys()), list(matrixdict.values())\n\ntrain_acc_1,test_acc_1, scop_acc_1 = [],[],[]\ntrain_acc_2,test_acc_2, scop_acc_2 = [],[],[]\ntrain_acc_3,test_acc_3, scop_acc_3 = [],[],[]\ntrain_acc_4,test_acc_4, scop_acc_4 = [],[],[]\ntrain_acc_5,test_acc_5, scop_acc_5 = [],[],[]\n\nfor fold in range(1,11):\n train_pdbs = []\n with open(\"Folds/{n}_train.txt\".format(n=fold),\"r\") as f:\n for i in f.readlines():\n train_pdbs.append(i.strip(\"\\n\"))\n test_pdbs = []\n with open(\"Folds/{n}_test.txt\".format(n=fold),\"r\") as f:\n for i in f.readlines():\n test_pdbs.append(i.strip(\"\\n\"))\n\n print(len(train_pdbs))\n print(len(test_pdbs))\n\n train_features, test_features = [],[]\n train_pdb_samples, test_pdb_samples = [],[]\n\n\n for i in range(int(len(train_pdbs)/batch_size)+1): # BATCH\n structures = []\n for pdb in train_pdbs[i*batch_size: (i+1)*batch_size]: # EACH PDB IN THE BATCH\n if pdb == \".ipynb_checkpoints\":\n continue\n pdb_path = os.path.join(\"PDBs\", pdb)\n parser = PDB.PDBParser()\n structure = parser.get_structure(pdb, pdb_path)\n structures.append(structure)\n matrixdict = DistanceMatrixDict(structures, resize_strategy=strategy, resize_to=(filter_size,filter_size),removeSymmetry=True)\n pdbs, features = list(matrixdict.keys()), list(matrixdict.values())\n\n train_pdb_samples+=pdbs\n train_features+=features\n\n input_size = len(train_features[0])\n\n # SCALING\n train_features = np.array(train_features)\n mean = np.mean(train_features.flatten())\n std_dev = np.std(train_features.flatten())\n train_features = scale_features(train_features,mean,std_dev)\n\n # AUTOENCODER\n tf.reset_default_graph()\n tf.set_random_seed(42)\n\n X = tf.placeholder(tf.float32, shape=[None, input_size])\n hidden = fully_connected(X, encoding_size, activation_fn=tf.nn.elu)\n outputs = fully_connected(hidden, input_size, activation_fn=None)\n\n reconstruction_loss = tf.reduce_sum(tf.square(outputs - X)) # MSE\n\n optimizer = tf.train.AdamOptimizer(0.0001)\n training_op = optimizer.minimize(reconstruction_loss)\n\n codings = hidden # the output of the hidden layer provides the codings\n\n init = tf.global_variables_initializer()\n\n sess = tf.InteractiveSession()\n sess.run(init)\n\n # AUTOENCODER TRAINING\n for iteration in range(num_iters):\n for i in range(int(len(train_features)/batch_size)+1): # BATCH\n batch = train_features[i*batch_size: (i+1)*batch_size]\n sess.run([training_op], feed_dict={X: batch})\n\n # TEST FEATURES\n for i in range(int(len(test_pdbs)/batch_size)+1): # BATCH\n structures = []\n for pdb in test_pdbs[i*batch_size: (i+1)*batch_size]: # EACH PDB IN THE BATCH\n if pdb == \".ipynb_checkpoints\":\n continue\n pdb_path = os.path.join(\"PDBs\", pdb)\n parser = PDB.PDBParser()\n structure = parser.get_structure(pdb, pdb_path)\n structures.append(structure)\n matrixdict = DistanceMatrixDict(structures, resize_strategy=strategy, resize_to=(filter_size,filter_size),removeSymmetry=True)\n pdbs, features = list(matrixdict.keys()), list(matrixdict.values())\n test_pdb_samples+=pdbs\n test_features+=features\n\n # SCALING\n test_features = scale_features(test_features,mean,std_dev)\n scop_features = scale_features(scop_features,mean,std_dev)\n\n # REPORT\n print(\"number of train pdbs: {n}\".format(n=len(train_pdb_samples)))\n print(\"number of test pdbs: {n}\".format(n=len(test_pdb_samples)))\n # Embedding vectors of train and test set\n new_train_features = sess.run([hidden], feed_dict={X: train_features})[0]\n new_test_features = sess.run([hidden], feed_dict={X: test_features})[0]\n new_scop_features = sess.run([hidden], feed_dict={X: scop_features})[0]\n\n train_feature_dict = {}\n for i in enumerate(train_pdb_samples):\n if \"sample\" in i[1]:\n pdb = i[1].split(\"sample\")[0]\n else:\n pdb = i[1]\n train_feature_dict.setdefault(pdb,[])\n train_feature_dict[pdb].append(new_train_features[i[0]])\n\n test_feature_dict = {}\n for i in enumerate(test_pdb_samples):\n if \"sample\" in i[1]:\n pdb = i[1].split(\"sample\")[0]\n else:\n pdb = i[1]\n test_feature_dict.setdefault(pdb,[])\n test_feature_dict[pdb].append(new_test_features[i[0]])\n\n scop_feature_dict = {}\n for i in enumerate(scop_pdb_samples):\n if \"sample\" in i[1]:\n pdb = i[1].split(\"sample\")[0]\n else:\n pdb = i[1]\n scop_feature_dict.setdefault(pdb,[])\n scop_feature_dict[pdb].append(new_scop_features[i[0]])\n\n\n X_train = []\n y_train = []\n\n for pdb,vector in train_feature_dict.items():\n pdb = pdb.split(\".\")[0]\n X_train.append(np.average(vector,axis=0))\n y_train.append(\".\".join(label_dict[pdb].split(\".\")[:2]))\n\n X_test = []\n y_test = []\n\n for pdb,vector in test_feature_dict.items():\n pdb = pdb.split(\".\")[0]\n X_test.append(np.average(vector,axis=0))\n y_test.append(\".\".join(label_dict[pdb.split(\".\")[0]].split(\".\")[:2]))\n\n X_scop = []\n y_scop = []\n\n for pdb,vector in scop_feature_dict.items():\n pdb = pdb.split(\".\")[0]\n X_scop.append(np.average(vector,axis=0))\n y_scop.append(\".\".join(scop_label_dict[pdb.split(\".\")[0]].split(\".\")[:2]))\n\n\n uniques = list(set(y_train).union(set(y_test)).union(set(y_scop)) )\n group2id = dict(zip(uniques, range(len(uniques))))\n\n X_train = np.array(X_train)\n y_train = np.array(list(map(lambda x: group2id[x], y_train)))\n X_test = np.array(X_test)\n y_test = np.array(list(map(lambda x: group2id[x], y_test)))\n X_scop = np.array(X_scop)\n y_scop = np.array(list(map(lambda x: group2id[x], y_scop)))\n\n index_train = {}\n for i,train in enumerate(y_train):\n index_train[i] = train\n\n # CLASSIFICATION\n knn = KNeighborsClassifier(n_neighbors=1)\n knn.fit(X_train,y_train)\n train_acc_1.append(knn.score(X_train,y_train))\n test_acc_1.append(knn.score(X_test,y_test))\n scop_acc_1.append(knn.score(X_scop,y_scop))\n\n knn = KNeighborsClassifier(n_neighbors=5)\n knn.fit(X_train,y_train)\n train_acc_5.append(top5score(index_train,knn.kneighbors(X_train,n_neighbors=5,return_distance=False),y_train))\n test_acc_5.append(top5score(index_train,knn.kneighbors(X_test,n_neighbors=5,return_distance=False),y_test))\n scop_acc_5.append(top5score(index_train,knn.kneighbors(X_scop,n_neighbors=5,return_distance=False),y_scop))\n\n\nwith open(\"result_{s}_{f}_{e}_scaled.txt\".format(s=strategy,f=filter_size,e=encoding_size),\"w\") as f:\n f.write(\"strategy:{s}\\nfilter size:{f}\\nencoding size:{e}\\n\\n\".format(s=strategy,f=filter_size,e=encoding_size))\n\n f.write(\"10-fold train Top-1 score:{tr}\\n\".format(tr=sum(train_acc_1)/len(train_acc_1) ))\n f.write(\"10-fold test Top-1 score:{tr}\\n\".format(tr=sum(test_acc_1)/len(test_acc_1) ))\n f.write(\"10-fold SCOP Top-1 score:{tr}\\n\\n\".format(tr=sum(scop_acc_1)/len(scop_acc_1) ))\n\n\n f.write(\"10-fold train Top-5 score):{tr}\\n\".format(tr=sum(train_acc_5)/len(train_acc_5) ))\n f.write(\"10-fold test Top-5 score:{tr}\\n\".format(tr=sum(test_acc_5)/len(test_acc_5) ))\n f.write(\"10-fold SCOP Top-5 score:{tr}\\n\".format(tr=sum(scop_acc_5)/len(scop_acc_5) ))\n"
},
{
"alpha_fraction": 0.6820388436317444,
"alphanum_fraction": 0.6909385323524475,
"avg_line_length": 23.19607925415039,
"blob_id": "f553502519c03e0f1aa79fc015fc8f8e2c6de172",
"content_id": "47807036e7ffd65f4e82350f139eae22d4b8f5d8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1236,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 51,
"path": "/notebooks/pys/pca_with_PDBs.py",
"repo_name": "hacertilbec/Protein-Vectorization",
"src_encoding": "UTF-8",
"text": "from pdb_utils import *\n\nimport pickle\nimport numpy as np\nimport pandas as pd\nimport random\n\nfrom functools import partial\nimport sys\n\nfrom Bio import PDB\nimport os\nimport cv2\n\n\nimport time\n\n\n# Loading label dictionaries\nwith open('pickle files/fold_groups.pkl', 'rb') as f:\n fold_dict = pickle.load(f)\n\n\n\n# Distance Matrices\nall_features = []\n\nfor fold,pdb_list in list(fold_dict.items()):\n structures = []\n for pdb in pdb_list:\n try: \n pdb_path = os.path.join(\"PDBs\", pdb+\".pdb\")\n parser = PDB.PDBParser()\n structure = parser.get_structure(pdb, pdb_path)\n structures.append(structure)\n except:\n continue\n matrix = DistanceMatrixDict(structures, resize_strategy=\"strategy1\", resize_to=(64,64),removeSymmetry=True)\n pdb_names, features = list(matrix.keys()), list(matrix.values())\n all_features += features\n \nall_features=np.array(all_features)\nprint(all_features.shape)\nfrom sklearn.decomposition import IncrementalPCA\ntransformer = IncrementalPCA(n_components=95, batch_size=100)\ntransformer.fit(all_features)\n\nprint(transformer.transform(all_features).shape)\n\nfrom joblib import dump\ndump(transformer, 'pca_with_PDBs.joblib') \n\n"
},
{
"alpha_fraction": 0.689258337020874,
"alphanum_fraction": 0.7004475593566895,
"avg_line_length": 27.962963104248047,
"blob_id": "f9cec1929dae6001917838fb163bfa2626d1ad21",
"content_id": "ec1ba44964e2e0357ae5cb841f8635d32ad4dc5f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6256,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 216,
"path": "/notebooks/pys/two_class_test.py",
"repo_name": "hacertilbec/Protein-Vectorization",
"src_encoding": "UTF-8",
"text": "#from autoencoders import *\nfrom pdb_utils import *\nfrom autoencoders import *\nimport pickle\nimport numpy as np\nimport random\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib.layers import fully_connected\nfrom functools import partial\nimport sys\n\nfrom Bio import PDB\nimport numpy as np\nimport os\nimport cv2\n\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score\nfrom sklearn.metrics import *\n\ndef top5score(index_dict,neighbors,testY):\n score = 0\n for i,nb in enumerate(neighbors):\n y = testY[i]\n for n in nb:\n if index_dict[n]==y:\n score+=1\n break\n return(score/float(len(neighbors)))\n\nfilter_size=64\nstrategy = \"strategy1\"\nencoding_size = 50\nbatch_size = 100\nnum_iters = 100\ninput_size=2016\n\n# LOAD LABEL DICTIONARIES\nwith open('pickle files/label_dict.pkl', 'rb') as f:\n label_dict = pickle.load(f)\nwith open('pickle files/test_labels.pkl', 'rb') as f:\n scop_label_dict = pickle.load(f)\n\nwith open(\"pickle files/fold_groups.pkl\",\"r\") as f:\n fold_groups = pickle.load(f)\nwith open(\"scop_fold_groups.pkl\",\"r\") as f:\n scop_fold_groups = pickle.load(f)\n\nselected = ['a.5','c.67','c.1','b.36']\n\nX_train_pdbs = []\nfor fold in fold_groups:\n if fold in selected:\n X_train_pdbs+=fold_groups[fold]\nprint(len(X_train_pdbs))\n\nX_test_pdbs = []\nfor fold in scop_fold_groups:\n if fold in selected:\n X_test_pdbs+=scop_fold_groups[fold]\nprint(len(X_test_pdbs))\n\n\ndef scale_features(features,mean,std_dev):\n return (np.array(features)-mean)/std_dev\n\n\nstructures = []\nfor pdb in X_test_pdbs:\n pdb=pdb+\".pdb\"\n pdb_path = os.path.join(\"SCOP_Test\", pdb)\n parser = PDB.PDBParser()\n structure = parser.get_structure(pdb, pdb_path)\n structures.append(structure)\n\nmatrixdict = DistanceMatrixDict(structures, resize_strategy=strategy, resize_to=(filter_size,filter_size),removeSymmetry=True)\nscop_pdb_samples, scop_features = list(matrixdict.keys()), list(matrixdict.values())\n\n\n\n\nstructures = []\nfor pdb in X_train_pdbs:\n pdb=pdb+\".pdb\"\n pdb_path = os.path.join(\"PDBs\", pdb)\n parser = PDB.PDBParser()\n structure = parser.get_structure(pdb, pdb_path)\n structures.append(structure)\n\nmatrixdict = DistanceMatrixDict(structures, resize_strategy=strategy, resize_to=(filter_size,filter_size),removeSymmetry=True)\ntrain_pdb_samples, train_features = list(matrixdict.keys()), list(matrixdict.values())\n\ninput_size = len(train_features[0])\n\n# SCALING\ntrain_features = np.array(train_features)\nmean = np.mean(train_features.flatten())\nstd_dev = np.std(train_features.flatten())\ntrain_features = scale_features(train_features,mean,std_dev)\n\n# AUTOENCODER\ntf.reset_default_graph()\ntf.set_random_seed(42)\n\nX = tf.placeholder(tf.float32, shape=[None, input_size])\nhidden = fully_connected(X, encoding_size, activation_fn=tf.nn.elu)\noutputs = fully_connected(hidden, input_size, activation_fn=None)\n\nreconstruction_loss = tf.reduce_sum(tf.square(outputs - X)) # MSE\n\noptimizer = tf.train.AdamOptimizer(0.0001)\ntraining_op = optimizer.minimize(reconstruction_loss)\n\ncodings = hidden # the output of the hidden layer provides the codings\n\ninit = tf.global_variables_initializer()\n\nsess = tf.InteractiveSession()\nsess.run(init)\n\n# AUTOENCODER TRAINING\nlosses = []\nfor iteration in range(num_iters):\n batch_loss = []\n for i in range(int(len(train_features)/batch_size)+1): # BATCH\n batch = train_features[i*batch_size: (i+1)*batch_size]\n _,loss = sess.run([training_op,reconstruction_loss], feed_dict={X: batch})\n batch_loss.append(loss)\n losses.append(sum(batch_loss)/float(len(batch_loss)))\nimport matplotlib.pyplot as plt\nfig, ax = plt.subplots()\nplt.plot(range(num_iters),losses)\nplt.savefig(\"loss_plot2.png\")\n\n# SCALING\nscop_features = scale_features(scop_features,mean,std_dev)\n\n# REPORT\nprint(\"number of train pdbs: {n}\".format(n=len(train_pdb_samples)))\n\n# Embedding vectors of train and test set\nnew_train_features = sess.run([hidden], feed_dict={X: train_features})[0]\nnew_scop_features = sess.run([hidden], feed_dict={X: scop_features})[0]\n\ntrain_feature_dict = {}\nfor i in enumerate(train_pdb_samples):\n if \"sample\" in i[1]:\n pdb = i[1].split(\"sample\")[0]\n else:\n pdb = i[1]\n train_feature_dict.setdefault(pdb,[])\n train_feature_dict[pdb].append(new_train_features[i[0]])\n\nscop_feature_dict = {}\nfor i in enumerate(scop_pdb_samples):\n if \"sample\" in i[1]:\n pdb = i[1].split(\"sample\")[0]\n else:\n pdb = i[1]\n scop_feature_dict.setdefault(pdb,[])\n scop_feature_dict[pdb].append(new_scop_features[i[0]])\n\n\nX_train = []\ny_train = []\n\nfor pdb,vector in train_feature_dict.items():\n pdb = pdb.split(\".\")[0]\n X_train.append(np.average(vector,axis=0))\n y_train.append(\".\".join(label_dict[pdb].split(\".\")[:2]))\n\n\nX_scop = []\ny_scop = []\n\nfor pdb,vector in scop_feature_dict.items():\n pdb = pdb.split(\".\")[0]\n X_scop.append(np.average(vector,axis=0))\n y_scop.append(\".\".join(scop_label_dict[pdb.split(\".\")[0]].split(\".\")[:2]))\n\n\nuniques = list(set(y_train).union(set(y_scop)))\ngroup2id = dict(zip(uniques, range(len(uniques))))\n\nX_train = np.array(X_train)\ny_train = np.array(list(map(lambda x: group2id[x], y_train)))\n\nX_scop = np.array(X_scop)\ny_scop = np.array(list(map(lambda x: group2id[x], y_scop)))\n\nindex_train = {}\nfor i,train in enumerate(y_train):\n index_train[i] = train\n\nfrom sklearn.decomposition import PCA\npca = PCA(n_components=2)\npca.fit(X_train)\nX_train = pca.transform(X_train)\nX_scop = pca.transform(X_scop)\n# CLASSIFICATION\n\nknn = KNeighborsClassifier(n_neighbors=5)\nknn.fit(X_train,y_train)\nprint(top5score(index_train,knn.kneighbors(X_train,n_neighbors=1,return_distance=False),y_train))\nprint(top5score(index_train,knn.kneighbors(X_scop,n_neighbors=1,return_distance=False),y_scop))\n\nprint(top5score(index_train,knn.kneighbors(X_train,n_neighbors=5,return_distance=False),y_train))\nprint(top5score(index_train,knn.kneighbors(X_scop,n_neighbors=5,return_distance=False),y_scop))\n\nfrom sklearn.ensemble import RandomForestClassifier\nlr = RandomForestClassifier()\nlr.fit(X_train,y_train)\nprint(lr.score(X_train,y_train))\nprint(lr.score(X_scop,y_scop))\n"
},
{
"alpha_fraction": 0.7010282874107361,
"alphanum_fraction": 0.7195372581481934,
"avg_line_length": 28.923076629638672,
"blob_id": "613d7b918da63168a72ad1cf84b038bd89dc7db6",
"content_id": "3d33999d815d5331cce9de72c663957add6b6236",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3890,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 130,
"path": "/notebooks/pys/features64x64500d.py",
"repo_name": "hacertilbec/Protein-Vectorization",
"src_encoding": "UTF-8",
"text": "from autoencoders import *\nfrom pdb_utils import *\n\nimport pickle\nimport numpy as np\nimport pandas as pd\nimport random\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib.layers import fully_connected\nfrom functools import partial\nimport sys\n\nfrom Bio import PDB\nimport numpy as np\nimport os\nimport cv2\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nfrom sklearn.model_selection import train_test_split\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import confusion_matrix\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score\nimport time\n\nos.environ['TF_CPP_MIN_LOG_LEVEL'] = '2'\n\n\n# Get and parse all pdb files in a folder\ndef parsePdbFiles(dir_path, sample_n=10):\n structures = []\n files = random.sample(os.listdir(dir_path), sample_n)\n print(\"Number of pdbs: %d\"%len(files))\n pdb_files = [(f, os.path.join(dir_path, f)) for f in files if f.endswith(\".pdb\")]\n\n for pdb, pdb_path in pdb_files:\n parser = PDB.PDBParser()\n structure = parser.get_structure(pdb, pdb_path)\n structures.append(structure)\n return structures\n\nwith open('label_dict.pkl', 'rb') as f:\n label_dict = pickle.load(f)\n\ndef nice_time(start,end):\n hours, rem = divmod(end-start, 3600)\n minutes, seconds = divmod(rem, 60)\n print(\"Runtime: {:0>2}:{:0>2}:{:05.2f}\".format(int(hours),int(minutes),seconds))\n\nprint(\"Started parsing structures\\n\")\ns_time = time.time()\nstructures = parsePdbFiles(\"PDBs\")\nend = time.time()\nnice_time(s_time,end)\n\n\nprint(\"\\nCreating protein contact maps\")\ns_time = time.time()\nproteinmatrixdict = ProteinContactMapDict(structures, resize_to=(64,64), removeSymmetry=True)\nend = time.time()\nnice_time(s_time,end)\n\nlabels, features = list(proteinmatrixdict.keys()), list(proteinmatrixdict.values())\ninput_size = len(features[0])\nprint(\"Input size: \",input_size)\n\nprint(\"\\nLinear Autoencoder - 100 epochs\")\ns_time = time.time()\nnew_features, loss = LinearAutoencoder(features, input_size, 500, 100, learning_rate=0.0001)\nend = time.time()\nnice_time(s_time,end)\n\n# LOSS GRAPH\nfig, ax = plt.subplots()\nax.plot(range(0,len(loss)), loss, 'go-', linewidth=1, markersize=1)\nfig.savefig(\"loss_figure.png\")\n\n#new_feature_dict = dict(zip(labels,new_features))\n\ny = []\nfor pdb_ in labels:\n y.append(label_dict[pdb_[:-4]])\nprint(y)\n\n#print(y[20])\n#print(labels[20])\n\nprint(len(y))\nprint(len(new_features))\n\n# Stratified Cross Validation\nfrom sklearn.model_selection import StratifiedShuffleSplit\n\nprint(\"Stratified Cross Validation - 10 splits\\n\")\ns_time = time.time()\n\nfrom sklearn.model_selection import cross_validate\nclassifier = RandomForestClassifier(n_estimators = 20, criterion = 'entropy', random_state = 42)\ncv_results = cross_validate(classifier, new_features, y, cv=3)\nprint(cv_results)\n\n\"\"\"\nsss = StratifiedShuffleSplit(n_splits=2, test_size=0.2, random_state=0)\nC = 1\nacc, prec, rec = 0,0,0\nfor train_index, test_index in sss.split(new_features, y):\n print(\"Stratified Cross Validation - %d\"%C)\n X_train, X_test = X[train_index], X[test_index]\n y_train, y_test = y[train_index], y[test_index]\n print(\"Random Forest Classifier - Training\")\n # Fitting Random Forest Classification to the Training set\n classifier = RandomForestClassifier(n_estimators = 20, criterion = 'entropy', random_state = 42)\n classifier.fit(X_train, y_train)\n # Predicting the Test set results\n print(\"Random Forest Classifier - Testing\")\n y_pred = classifier.predict(X_test)\n acc+=accuracy_score(y_test, y_pred)\n prec+=precision_score(y_test, y_pred, average='weighted')\n rec+=recall_score(y_test, y_pred, average='weighted')\nend = time.time()\nnice_time(s_time,end)\n\nprint(\"\\naverage accuracy_score: %f\" %acc/10.0)\nprint(\"average precision_score: %f\" %prec/10.0)\nprint(\"average recall_score: %f\" %rec/10.0)\n\"\"\"\n"
},
{
"alpha_fraction": 0.5906177759170532,
"alphanum_fraction": 0.6083458065986633,
"avg_line_length": 42.910179138183594,
"blob_id": "aa2b0d55961c3854b95c89d3f6746dd5bc517434",
"content_id": "a349cc954fff9d8768145355b764bd9706b1ae88",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7333,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 167,
"path": "/notebooks/pys/pdb_utils.py",
"repo_name": "hacertilbec/Protein-Vectorization",
"src_encoding": "UTF-8",
"text": "from Bio import PDB\nimport numpy as np\nimport os\nimport cv2\nfrom math import ceil, floor\nimport random\n\n# Get and parse all pdb files in a folder\ndef parsePdbFiles(dir_path):\n structures = []\n files = os.listdir(dir_path)\n pdb_files = [(f, os.path.join(dir_path, f)) for f in files if f.endswith(\".pdb\")]\n\n for pdb, pdb_path in pdb_files:\n parser = PDB.PDBParser()\n structure = parser.get_structure(pdb, pdb_path)[0]\n structures.append(structure)\n return structures\n\n# Sampling: For a protein with length over 256, they randomly sampled a 256x256\n# sub-matrix from its distance matrix. They repeated this procedure\n# multiple times and obtained an ensemble\n\ndef sampling(distance_matrix, new_shape=(64,64), sample_size=None):\n if not sample_size:\n sample_size = int(floor((distance_matrix.shape[0]/float(new_shape[0]))))*2 # Here, the number of ensemble matrices\n ensemble = [] # was set to be proportional to the length of query protein\n for sample in range(sample_size):\n sampled_matrix = []\n x,y = random.randint(0,len(distance_matrix)-new_shape[0]), random.randint(0,len(distance_matrix)-new_shape[0])\n for i in range(x,x+new_shape[0]):\n sampled_matrix.append(distance_matrix[i][y:y+new_shape[0]])\n ensemble.append(sampled_matrix)\n return(np.array(ensemble))\n\n# Padding: For a protein with length smaller than 256, we embedded its distance\n# matrix into a 256x256 matrix with all elements being 0. The embedding\n# positions are random; thus, we obtained an ensemble of 256x256 matrices\n# after repeating this operation multiple times.\n\ndef padding(distance_matrix, new_shape=(64,64), sample_size=None):\n if not sample_size:\n sample_size = int(ceil((distance_matrix.shape[0]/float(new_shape[0]))))*2 # Here, the number of ensemble matrices\n ensemble = [] # was set to be proportional to the\n for sample in range(sample_size): # length of query protein\n sampled_matrix = [[0 for i in range(new_shape[0])] for i in range(new_shape[0])]\n x,y = random.randint(0,len(sampled_matrix)-len(distance_matrix)), random.randint(0,len(sampled_matrix)-len(distance_matrix))\n s = 0\n for i in range(x,x+len(distance_matrix)):\n sampled_matrix[i][y:y+len(distance_matrix)] = distance_matrix[s][:]\n s+=1\n ensemble.append(sampled_matrix)\n return(np.array(ensemble))\n\n# Strategy 3, Sampling\ndef sampling_s3(distance_matrix, new_shape=(64,64)):\n ensemble = []\n filter_s=new_shape[0]\n step = ceil(distance_matrix.shape[0]/filter_s)\n for i in range(step):\n for j in range(int(step)):\n part = np.array(distance_matrix[i*filter_s:(i+1)*filter_s,j*filter_s:(j+1)*filter_s])\n sample = np.zeros((filter_s,filter_s))\n sample[0:part.shape[0], 0:part.shape[1]] = part\n ensemble.append(sample)\n return(np.array(ensemble))\n\n# Strategy 3, Padding\ndef padding_s3(distance_matrix, new_shape=(64,64)):\n ensemble = []\n filter_s=distance_matrix.shape[0]\n step = ceil(new_shape[0]/distance_matrix.shape[0])\n for i in range(step):\n for j in range(int(step)):\n sample = np.zeros((new_shape[0],new_shape[0]))\n if ((i+1)*filter_s)>new_shape[0] and ((j+1)*filter_s) >new_shape[0]:\n d = distance_matrix[0:(new_shape[0]%filter_s),0:(new_shape[0]%filter_s)]\n elif ((i+1)*filter_s)>new_shape[0]:\n d = distance_matrix[0:(new_shape[0]%filter_s),:]\n elif ((j+1)*filter_s)>new_shape[0]:\n d = distance_matrix[:,0:(new_shape[0]%filter_s)]\n else:\n d = distance_matrix\n sample[i*filter_s:(i+1)*filter_s,j*filter_s:(j+1)*filter_s] = d\n ensemble.append(sample)\n return(np.array(ensemble))\n\ndef createDistanceMatrix(structure,resize_strategy,resize_to,sample_size):\n coords_list = []\n try:\n model=structure[0]\n except:\n model=structure\n for chain in model.get_list():\n for residue in chain.get_list():\n try:\n coords = residue['CA'].coord\n coords_list.append(coords)\n except:\n continue\n distance_matrix = []\n for c in coords_list:\n coord_dist = []\n for c_ in coords_list:\n dist = np.linalg.norm(c-c_) # calculate distance between coordinates of CAs of residues\n coord_dist.append(dist)\n distance_matrix.append(coord_dist)\n distance_matrix = np.array(distance_matrix)\n # Resize protein_matrix\n if resize_strategy == False or len(distance_matrix) == resize_to[0]:\n return distance_matrix\n else:\n if resize_strategy == \"strategy1\":\n try:\n resized = cv2.resize(distance_matrix, (resize_to[0], resize_to[1]), interpolation=cv2.INTER_AREA)\n except:\n return []\n elif resize_strategy == \"strategy2\":\n if len(distance_matrix) > resize_to[0]:\n resized = sampling(distance_matrix, new_shape=resize_to,sample_size=sample_size)\n else:\n resized = padding(distance_matrix, new_shape=resize_to,sample_size=sample_size)\n elif resize_strategy == \"strategy3\":\n if len(distance_matrix) > resize_to[0]:\n resized = sampling_s3(distance_matrix, new_shape=resize_to)\n else:\n resized = padding_s3(distance_matrix, new_shape=resize_to)\n else:\n print(\"Not a valid strategy method. Use False, strategy1, strategy2 or strategy3.\")\n return\n return resized\n\n# Removes symmetry from the distance matrix\ndef RemoveSymmetry(matrix):\n flatten = []\n row = 0\n for i in range(1, len(matrix)):\n flatten += matrix[row][i:].tolist()\n row+=1\n return np.array(flatten)\n\n# get structure list and returns protein, distance matrix dictionary\ndef DistanceMatrixDict(structures,resize_strategy=\"strategy1\", resize_to=(32,32), removeSymmetry=False,sample_size=None):\n if resize_strategy == \"strategy2\" and removeSymmetry == True:\n print(\"RemoveSymmetry parameter can not be used with strategy2\")\n return\n protein_matrix_dict = {}\n for protein in structures:\n protein_matrix = createDistanceMatrix(protein,resize_strategy, resize_to,sample_size)\n if len(protein_matrix) == 0:\n continue\n if resize_strategy == \"strategy2\" or resize_strategy == \"strategy3\":\n try:\n protein_matrix[0].shape[1]\n for sample in enumerate(protein_matrix):\n key = protein.id + \"sample\" + str(sample[0])\n protein_matrix_dict[key] = sample[1].flatten()\n except:\n protein_matrix_dict[protein.id] = protein_matrix.flatten()\n else:\n if type(protein_matrix) == np.ndarray:\n if removeSymmetry == True:\n protein_matrix = RemoveSymmetry(protein_matrix)\n else:\n protein_matrix = protein_matrix.flatten()\n protein_matrix_dict[protein.id] = protein_matrix\n return protein_matrix_dict\n"
},
{
"alpha_fraction": 0.620047390460968,
"alphanum_fraction": 0.6329156756401062,
"avg_line_length": 37.4782600402832,
"blob_id": "3f93451303ca7aab378a3489e8852419ca9a5851",
"content_id": "a11c5a489a31b122406f2b81f5701434b6eaba28",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8859,
"license_type": "no_license",
"max_line_length": 139,
"num_lines": 230,
"path": "/notebooks/pys/autoencoders.py",
"repo_name": "hacertilbec/Protein-Vectorization",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib.layers import fully_connected\nfrom functools import partial\nimport sys\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib.layers import fully_connected\nfrom functools import partial\nimport sys\nimport os\n\n\nclass LinearAutoEncoder:\n def __init__(self,n_input, n_hidden, n_iteration=100, learning_rate = 0.001,model_path = \"models/autoencoder.ckpt\"):\n tf.reset_default_graph()\n tf.set_random_seed(42)\n self.n_inputs = n_input\n self.n_hidden = n_hidden\n self.n_outputs = n_input\n self.n_iteration = n_iteration\n self.learning_rate = learning_rate\n self.n_iterations = n_iteration\n \n self.model_path = model_path\n \n def train(self,X_train):\n X = tf.placeholder(tf.float32, shape=[None, self.n_inputs])\n hidden = fully_connected(X, self.n_hidden, activation_fn=tf.nn.relu)\n outputs = fully_connected(hidden, self.n_outputs, activation_fn=tf.nn.relu)\n\n reconstruction_loss = tf.reduce_sum(tf.square(outputs - X)) # MSE\n\n optimizer = tf.train.AdamOptimizer(self.learning_rate)\n training_op = optimizer.minimize(reconstruction_loss)\n\n codings = hidden # the output of the hidden layer provides the codings\n \n init = tf.global_variables_initializer()\n \n # Add ops to save and restore all the variables.\n saver = tf.train.Saver()\n \n with tf.Session() as sess:\n init.run()\n if os.path.isfile(self.model_path+\".index\"):\n saver.restore(sess, self.model_path)\n loss = []\n for iteration in range(self.n_iterations):\n iteration_loss = []\n for protein in X_train:\n _, loss_val = sess.run([training_op, reconstruction_loss], feed_dict={X: [protein]})\n iteration_loss.append(loss_val)\n loss.append(sum(iteration_loss)/float(len(X_train)))\n\n # Save model parameters\n save_path = saver.save(sess, self.model_path)\n print(\"Model saved in path: %s\" % save_path)\n return loss\n \n def encode(self,samples):\n tf.reset_default_graph()\n X = tf.placeholder(tf.float32, shape=[None, self.n_inputs])\n hidden = fully_connected(X, self.n_hidden, activation_fn=None)\n codings = hidden # the output of the hidden layer provides the codings\n\n # Add ops to save and restore all the variables.\n saver = tf.train.Saver()\n \n # Later, launch the model, use the saver to restore variables from disk, and\n # do some work with the model.\n with tf.Session() as sess:\n # Restore variables from disk.\n saver.restore(sess, self.model_path)\n print(\"Model restored.\")\n # Check the values of the variables\n encoding = codings.eval(feed_dict={X: samples},session=sess)\n return encoding\n \n \ndef LinearAutoencoder(X_train, n_input, n_hidden, n_iteration, learning_rate = 0.001):\n n_inputs = n_input # input is flatten version of input matrix\n n_hidden = n_hidden\n n_outputs = n_inputs\n\n learning_rate = learning_rate\n\n X = tf.placeholder(tf.float32, shape=[None, n_inputs])\n hidden = fully_connected(X, n_hidden, activation_fn=tf.nn.relu)\n outputs = fully_connected(hidden, n_outputs, activation_fn=tf.nn.relu)\n\n reconstruction_loss = tf.reduce_sum(tf.square(outputs - X)) # MSE\n\n optimizer = tf.train.AdamOptimizer(learning_rate)\n training_op = optimizer.minimize(reconstruction_loss)\n\n init = tf.global_variables_initializer()\n\n n_iterations = n_iteration # Number of iterations\n codings = hidden # the output of the hidden layer provides the codings\n\n # Add ops to save and restore all the variables.\n saver = tf.train.Saver()\n\n with tf.Session() as sess:\n init.run()\n loss = []\n for iteration in range(n_iterations):\n _, loss_val = sess.run([training_op, reconstruction_loss], feed_dict={X: X_train}) # no labels (unsupervised)\n loss.append(loss_val)\n\n # Save model parameters\n save_path = saver.save(sess, \"models/autoencoder.ckpt\")\n print(\"Model saved in path: %s\" % save_path)\n \n # Encode training samples\n codings_val = codings.eval(feed_dict={X: X_train})\n return codings_val, loss\n\n\ndef StackedAutoencoderWithTiedWeights(X_train, n_input, n_hidden1, n_hidden2, n_epochs, learning_rate = 0.001):\n n_inputs = n_input # for pair distance matrix\n n_hidden1 = n_hidden1\n n_hidden2 = n_hidden2 # codings\n n_hidden3 = n_hidden1\n n_outputs = n_inputs\n\n learning_rate = learning_rate\n l2_reg = 0.001\n\n activation = tf.nn.elu\n regularizer = tf.contrib.layers.l2_regularizer(l2_reg)\n initializer = tf.contrib.layers.variance_scaling_initializer()\n\n X = tf.placeholder(tf.float32, shape=[None, n_inputs])\n\n weights1_init = initializer([n_inputs, n_hidden1])\n weights2_init = initializer([n_hidden1, n_hidden2])\n\n weights1 = tf.Variable(weights1_init, dtype=tf.float32, name=\"weights1\")\n weights2 = tf.Variable(weights2_init, dtype=tf.float32, name=\"weights2\")\n weights3 = tf.transpose(weights2, name=\"weights3\") # tied weights\n weights4 = tf.transpose(weights1, name=\"weights4\") # tied weights\n\n biases1 = tf.Variable(tf.zeros(n_hidden1), name=\"biases1\")\n biases2 = tf.Variable(tf.zeros(n_hidden2), name=\"biases2\")\n biases3 = tf.Variable(tf.zeros(n_hidden3), name=\"biases3\")\n biases4 = tf.Variable(tf.zeros(n_outputs), name=\"biases4\")\n\n hidden1 = activation(tf.matmul(X, weights1) + biases1)\n hidden2 = activation(tf.matmul(hidden1, weights2) + biases2)\n hidden3 = activation(tf.matmul(hidden2, weights3) + biases3)\n outputs = tf.matmul(hidden3, weights4) + biases4\n\n reconstruction_loss = tf.reduce_mean(tf.square(outputs - X))\n reg_loss = regularizer(weights1) + regularizer(weights2)\n\n loss = reconstruction_loss + reg_loss\n\n optimizer = tf.train.AdamOptimizer(learning_rate)\n training_op = optimizer.minimize(loss)\n n_epochs = n_epochs\n\n init = tf.global_variables_initializer()\n\n with tf.Session() as sess:\n init.run()\n loss_control = []\n for epoch in range(n_epochs):\n print(\"Iteration \",epoch)\n iteration_loss = []\n for protein in X_train:\n _, loss_val = sess.run([training_op, loss], feed_dict={X: [protein]})\n iteration_loss.append(loss_val)\n loss_control.append(sum(iteration_loss)/float(len(X_train)))\n # Test on the same protein\n codings_val = hidden2.eval(feed_dict={X: X_train})\n\n return codings_val, loss_control\n\n\ndef reset_graph(seed=42):\n tf.reset_default_graph()\n tf.set_random_seed(seed)\n np.random.seed(seed)\n\ndef train_autoencoder(X_train, n_neurons, n_epochs,\n learning_rate = 0.01, l2_reg = 0.0005, seed=42,\n hidden_activation=tf.nn.elu,\n output_activation=tf.nn.elu):\n graph = tf.Graph()\n with graph.as_default():\n tf.set_random_seed(seed)\n\n n_inputs = X_train.shape[1]\n\n X = tf.placeholder(tf.float32, shape=[None, n_inputs])\n\n my_dense_layer = partial(\n tf.layers.dense,\n kernel_initializer=tf.contrib.layers.variance_scaling_initializer(),\n kernel_regularizer=tf.contrib.layers.l2_regularizer(l2_reg))\n\n hidden = my_dense_layer(X, n_neurons, activation=hidden_activation, name=\"hidden\")\n outputs = my_dense_layer(hidden, n_inputs, activation=output_activation, name=\"outputs\")\n\n reconstruction_loss = tf.reduce_mean(tf.square(outputs - X))\n\n reg_losses = tf.get_collection(tf.GraphKeys.REGULARIZATION_LOSSES)\n loss = tf.add_n([reconstruction_loss] + reg_losses)\n\n optimizer = tf.train.AdamOptimizer(learning_rate)\n training_op = optimizer.minimize(loss)\n\n init = tf.global_variables_initializer()\n\n with tf.Session(graph=graph) as sess:\n init.run()\n losses = []\n for epoch in range(n_epochs):\n for protein in X_train:\n #print(\"\\r{}%\".format(100 * iteration // n_batches), end=\"\")\n sys.stdout.flush()\n sess.run(training_op, feed_dict={X: [protein]})\n loss_train = reconstruction_loss.eval(feed_dict={X: [protein]})\n losses.append(loss_train)\n params = dict([(var.name, var.eval()) for var in tf.get_collection(tf.GraphKeys.TRAINABLE_VARIABLES)])\n hidden_val = hidden.eval(feed_dict={X: X_train})\n return hidden_val, params[\"hidden/kernel:0\"], params[\"hidden/bias:0\"], params[\"outputs/kernel:0\"], params[\"outputs/bias:0\"], losses\n \n \n"
},
{
"alpha_fraction": 0.6142019033432007,
"alphanum_fraction": 0.6291326284408569,
"avg_line_length": 33.94409942626953,
"blob_id": "cb9f313d50260297bec78bfed02444bde360d8ac",
"content_id": "d4815ecd5ccc9b15323aa8ebe8d036913ad31adf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11252,
"license_type": "no_license",
"max_line_length": 159,
"num_lines": 322,
"path": "/notebooks/pys/strategy1-filter64-50d-scaled.py",
"repo_name": "hacertilbec/Protein-Vectorization",
"src_encoding": "UTF-8",
"text": "from pdb_utils import *\n\nimport pickle\nimport numpy as np\nimport pandas as pd\nimport random\n\nimport tensorflow as tf\nfrom tensorflow.contrib.layers import fully_connected\nfrom functools import partial\nimport sys\n\nfrom Bio import PDB\nimport os\nimport cv2\n\nfrom sklearn.model_selection import train_test_split, GridSearchCV\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.model_selection import StratifiedShuffleSplit\nfrom sklearn.linear_model import LogisticRegression\nfrom sklearn.metrics import *\nimport time\n\ndef nice_time(start,end):\n hours, rem = divmod(end-start, 3600)\n minutes, seconds = divmod(rem, 60)\n print(\"Runtime: {:0>2}:{:0>2}:{:05.2f}\".format(int(hours),int(minutes),seconds))\n\ndef createDistanceMatrix2(structure,mean,std_dev,resize_strategy,resize_to,sample_size):\n coords_list = []\n model=structure[0]\n for chain in model.get_list():\n for residue in chain.get_list():\n try:\n coords = residue['CA'].coord\n coords_list.append(coords)\n except:\n continue\n distance_matrix = []\n for c in coords_list:\n coord_dist = []\n for c_ in coords_list:\n dist = np.linalg.norm(c-c_) # calculate distance between coordinates of CAs of residues\n coord_dist.append(dist)\n distance_matrix.append(coord_dist)\n print(np.array(distance_matrix))\n distance_matrix = (np.array(distance_matrix)-mean)/std_dev\n print(distance_matrix)\n # Resize protein_matrix\n if resize_strategy == False or len(distance_matrix) == resize_to[0]:\n return distance_matrix\n else:\n if resize_strategy == \"strategy1\":\n resized = cv2.resize(distance_matrix, (resize_to[0], resize_to[1]), interpolation=cv2.INTER_AREA)\n elif resize_strategy == \"strategy2\":\n if len(distance_matrix) > resize_to[0]:\n resized = sampling(distance_matrix, new_shape=resize_to,sample_size=sample_size)\n else:\n resized = padding(distance_matrix, new_shape=resize_to,sample_size=sample_size)\n elif resize_strategy == \"strategy3\":\n if len(distance_matrix) > resize_to[0]:\n resized = sampling_s3(distance_matrix, new_shape=resize_to)\n else:\n resized = padding_s3(distance_matrix, new_shape=resize_to)\n else:\n print(\"Not a valid strategy method. Use False, strategy1, strategy2 or strategy3.\")\n return\n return resized\n\n\n# get structure list and returns protein, distance matrix dictionary\ndef DistanceMatrixDict2(structures,mean,std_dev,resize_strategy=\"strategy1\", resize_to=(32,32), removeSymmetry=False,sample_size=None):\n if resize_strategy == \"strategy2\" and removeSymmetry == True:\n print(\"RemoveSymmetry parameter can not be used with strategy2\")\n return\n protein_matrix_dict = {}\n for protein in structures:\n protein_matrix = createDistanceMatrix2(protein,mean,std_dev,resize_strategy, resize_to,sample_size)\n if resize_strategy == \"strategy2\" or resize_strategy == \"strategy3\":\n try:\n protein_matrix[0].shape[1]\n for sample in enumerate(protein_matrix):\n key = protein.id + \"sample\" + str(sample[0])\n protein_matrix_dict[key] = sample[1].flatten()\n except:\n protein_matrix_dict[protein.id] = protein_matrix.flatten()\n else:\n if type(protein_matrix) == np.ndarray:\n if removeSymmetry == True:\n protein_matrix = RemoveSymmetry(protein_matrix)\n else:\n protein_matrix = protein_matrix.flatten()\n protein_matrix_dict[protein.id] = protein_matrix\n return protein_matrix_dict\n\n# Loading label dictionaries\nwith open('pickle files/fold_groups.pkl', 'rb') as f:\n fold_dict = pickle.load(f)\nwith open('pickle files/label_dict.pkl', 'rb') as f:\n label_dict = pickle.load(f)\nwith open('pickle files/test_labels.pkl', 'rb') as f:\n test_label_dict = pickle.load(f)\n\n\ntf.reset_default_graph()\ntf.set_random_seed(42)\n\nencoding_size = 50\nfilter_size = 64\n\ntrain_all_features = []\ntrain_all_pdb_names = []\n\nX = tf.placeholder(tf.float32, shape=[None, 2016])\nhidden = fully_connected(X, 50, activation_fn=tf.nn.relu)\noutputs = fully_connected(hidden, 2016, activation_fn=tf.nn.relu)\n\nreconstruction_loss = tf.reduce_sum(tf.square(outputs - X)) # MSE\n\noptimizer = tf.train.AdamOptimizer(0.0001)\ntraining_op = optimizer.minimize(reconstruction_loss)\n\ncodings = hidden # the output of the hidden layer provides the codings\n\ninit = tf.global_variables_initializer()\n\nsess = tf.InteractiveSession()\nsaver = tf.train.Saver()\nsess.run(init)\n\nall_values = []\nfor fold,pdb_list in list(fold_dict.items())[:10]:\n if len(pdb_list)<2:\n continue\n for pdb in pdb_list:\n try: \n pdb_path = os.path.join(\"PDBs\", pdb+\".pdb\")\n parser = PDB.PDBParser()\n structure = parser.get_structure(pdb, pdb_path)\n coords_list = []\n model=structure[0]\n for chain in model.get_list():\n for residue in chain.get_list():\n try:\n coords = residue['CA'].coord\n coords_list.append(coords)\n except:\n continue\n distance_matrix = []\n for c in coords_list:\n coord_dist = []\n for c_ in coords_list:\n dist = np.linalg.norm(c-c_) # calculate distance between coordinates of CAs of residues\n coord_dist.append(dist)\n distance_matrix.append(coord_dist)\n flatten = []\n row = 0\n for i in range(1, len(distance_matrix)):\n flatten += distance_matrix[row][i:]\n row+=1\n all_values+=flatten\n except:\n continue\n \nall_values = np.array(all_values)\nmean = np.mean(all_values)\nstd_dev = np.std(all_values)\n\n# Distance Matrices\ntrain_all_pdb_names, train_all_features = [],[]\n\nfor fold,pdb_list in list(fold_dict.items())[:10]:\n if len(pdb_list)<2:\n continue\n structures = []\n for pdb in pdb_list:\n try: \n pdb_path = os.path.join(\"PDBs\", pdb+\".pdb\")\n parser = PDB.PDBParser()\n structure = parser.get_structure(pdb, pdb_path)\n structures.append(structure)\n train_matrix = DistanceMatrixDict2(structures, mean, std_dev, resize_strategy=\"strategy1\", resize_to=(filter_size,filter_size),removeSymmetry=True)\n train_pdb_names, train_features = list(train_matrix.keys()), list(train_matrix.values())\n input_size = len(train_features[0])\n\n train_all_pdb_names += train_pdb_names\n train_all_features += train_features\n\n except:\n continue\nX_train, X_test, y_train, y_test = train_test_split(train_all_features, train_all_pdb_names, test_size=0.2,random_state=42)\nprint(\"Train size: %d\"%len(X_train))\nprint(\"Test size: %d\"%len(X_test))\n# Autoencoder\nfor iteration in range(100):\n print(\"Iteration %d\"%iteration)\n start,end = 0, 500\n for i in range(int(len(X_train)/500.)+1):\n batch = X_train[start:end]\n # Train model with the batch\n sess.run([training_op], feed_dict={X: np.array(batch)})\n\n start+=500\n end+=500\n \n\nprint(\"Training step end.\")\ncurdir = os.getcwd()\n# Save the variables to disk.\nsave_path = saver.save(sess, curdir+\"/models/model.ckpt\")\nprint(\"Model saved in path: %s\" % save_path)\n\n# Encode Train pdbs\nnew_train_features = codings.eval(feed_dict={X: np.array(X_train)},session=sess)\n# Encode Test pdbs\nnew_test_features = codings.eval(feed_dict={X: np.array(X_test)},session=sess)\n\n# Prepare Scop Test data\nscop_structures = []\nfor pdb in os.listdir(\"SCOP_Test/\"):\n pdb_path = os.path.join(\"SCOP_Test\", pdb)\n parser = PDB.PDBParser()\n structure = parser.get_structure(pdb, pdb_path)\n scop_structures.append(structure)\nscop_matrix = DistanceMatrixDict(scop_structures, resize_strategy=\"strategy1\", resize_to=(filter_size,filter_size),removeSymmetry=True)\ny_scop, scop_features = list(scop_matrix.keys()), list(scop_matrix.values())\n\n# Encode Scop Test pdbs\nscop_features = codings.eval(feed_dict={X: scop_features},session=sess)\n\n\n\n# Prepare train X and y\ntrain_feature_dict = {}\nfor i in enumerate(y_train):\n if \"sample\" in i[1]:\n pdb = i[1].split(\"sample\")[0]\n else:\n pdb = i[1]\n train_feature_dict.setdefault(pdb,[])\n train_feature_dict[pdb].append(new_train_features[i[0]])\n\n# Preparing test X and y\ntest_feature_dict = {}\nfor i in enumerate(y_test):\n if \"sample\" in i[1]:\n pdb = i[1].split(\"sample\")[0]\n else:\n pdb = i[1]\n test_feature_dict.setdefault(pdb,[])\n test_feature_dict[pdb].append(new_test_features[i[0]])\n\n# Preparing Scop test X and y\nscop_feature_dict = {}\nfor i in enumerate(y_scop):\n if \"sample\" in i[1]:\n pdb = i[1].split(\"sample\")[0]\n else:\n pdb = i[1]\n scop_feature_dict.setdefault(pdb,[])\n scop_feature_dict[pdb].append(scop_features[i[0]])\n\nX_train = []\ny_train = []\n\nfor pdb,vector in train_feature_dict.items():\n X_train.append(np.average(vector,axis=0))\n y_train.append(\".\".join(label_dict[pdb].split(\".\")[:2]))\n\nX_test = []\ny_test = []\n\nfor pdb,vector in test_feature_dict.items():\n X_test.append(np.average(vector,axis=0))\n y_test.append(\".\".join(label_dict[pdb.split(\".\")[0]].split(\".\")[:2]))\n\nX_scop = []\ny_scop = []\n\nfor pdb,vector in scop_feature_dict.items():\n X_scop.append(np.average(vector,axis=0))\n y_scop.append(\".\".join(test_label_dict[pdb.split(\".\")[0]].split(\".\")[:2]))\n\n\nuniques = list(set(y_train).union(set(y_test)).union(set(y_scop)))\ngroup2id = dict(zip(uniques, range(len(uniques))))\n\nX_train = np.array(X_train)\ny_train = np.array(list(map(lambda x: group2id[x], y_train)))\nX_test = np.array(X_test)\ny_test = np.array(list(map(lambda x: group2id[x], y_test)))\nX_scop = np.array(X_scop)\ny_scop = np.array(list(map(lambda x: group2id[x], y_scop)))\n\n\nprint(\"Random Forest starts\")\nsss1 = StratifiedShuffleSplit(n_splits=2, test_size=0.25, random_state=42)\nfor a, b in sss1.split(X_train, y_train):\n X_train_, y_train_ = X_train[a], y_train[a]\n X_validation, y_validation = X_train[b], y_train[b]\n\n # Hyperparameter Optimization with validation set\n params = {'max_depth':[3,4,5,6,7,8,9,10,15,20],\n 'criterion':('gini', 'entropy'),\n 'warm_start':(True,False),\n 'n_estimators': (10,50,100,200,500)}\n\n rf = RandomForestClassifier(random_state=42)\n clf = GridSearchCV(rf, params, cv=5, refit=True)\n clf.fit(X_validation, y_validation)\n\n # Training best model with train and validation set\n model = clf.best_estimator_\n model.fit(X_train, y_train)\n\n # Train and Test Accuracy Scores\n train_acc = model.score(X_train,y_train)\n test_acc = model.score(X_test,y_test)\n scop_acc = model.score(X_scop,y_scop)\n print(clf.best_params_)\n print((train_acc,test_acc,scop_acc))\n"
},
{
"alpha_fraction": 0.6904470920562744,
"alphanum_fraction": 0.7011971473693848,
"avg_line_length": 32.54917907714844,
"blob_id": "c95df1c143d13505fca64a7e8e098701cce5455d",
"content_id": "2b51fce982744acb1c265c70aabee0acff3f48c7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4093,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 122,
"path": "/notebooks/pys/encoder_train.py",
"repo_name": "hacertilbec/Protein-Vectorization",
"src_encoding": "UTF-8",
"text": "#from autoencoders import *\nfrom pdb_utils import *\nimport pickle\nimport numpy as np\nimport random\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib.layers import fully_connected\nfrom functools import partial\nimport sys\n\nfrom Bio import PDB\nimport numpy as np\nimport os\nimport cv2\n\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score\nfrom sklearn.metrics import *\n\nfrom keras.layers import Input, Dense\nfrom keras.models import Model\nfrom keras.callbacks import EarlyStopping, ModelCheckpoint, TensorBoard\nfrom keras import regularizers\nfrom keras import backend as K\nfrom keras.optimizers import Adam, Adadelta\nK.tensorflow_backend._get_available_gpus()\n\nimport matplotlib\n\nimport matplotlib.pyplot as plt\n\nfilter_size=64\nstrategy = \"strategy1\"\nbatch_size = 100\nnum_iters = 1000\ninput_size=2016\n\n\ndef build_model(inp_dim,encoding_dim,sparse=False):\n # this is our input placeholder\n input_img = Input(shape=(inp_dim,))\n # \"encoded\" is the encoded representation of the input\n if sparse==True:\n encoded = Dense(encoding_dim, activation='relu',activity_regularizer=regularizers.l1(10e-5))(input_img)\n else:\n encoded = Dense(encoding_dim, activation='relu')(input_img)\n # \"decoded\" is the lossy reconstruction of the input\n decoded = Dense(inp_dim, activation='sigmoid')(encoded)\n\n # this model maps an input to its reconstruction\n autoencoder = Model(input_img, decoded)\n\n # this model maps an input to its encoded representation\n encoder = Model(input_img, encoded)\n\n # create a placeholder for an encoded (32-dimensional) input\n encoded_input = Input(shape=(encoding_dim,))\n # retrieve the last layer of the autoencoder model\n decoder_layer = autoencoder.layers[-1]\n # create the decoder model\n decoder = Model(encoded_input, decoder_layer(encoded_input))\n optimizer = Adadelta(lr=0.001)\n autoencoder.compile(optimizer=optimizer,\n loss='categorical_crossentropy',\n metrics=['accuracy','mse'])\n autoencoder.summary()\n return encoder,decoder,autoencoder\n\n\nfold=1\ntrain_pdbs = []\nwith open(\"Folds/{n}_train.txt\".format(n=fold),\"r\") as f:\n for i in f.readlines():\n train_pdbs.append(i.strip(\"\\n\"))\nwith open(\"Folds/{n}_test.txt\".format(n=fold),\"r\") as f:\n for i in f.readlines():\n train_pdbs.append(i.strip(\"\\n\"))\n \ntrain_pdbs = train_pdbs\nprint(len(train_pdbs))\n\ntrain_features = []\nfor i in range(int(len(train_pdbs)/batch_size)+1): # BATCH\n structures = []\n for pdb in train_pdbs[i*batch_size: (i+1)*batch_size]: # EACH PDB IN THE BATCH\n if pdb == \".ipynb_checkpoints\":\n continue\n pdb_path = os.path.join(\"PDBs\", pdb)\n parser = PDB.PDBParser()\n structure = parser.get_structure(pdb, pdb_path)\n structures.append(structure)\n matrixdict = DistanceMatrixDict(structures, resize_strategy=strategy, resize_to=(filter_size,filter_size),removeSymmetry=True)\n pdbs, features = list(matrixdict.keys()), list(matrixdict.values())\n train_features+=features\n\n# TRAIN MODEL\nX_train = np.array(train_features)\ninp_dim = X_train.shape[1]\nenc_dim = 100\nencoder,decoder,autoencoder = build_model(inp_dim,enc_dim)\n# Set callback functions to early stop training and save the best model so far\ncallbacks = [EarlyStopping(monitor='val_loss', patience=2),\n ModelCheckpoint(filepath='best_model.h5', monitor='val_loss', save_best_only=True)]\n\nhist = autoencoder.fit(X_train, X_train,\n epochs=num_iters,\n batch_size=batch_size,\n callbacks=callbacks, # Early stopping\n shuffle=True,\n validation_split=0.3\n )\nencoder.save(\"encoder.h5\")\n# LOSS GRAPH\ntrain_loss = hist.history['loss']\nval_loss = hist.history['val_loss']\n\nfig, ax = plt.subplots()\nax.plot(range(0,len(train_loss)), train_loss, 'go-', linewidth=1, markersize=1,color=\"red\")\nax.plot(range(0,len(val_loss)), val_loss, 'go-', linewidth=1, markersize=1,color=\"blue\")\nplt.savefig(\"LOSS.png\")\n"
},
{
"alpha_fraction": 0.6017069816589355,
"alphanum_fraction": 0.6085032224655151,
"avg_line_length": 34.74576187133789,
"blob_id": "d97320b598711a9aea362b94f1f6a2ac1fbc37d4",
"content_id": "e455928fcb95f98cbbc3fb52a43e8689bcda008f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6327,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 177,
"path": "/notebooks/pys/optimized_classification.py",
"repo_name": "hacertilbec/Protein-Vectorization",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib.layers import fully_connected\nfrom functools import partial\nimport sys\n\nfrom Bio import PDB\nimport numpy as np\nimport os\nimport cv2\n\nimport matplotlib\nimport matplotlib.pyplot as plt\n\nimport pickle\n\n# Get and parse all pdb files in a folder\ndef parsePdbFiles(dir_path):\n structures = []\n files = os.listdir(dir_path)\n pdb_files = [(f, os.path.join(dir_path, f)) for f in files if f.endswith(\".pdb\")]\n\n for pdb, pdb_path in pdb_files:\n parser = PDB.PDBParser()\n structure = parser.get_structure(pdb, pdb_path)\n structures.append(structure)\n return structures\n\ndef CreateContactMap(structure,resize_to):\n coords_list = []\n for residue in structure.get_residues():\n try:\n coords = residue['CA'].coord\n coords_list.append(coords)\n except:\n continue\n contact_map = []\n for c in coords_list:\n coord_dist = []\n for c_ in coords_list:\n dist = np.linalg.norm(c-c_) # calculate distance between coordinates of CAs of residues\n coord_dist.append(dist)\n contact_map.append(coord_dist)\n # Resize protein_matrix\n try:\n resized = cv2.resize(np.array(contact_map), (resize_to[0], resize_to[1]), interpolation=cv2.INTER_AREA)\n except:\n resized = None\n return resized\n\n# Removes symmetry from the contact map\ndef RemoveSymmetry(matrix):\n flatten = []\n row = 0\n for i in range(1, len(matrix)):\n flatten += matrix[row][i:].tolist()\n row+=1\n return np.array(flatten)\n\n# get structure list and returns protein, contact map dictionary\ndef ProteinContactMapDict(structures, resize_to=(32,32), removeSymmetry=True):\n protein_matrix_dict = {}\n for protein in structures:\n protein_matrix = CreateContactMap(protein, resize_to)\n if type(protein_matrix) == np.ndarray:\n if removeSymmetry == True:\n protein_matrix = RemoveSymmetry(protein_matrix)\n else:\n protein_matrix = protein_matrix.flatten()\n protein_matrix_dict[protein.id] = protein_matrix\n return protein_matrix_dict\n\ndef pipeline(dir_path, batch_size, resizeto=64, n_hidden=500, n_iteration=100, learning_rate = 0.0001):\n\n pdbs = os.listdir(dir_path)\n n_pdbs = len(pdbs)\n print(\"Total number of pdbs: %d\" %n_pdbs)\n\n # Setting Linear Autoencoder parameters\n n_inputs = (resizeto**2/2)-(resizeto/2) # input is flatten version of input matrix\n n_hidden = n_hidden\n n_outputs = n_inputs\n\n learning_rate = learning_rate\n\n X = tf.placeholder(tf.float32, shape=[None, n_inputs])\n hidden = fully_connected(X, n_hidden, activation_fn=None)\n outputs = fully_connected(hidden, n_outputs, activation_fn=None)\n\n reconstruction_loss = tf.reduce_sum(tf.square(outputs - X)) # MSE\n\n optimizer = tf.train.AdamOptimizer(learning_rate)\n training_op = optimizer.minimize(reconstruction_loss)\n\n init = tf.global_variables_initializer()\n\n n_iterations = n_iteration # Number of iterations\n codings = hidden # the output of the hidden layer provides the codings\n\n print(\"images resized to: %dx%d\" %(resizeto,resizeto))\n print(\"input size: %d\" %n_inputs)\n print(\"hidden input size: %d\" %n_hidden)\n print(\"learning rate: %d\" %learning_rate)\n print(\"number of iterations: %d\" %n_iteration)\n\n # Train\n with tf.Session() as sess:\n init.run()\n loss = []\n for iteration in range(n_iterations):\n print(\"\\n--- Iteration %d ---\" %iteration)\n start=0\n end = batch_size\n iteration_loss = []\n for i in range(n_pdbs/batch_size+1):\n batch_pdbs = pdbs[start:end]\n print(\"%d - Parsing %d pdbs\" %(i, len(batch_pdbs)))\n start+=batch_size\n end+=batch_size\n\n # Constracting Pdb Structures\n #print(\"Constracting pdb structures, Generating Protein Contact Maps and Training\")\n structures = []\n pdb_files = [(f, os.path.join(dir_path, f)) for f in batch_pdbs if f.endswith(\".pdb\")]\n\n for pdb, pdb_path in pdb_files:\n parser = PDB.PDBParser()\n structure = parser.get_structure(pdb, pdb_path)\n structures.append(structure)\n\n # Generating Protein Contact Maps\n proteinmatrixdict = ProteinContactMapDict(structures, resize_to=(resizeto,resizeto), removeSymmetry=True)\n\n labels, features = proteinmatrixdict.keys(), proteinmatrixdict.values()\n\n _, loss_val = sess.run([training_op, reconstruction_loss], feed_dict={X: features}) # no labels (unsupervised)\n iteration_loss.append(loss_val)\n loss.append(sum(iteration_loss)/float(n_pdbs))\n print(\"---------- Training end ----------\\n\\n\")\n # LOSS GRAPH\n fig, ax = plt.subplots()\n ax.plot(range(0,len(loss)), loss, 'go-', linewidth=1, markersize=1)\n fig.savefig(\"loss.png\")\n\n # Test\n print(\"---------- Test starts ----------\")\n new_features = []\n start=0\n end = batch_size\n\n for i in range(n_pdbs/batch_size+1):\n batch_pdbs = pdbs[start:end]\n print(\"%d - Parsing %d pdbs\" %(i, len(batch_pdbs)))\n start+=batch_size\n end+=batch_size\n\n # Constracting Pdb Structures\n structures = []\n pdb_files = [(f, os.path.join(dir_path, f)) for f in batch_pdbs if f.endswith(\".pdb\")]\n\n for pdb, pdb_path in pdb_files:\n parser = PDB.PDBParser()\n structure = parser.get_structure(pdb, pdb_path)\n structures.append(structure)\n\n # Generating Protein Contact Maps\n proteinmatrixdict = ProteinContactMapDict(structures, resize_to=(resizeto,resizeto), removeSymmetry=True)\n\n labels, features = proteinmatrixdict.keys(), proteinmatrixdict.values()\n\n codings_val = codings.eval(feed_dict={X: features})\n new_features += (zip(labels, codings_val))\n\n with open(\"newnewfeatures.py\", \"wb\") as f:\n pickle.dump(dict(new_features), f)\n\npipeline(\"PDBs\",batch_size=100,n_iteration=100)\n"
},
{
"alpha_fraction": 0.6330543756484985,
"alphanum_fraction": 0.6462640166282654,
"avg_line_length": 38.827308654785156,
"blob_id": "3e4bd1600208157bdb46230f2c0766a28577e66f",
"content_id": "81e41ce7a1e09d89acca9872a053544fac3834a2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9917,
"license_type": "no_license",
"max_line_length": 165,
"num_lines": 249,
"path": "/notebooks/pys/knnclassifier.py",
"repo_name": "hacertilbec/Protein-Vectorization",
"src_encoding": "UTF-8",
"text": "#from autoencoders import *\nfrom pdb_utils import *\nfrom autoencoders import *\nimport pickle\nimport numpy as np\nimport random\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib.layers import fully_connected\nfrom functools import partial\nimport sys\n\nfrom Bio import PDB\nimport numpy as np\nimport os\nimport cv2\n\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.ensemble import RandomForestClassifier\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score\nfrom sklearn.metrics import *\n\nfilter_size=64\nstrategy = \"strategy1\"\nencoding_size = 100\nbatch_size = 100\nnum_iters = 100\ninput_size=2016\nsample_size=50\n\nwith open('pickle files/label_dict.pkl', 'rb') as f:\n label_dict = pickle.load(f)\nwith open('pickle files/test_labels.pkl', 'rb') as f:\n scop_label_dict = pickle.load(f)\n\n# SCOP TEST PDBs\nstructures = []\nfor pdb in os.listdir(\"SCOP_Test/\"):\n if not pdb.endswith(\".pdb\"):\n continue\n pdb_path = os.path.join(\"SCOP_Test\", pdb)\n parser = PDB.PDBParser()\n structure = parser.get_structure(pdb, pdb_path)\n structures.append(structure)\nif strategy == \"strategy1\":\n matrixdict = DistanceMatrixDict(structures, resize_strategy=strategy, resize_to=(filter_size,filter_size),removeSymmetry=True)\nelif strategy == \"strategy2\":\n matrixdict = DistanceMatrixDict(structures, resize_strategy=strategy, resize_to=(filter_size,filter_size),removeSymmetry=False, sample_size=sample_size) \nelse:\n matrixdict = DistanceMatrixDict(structures, resize_strategy=strategy, resize_to=(filter_size,filter_size),removeSymmetry=False)\n \nscop_pdb_samples, scop_features = list(matrixdict.keys()), list(matrixdict.values())\n\n\ntrain_acc_1,test_acc_1, scop_acc_1 = [],[],[]\ntrain_acc_5,test_acc_5, scop_acc_5 = [],[],[]\ntrain_acc_rf,test_acc_rf, scop_acc_rf = [],[],[]\nloss_all = []\n\nfor fold in range(1,11):\n train_pdbs = []\n with open(\"Folds/{n}_train.txt\".format(n=fold),\"r\") as f:\n for i in f.readlines():\n train_pdbs.append(i.strip(\"\\n\"))\n test_pdbs = []\n with open(\"Folds/{n}_test.txt\".format(n=fold),\"r\") as f:\n for i in f.readlines():\n test_pdbs.append(i.strip(\"\\n\"))\n train_pdbs = train_pdbs\n test_pdbs = test_pdbs\n\n print(len(train_pdbs))\n print(len(test_pdbs))\n\n tf.reset_default_graph()\n tf.set_random_seed(42)\n\n X = tf.placeholder(tf.float32, shape=[None, input_size])\n hidden = fully_connected(X, encoding_size, activation_fn=tf.nn.relu)\n outputs = fully_connected(hidden, input_size, activation_fn=tf.nn.softmax)\n\n reconstruction_loss = tf.reduce_sum(tf.square(outputs - X)) # MSE\n\n optimizer = tf.train.AdamOptimizer(0.0001)\n training_op = optimizer.minimize(reconstruction_loss)\n\n codings = hidden # the output of the hidden layer provides the codings\n\n init = tf.global_variables_initializer()\n\n sess = tf.InteractiveSession()\n saver = tf.train.Saver()\n sess.run(init)\n\n\n model_path = \"models/\"+strategy+str(filter_size)+str(encoding_size)+\".ckpt\"\n\n train_features, test_features = [],[]\n train_pdb_samples, test_pdb_samples = [],[]\n\n autoencoder = None\n for i in range(int(len(train_pdbs)/batch_size)+1): # BATCH\n structures = []\n for pdb in train_pdbs[i*batch_size: (i+1)*batch_size]: # EACH PDB IN THE BATCH\n if pdb == \".ipynb_checkpoints\":\n continue\n pdb_path = os.path.join(\"PDBs\", pdb)\n parser = PDB.PDBParser()\n structure = parser.get_structure(pdb, pdb_path)\n structures.append(structure)\n if strategy == \"strategy1\":\n matrixdict = DistanceMatrixDict(structures, resize_strategy=strategy, resize_to=(filter_size,filter_size),removeSymmetry=True)\n elif strategy == \"strategy2\":\n matrixdict = DistanceMatrixDict(structures, resize_strategy=strategy, resize_to=(filter_size,filter_size),removeSymmetry=False, sample_size=sample_size) \n else:\n matrixdict = DistanceMatrixDict(structures, resize_strategy=strategy, resize_to=(filter_size,filter_size),removeSymmetry=False)\n pdbs, features = list(matrixdict.keys()), list(matrixdict.values())\n\n train_pdb_samples+=pdbs\n train_features+=features\n input_size = len(features[0])\n\n # ITERATION\n for iteration in range(num_iters):\n for i in range(int(len(train_features)/batch_size)+1): # BATCH\n batch = train_features[i*batch_size: (i+1)*batch_size]\n sess.run([training_op], feed_dict={X: batch})\n\n for i in range(int(len(test_pdbs)/batch_size)+1): # BATCH\n structures = []\n for pdb in test_pdbs[i*batch_size: (i+1)*batch_size]: # EACH PDB IN THE BATCH\n if pdb == \".ipynb_checkpoints\":\n continue\n pdb_path = os.path.join(\"PDBs\", pdb)\n parser = PDB.PDBParser()\n structure = parser.get_structure(pdb, pdb_path)\n structures.append(structure)\n if strategy == \"strategy1\":\n matrixdict = DistanceMatrixDict(structures, resize_strategy=strategy, resize_to=(filter_size,filter_size),removeSymmetry=True)\n elif strategy == \"strategy2\":\n matrixdict = DistanceMatrixDict(structures, resize_strategy=strategy, resize_to=(filter_size,filter_size),removeSymmetry=False, sample_size=sample_size) \n else:\n matrixdict = DistanceMatrixDict(structures, resize_strategy=strategy, resize_to=(filter_size,filter_size),removeSymmetry=False)\n pdbs, features = list(matrixdict.keys()), list(matrixdict.values())\n test_pdb_samples+=pdbs\n test_features+=features\n\n print(\"number of train pdbs: {n}\".format(n=len(train_pdb_samples)))\n print(\"number of test pdbs: {n}\".format(n=len(test_pdb_samples)))\n # Embedding vectors of train and test set\n new_train_features = sess.run([hidden], feed_dict={X: train_features})[0]\n new_test_features = sess.run([hidden], feed_dict={X: test_features})[0]\n new_scop_features = sess.run([hidden], feed_dict={X: scop_features})[0]\n\n train_feature_dict = {}\n for i in enumerate(train_pdb_samples):\n if \"sample\" in i[1]:\n pdb = i[1].split(\"sample\")[0]\n else:\n pdb = i[1]\n train_feature_dict.setdefault(pdb,[])\n train_feature_dict[pdb].append(new_train_features[i[0]])\n\n test_feature_dict = {}\n for i in enumerate(test_pdb_samples):\n if \"sample\" in i[1]:\n pdb = i[1].split(\"sample\")[0]\n else:\n pdb = i[1]\n test_feature_dict.setdefault(pdb,[])\n test_feature_dict[pdb].append(new_test_features[i[0]])\n\n scop_feature_dict = {}\n for i in enumerate(scop_pdb_samples):\n if \"sample\" in i[1]:\n pdb = i[1].split(\"sample\")[0]\n else:\n pdb = i[1]\n scop_feature_dict.setdefault(pdb,[])\n scop_feature_dict[pdb].append(new_scop_features[i[0]])\n\n\n X_train = []\n y_train = []\n\n for pdb,vector in train_feature_dict.items():\n pdb = pdb.split(\".\")[0]\n X_train.append(np.average(vector,axis=0))\n y_train.append(\".\".join(label_dict[pdb].split(\".\")[:2]))\n\n X_test = []\n y_test = []\n\n for pdb,vector in test_feature_dict.items():\n pdb = pdb.split(\".\")[0]\n X_test.append(np.average(vector,axis=0))\n y_test.append(\".\".join(label_dict[pdb.split(\".\")[0]].split(\".\")[:2]))\n\n X_scop = []\n y_scop = []\n\n for pdb,vector in scop_feature_dict.items():\n pdb = pdb.split(\".\")[0]\n X_scop.append(np.average(vector,axis=0))\n y_scop.append(\".\".join(scop_label_dict[pdb.split(\".\")[0]].split(\".\")[:2]))\n\n\n uniques = list(set(y_train).union(set(y_test)).union(set(y_scop)) )\n group2id = dict(zip(uniques, range(len(uniques))))\n\n X_train = np.array(X_train)\n y_train = np.array(list(map(lambda x: group2id[x], y_train)))\n X_test = np.array(X_test)\n y_test = np.array(list(map(lambda x: group2id[x], y_test)))\n X_scop = np.array(X_scop)\n y_scop = np.array(list(map(lambda x: group2id[x], y_scop)))\n\n\n knn = KNeighborsClassifier(n_neighbors=1)\n knn.fit(X_train,y_train)\n train_acc_1.append(knn.score(X_train,y_train))\n test_acc_1.append(knn.score(X_test,y_test))\n scop_acc_1.append(knn.score(X_scop,y_scop))\n\n knn = KNeighborsClassifier(n_neighbors=5)\n knn.fit(X_train,y_train)\n train_acc_5.append(knn.score(X_train,y_train))\n test_acc_5.append(knn.score(X_test,y_test))\n scop_acc_5.append(knn.score(X_scop,y_scop))\n\n rf = RandomForestClassifier(max_depth=3, n_estimators=100)\n rf.fit(X_train,y_train)\n train_acc_rf.append(rf.score(X_train,y_train))\n test_acc_rf.append(rf.score(X_test,y_test))\n scop_acc_rf.append(rf.score(X_scop,y_scop))\n\n\nwith open(\"result_{s}_{f}_{e}.txt\".format(s=strategy,f=filter_size,e=encoding_size),\"w\") as f:\n f.write(\"strategy:{s}\\nfilter size:{f}\\nencoding size:{e}\\n\\n\".format(s=strategy,f=filter_size,e=encoding_size))\n f.write(\"10-fold train accuracy with knn(k=1):{tr}\\n\".format(tr=sum(train_acc_1)/len(train_acc_1) ))\n f.write(\"10-fold test accuracy with knn(k=1):{tr}\\n\".format(tr=sum(test_acc_1)/len(test_acc_1) ))\n f.write(\"10-fold SCOP accuracy with knn(k=1):{tr}\\n\\n\".format(tr=sum(scop_acc_1)/len(scop_acc_1) ))\n f.write(\"10-fold train accuracy with knn(k=5):{tr}\\n\".format(tr=sum(train_acc_5)/len(train_acc_5) ))\n f.write(\"10-fold test accuracy with knn(k=5):{tr}\\n\".format(tr=sum(test_acc_5)/len(test_acc_5) ))\n f.write(\"10-fold SCOP accuracy with knn(k=5):{tr}\\n\".format(tr=sum(scop_acc_5)/len(scop_acc_5) ))\n f.write(\"10-fold train accuracy with random forest:{tr}\\n\".format(tr=sum(train_acc_rf)/len(train_acc_rf) ))\n f.write(\"10-fold test accuracy with random forest:{tr}\\n\".format(tr=sum(test_acc_rf)/len(test_acc_rf) ))\n f.write(\"10-fold SCOP accuracy with random forest:{tr}\\n\".format(tr=sum(scop_acc_rf)/len(scop_acc_rf) ))\n"
},
{
"alpha_fraction": 0.6516159772872925,
"alphanum_fraction": 0.661596953868866,
"avg_line_length": 27.053333282470703,
"blob_id": "dff7bb5576e4d8dc7578866ed451594e1bbad3eb",
"content_id": "15540cbc8ffb7d776568386747996ffe6f00c007",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2104,
"license_type": "no_license",
"max_line_length": 134,
"num_lines": 75,
"path": "/notebooks/pys/mean_std.py",
"repo_name": "hacertilbec/Protein-Vectorization",
"src_encoding": "UTF-8",
"text": "#from autoencoders import *\nfrom pdb_utils import *\nfrom autoencoders import *\nimport pickle\nimport numpy as np\nimport random\n\nimport numpy as np\nimport tensorflow as tf\nfrom tensorflow.contrib.layers import fully_connected\nfrom functools import partial\nimport sys\n\nfrom Bio import PDB\nimport numpy as np\nimport os\nimport cv2\n\nfrom sklearn.neighbors import KNeighborsClassifier\nfrom sklearn.metrics import accuracy_score, precision_score, recall_score\nfrom sklearn.metrics import *\n\nfilter_size=64\nstrategy = \"strategy1\"\nencoding_size = 50\nbatch_size = 100\nnum_iters = 100\ninput_size=2016\n\n\n\ndef scale_features(features,mean,std_dev):\n return (np.array(features)-mean)/std_dev\n\n\nfor fold in range(1,2):\n train_pdbs = []\n with open(\"Folds/{n}_train.txt\".format(n=fold),\"r\") as f:\n for i in f.readlines():\n train_pdbs.append(i.strip(\"\\n\"))\n test_pdbs = []\n with open(\"Folds/{n}_test.txt\".format(n=fold),\"r\") as f:\n for i in f.readlines():\n test_pdbs.append(i.strip(\"\\n\"))\n\n print(len(train_pdbs))\n print(len(test_pdbs))\n\n train_features, test_features = [],[]\n train_pdb_samples, test_pdb_samples = [],[]\n\n\n for i in range(int(len(train_pdbs)/batch_size)+1): # BATCH\n structures = []\n for pdb in train_pdbs[i*batch_size: (i+1)*batch_size]: # EACH PDB IN THE BATCH\n if pdb == \".ipynb_checkpoints\":\n continue\n pdb_path = os.path.join(\"PDBs\", pdb)\n parser = PDB.PDBParser()\n structure = parser.get_structure(pdb, pdb_path)\n structures.append(structure)\n matrixdict = DistanceMatrixDict(structures, resize_strategy=strategy, resize_to=(filter_size,filter_size),removeSymmetry=True)\n pdbs, features = list(matrixdict.keys()), list(matrixdict.values())\n\n train_pdb_samples+=pdbs\n train_features+=features\n\n input_size = len(train_features[0])\n\n # SCALING\n train_features = np.array(train_features)\n mean = np.mean(train_features.flatten())\n std_dev = np.std(train_features.flatten())\n print(mean)\n print(std_dev)\n"
}
] | 11 |
ThanThoai/My_tool_label_dataset | https://github.com/ThanThoai/My_tool_label_dataset | 131960a8b1b8d909b03535e5b27782f155fad713 | 2e4694a68e542b650d28e61fd60a7a769f732c26 | aae6fe2bdeb65e7fbf38a8093fe804438d29aa1a | refs/heads/main | 2023-02-07T02:34:58.794715 | 2020-12-26T04:41:45 | 2020-12-26T04:41:45 | 319,657,418 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7478991746902466,
"alphanum_fraction": 0.756302535533905,
"avg_line_length": 28.75,
"blob_id": "9a4a5606e0a9ff18de38a2adfaa19e41f1228c08",
"content_id": "c3e9b5ab29be9e8c5b5e12da68243266f5be3c90",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 119,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 4,
"path": "/README.md",
"repo_name": "ThanThoai/My_tool_label_dataset",
"src_encoding": "UTF-8",
"text": "# My_tool_label_dataset\n Simple tools created to label data for graduation thesis project\n \n \n"
},
{
"alpha_fraction": 0.4103947877883911,
"alphanum_fraction": 0.41777902841567993,
"avg_line_length": 34.03980255126953,
"blob_id": "360ee640d0d9ec76d6f6ecedf79b959abe775f57",
"content_id": "1da5eee7e1f090b3cab87853b968083ce3c67fb8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7042,
"license_type": "no_license",
"max_line_length": 308,
"num_lines": 201,
"path": "/app.py",
"repo_name": "ThanThoai/My_tool_label_dataset",
"src_encoding": "UTF-8",
"text": "import dash\nimport dash_core_components as dcc\nimport dash_html_components as html\nimport pandas as pd\nimport plotly.express as px\nfrom skimage import io\nimport os\nfrom dash.dependencies import Input, Output, State\nimport json\n\nexternal_stylesheets = ['https://codepen.io/chriddyp/pen/bWLwgP.css']\n\napp = dash.Dash(__name__, external_stylesheets=external_stylesheets)\n\ndir_img = \"images/\"\nlist_img = [os.path.join(dir_img, i) for i in os.listdir(dir_img)]\ndir_anno = \"anno\"\njson_check_path = 'check.json'\n# print(len(dir_img))\nif not os.path.isdir(dir_anno):\n os.mkdir(dir_anno)\n\ndata = None\nif not os.path.isfile(json_check_path):\n with open(json_check_path, mode=\"w+\") as j:\n data = {}\n for img in list_img:\n result = {\n \"status\" : 0,\n \"num_ques\" : 0\n }\n img_name = img.split('/')[-1].split('.')[0]\n data[img_name] = result\n json.dump(data, j)\nelse:\n data = json.load(open(json_check_path, 'r'))\n\n\ndef refesh_img(list_img, data):\n list_img_checked = []\n for img in list_img:\n # print(img)\n img_name = img.split('/')[-1].split('.')[0]\n # print(img_name)\n if not int(data[img_name]['status']):\n list_img_checked.append(img)\n return list_img_checked\n\nlist_img_checked = refesh_img(list_img, data)\n\nimg_index = 0\nfig = px.imshow(io.imread(list_img_checked[img_index]), binary_backend=\"jpg\")\nTYPE_QUES = ['queryGlobal', 'verifyGlobal', 'chooseGlobal', 'queryAttr', 'verifyAttr', 'verifyAttrs', 'chooseAttr', 'exist', 'existRel', 'logicOr', 'logicAnd', 'queryObject', 'chooseObject', 'queryRel', 'verifyRel','chooseRel', 'chooseObjRel', 'compare', 'common', 'twoSame', 'twoDiff', 'allSame', 'allDiff']\n\napp.layout = html.Div(\n [\n html.Div(\n [ \n html.Div(\n [\n html.H2(\"Image Show:\"),\n dcc.Graph(\n id = \"div-image\",\n figure = fig,\n ),\n html.Div(\n id = \"div-info\", \n children = \"\", \n style = { \n 'margin-left': '550px',\n 'margin-bottom': '10px',\n 'verticalAlign': 'middle'\n }\n )\n ]\n ),\n html.Div(\n [\n html.Button(\"Prev\", id = \"btn-prev\", n_clicks = 0),\n html.Button(\"Next\", id = \"btn-next\", n_clicks = 0),\n ],\n style = { \n 'margin-left': '550px',\n 'margin-bottom': '10px',\n 'verticalAlign': 'middle'\n }\n )\n ]\n ),\n html.Div(\n [ \n html.Div(\n [\n html.H5(\"Question type:\"),\n dcc.Dropdown(\n id = \"dp-ques\", \n options = [{\"label\" : i, \"value\" : i} for i in TYPE_QUES],\n style = {\n 'width': '220px',\n 'font-size': '90%',\n 'height': '40px',\n }\n ),\n html.H5(\"Question: \"),\n # html.Br(),\n dcc.Input(id = \"ip-ques\", type = \"text\"),\n html.H5(\"Answer: \"),\n # html.Br(),\n dcc.Input(id = \"ip-ans\", type = \"text\"),\n ]\n ),\n html.Div(\n [\n html.Button(\"Save\", id = \"btn-save\", n_clicks = 0),\n ],\n style = { \n 'margin-left': '550px',\n 'margin-bottom': '10px',\n 'verticalAlign': 'middle'\n }\n )\n ]\n )\n ]\n)\n\[email protected](\n Output(\"div-image\", \"figure\"),\n Input(\"btn-prev\", \"n_clicks\"),\n Input(\"btn-next\", \"n_clicks\")\n)\ndef updateimg(prev_clicks, next_clicks):\n global img_index\n global list_img_checked\n global data\n changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]\n if \"btn-prev\" in changed_id:\n if img_index > 0:\n img_index -= 1\n elif \"btn-next\" in changed_id:\n if img_index < len(list_img_checked) - 1:\n img_index += 1\n fig = px.imshow(io.imread(list_img_checked[img_index]), binary_backend=\"jpg\")\n return fig\n\n\[email protected](\n Output(\"div-info\", \"children\"),\n Input(\"btn-save\", \"n_clicks\"),\n Input(\"dp-ques\", \"value\"),\n Input(\"ip-ques\", \"value\"),\n Input(\"ip-ans\", \"value\")\n)\ndef save(btn_save, type_ques, ques, ans):\n global data\n global img_index\n global list_img_checked\n changed_id = [p['prop_id'] for p in dash.callback_context.triggered][0]\n if \"btn-save\" in changed_id:\n if len(ques) * len(ans) > 0:\n img_name = list_img_checked[img_index].split(\"/\")[-1].split(\".\")[0]\n anno = None\n if not os.path.isfile(os.path.join(dir_anno, img_name + \".json\")):\n with open(os.path.join(dir_anno, img_name + \".json\"), 'w+') as f:\n anno = {\n \"id\" : img_name,\n \"result\" : [],\n \"num_ques\" : 1,\n }\n anno[\"result\"].append({\n \"question\" : ques,\n \"answer\" : ans,\n \"type\" : type_ques\n })\n json.dump(anno, f)\n data[img_name][\"num_ques\"] += 1\n return \"Image has 1 questions!!!\"\n else:\n anno = json.load(open(os.path.join(dir_anno, img_name + \".json\"), 'r'))\n if img_name == anno[\"id\"]:\n anno[\"result\"].append({\n \"question\" : ques,\n \"answer\" : ans,\n \"type\" : type_ques\n })\n anno[\"num_ques\"] += 1\n json.dump(anno, open(os.path.join(dir_anno, img_name + \".json\"), 'w+'))\n data[img_name][\"num_ques\"] += 1\n if data[img_name][\"num_ques\"] == 5:\n data[img_name][\"status\"] = 1\n json.dump(data, open(json_check_path, 'w+'))\n list_img_checked = refesh_img(list_img_checked, data)\n return \"Image has %d question!!!\" %(int(anno[\"num_ques\"]))\n else:\n return \"ERROR!!\"\n\n \n \n\nif __name__ == '__main__':\n app.run_server(debug=False)"
}
] | 2 |
vivi-and-tea/CafeAPI | https://github.com/vivi-and-tea/CafeAPI | 00ca03ccaca16c4bba69e1c04cc5d3e67869cbc7 | 1498bd9cb0d70db1d4f36a8f5d367b27d0a433a0 | ee35b4fbcc2d976b19e0412bc1262dadf1f1d788 | refs/heads/master | 2023-07-02T07:05:53.763378 | 2021-07-28T12:51:42 | 2021-07-28T12:51:42 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6324101090431213,
"alphanum_fraction": 0.6367833018302917,
"avg_line_length": 29.264705657958984,
"blob_id": "3861a61762a407bb948efca11b4880bb21933dec",
"content_id": "e971598d2003915da54e5d2cc227aa3f6e86155f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4116,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 136,
"path": "/main.py",
"repo_name": "vivi-and-tea/CafeAPI",
"src_encoding": "UTF-8",
"text": "from flask import Flask, jsonify, render_template, request\nfrom flask_sqlalchemy import SQLAlchemy\nfrom sqlalchemy_serializer import SerializerMixin\nimport random\n\n\napp = Flask(__name__)\n\n##Connect to Database\napp.config['SQLALCHEMY_DATABASE_URI'] = 'sqlite:///cafes.db'\napp.config['SQLALCHEMY_TRACK_MODIFICATIONS'] = False\ndb = SQLAlchemy(app)\n\n\n##Cafe TABLE Configuration\nclass Cafe(db.Model, SerializerMixin):\n id = db.Column(db.Integer, primary_key=True)\n name = db.Column(db.String(250), unique=True, nullable=False)\n map_url = db.Column(db.String(500), nullable=False)\n img_url = db.Column(db.String(500), nullable=False)\n location = db.Column(db.String(250), nullable=False)\n seats = db.Column(db.String(250), nullable=False)\n has_toilet = db.Column(db.Boolean, nullable=False)\n has_wifi = db.Column(db.Boolean, nullable=False)\n has_sockets = db.Column(db.Boolean, nullable=False)\n can_take_calls = db.Column(db.Boolean, nullable=False)\n coffee_price = db.Column(db.String(250), nullable=True)\n\n\[email protected](\"/\")\ndef home():\n return render_template(\"index.html\")\n\[email protected](\"/random\", methods=[\"GET\"]) ## GET is actually allowed automatically on all routes, but just for study purposes..\ndef random_cafe():\n cafes = db.session.query(Cafe).all()\n random_cafe = random.choice(cafes)\n print(random_cafe.name)\n return jsonify(\n id=random_cafe.id,\n name = random_cafe.name,\n map_url = random_cafe.map_url,\n img_url = random_cafe.img_url,\n location = random_cafe.location,\n seats = random_cafe.seats,\n has_toilet = random_cafe.has_toilet,\n has_wifi = random_cafe.has_wifi,\n has_sockets = random_cafe.has_sockets,\n can_take_calls = random_cafe.can_take_calls,\n coffee_price = random_cafe.coffee_price\n )\n\[email protected](\"/all\", methods=[\"GET\"])\ndef get_all_cafes():\n cafes = db.session.query(Cafe).all()\n\n #Creating a dictionary from all cafe data.\n all_cafes = [{'id': cafe.id,\n 'name': cafe.name,\n 'map_url': cafe.map_url,\n 'img_url':cafe.img_url,\n 'location': cafe.location,\n 'seats': cafe.seats,\n 'has_toilet': cafe.has_toilet,\n 'has_wifi': cafe.has_wifi,\n 'has_sockets': cafe.has_sockets,\n 'can_take_calls': cafe.can_take_calls,\n 'coffee_price': cafe.coffee_price}\n for cafe in cafes]\n\n return jsonify(all_cafes)\n\[email protected](\"/search\", methods=[\"GET\"])\ndef search_location():\n loc = request.args.get('loc')\n cafe = db.session.query(Cafe).filter_by(location=loc).first()\n if cafe:\n cafe = {'id': cafe.id,\n 'name': cafe.name,\n 'map_url': cafe.map_url,\n 'img_url': cafe.img_url,\n 'location': cafe.location,\n 'seats': cafe.seats,\n 'has_toilet': cafe.has_toilet,\n 'has_wifi': cafe.has_wifi,\n 'has_sockets': cafe.has_sockets,\n 'can_take_calls': cafe.can_take_calls,\n 'coffee_price': cafe.coffee_price}\n\n return jsonify(cafe=cafe)\n return jsonify(error={'Not Found': f'We were unable to find a cafe in {loc}.for '})\n\n\[email protected](\"/add\", methods=[\"POST\", \"GET\"])\ndef post_new_cafe():\n new_cafe = Cafe(\n name=request.form.get(\"name\"),\n map_url=request.form.get(\"map_url\"),\n img_url=request.form.get(\"img_url\"),\n location=request.form.get(\"loc\"),\n has_sockets=bool(request.form.get(\"sockets\")),\n has_toilet=bool(request.form.get(\"toilet\")),\n has_wifi=bool(request.form.get(\"wifi\")),\n can_take_calls=bool(request.form.get(\"calls\")),\n seats=request.form.get(\"seats\"),\n coffee_price=request.form.get(\"coffee_price\"),\n )\n db.session.add(new_cafe)\n db.session.commit()\n return jsonify(response={\"success\": \"Successfully added the new cafe.\"})\n\[email protected](\"/update-price/<int:cafe_id>\", methods=[\"PATCH\"])\ndef update_price(cafe_id):\n price = request.args.get('price')\n\n\n\n\n\n\n\n\n\n\n\n## HTTP GET - Read Record\n\n## HTTP POST - Create Record\n\n## HTTP PUT/PATCH - Update Record\n\n## HTTP DELETE - Delete Record\n\n\nif __name__ == '__main__':\n app.run(debug=True)\n"
}
] | 1 |
Thangarajsubramani/Topwords | https://github.com/Thangarajsubramani/Topwords | 36f210280e56ffd448cdc137f7a1f87a9260df92 | 361366169a834c7b6abd0c5a14cf09f03076e42d | 38d9c8801aaf48262507bd436be9a4bcfb116441 | refs/heads/master | 2020-07-05T21:30:47.449554 | 2017-03-10T21:33:24 | 2017-03-10T21:33:24 | 73,979,265 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5489715337753296,
"alphanum_fraction": 0.5568723678588867,
"avg_line_length": 30.919282913208008,
"blob_id": "aea1fbf11bae2af0c189d629ea43d560a3b69551",
"content_id": "edd241e4704f24f32105caf687fd53449267f3d8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7341,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 223,
"path": "/count_word.py",
"repo_name": "Thangarajsubramani/Topwords",
"src_encoding": "UTF-8",
"text": "import json\r\nimport re\r\nimport collections\r\nfrom threading import *\r\nfrom Queue import Queue\r\nimport logging\r\nfrom time import time\r\nimport zipfile\r\nimport os\r\nimport shutil\r\nimport web\r\nimport socket\r\nimport tarfile\r\n\r\nurls = ('/', 'Index',\r\n '/upload', 'Upload',)\r\n\r\nlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\r\nlogging.getLogger('requests').setLevel(logging.CRITICAL)\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\nclass Index:\r\n \"\"\"\r\n @GET method : return Web server Index\"\"\"\r\n def __init__(self):\r\n pass\r\n\r\n def GET(self):\r\n logging.info(\"Index Requested\")\r\n return \"Sample WSGI APP\"\r\n\r\n\r\nclass Upload:\r\n \"\"\"\r\n @POST method : return top 10 words\"\"\"\r\n def __init__(self):\r\n pass\r\n\r\n def POST(self):\r\n x = web.input(data={})\r\n try:\r\n\r\n file_name = x.data.filename\r\n except AttributeError:\r\n data = {'error':'Use keyword data=@filepath as parameter to specify file'}\r\n logging.error(data['error'])\r\n raise web.HTTPError('400 Bad request', {'Content-Type': 'application/json'}, data)\r\n\r\n file_ext = os.path.splitext(file_name)[1]\r\n\r\n if file_ext not in ('.zip', '.gz', '.tgz', '.bz2', '.tbz', '.tar'):\r\n data = {'error': 'File format not supported!!!'}\r\n raise web.HTTPError('400 Bad request', {'Content-Type': 'application/json'}, data)\r\n\r\n with open(x.data.filename,'wb') as saved:\r\n shutil.copyfileobj(x['data'].file, saved)\r\n\r\n cwd = os.path.dirname(__file__)\r\n path = os.path.join(cwd, file_name)\r\n logging.info(\"File Path:\" + path)\r\n if os.path.exists(path):\r\n logging.info(\"File saved successfully\")\r\n return main(path)\r\n else:\r\n logging.error(\"File not saved\")\r\n headers = {'Content-Type': 'application/json'}\r\n data = {'error': \"File not saved\"}\r\n raise web.HTTPError('400 Bad request', headers, data)\r\n\r\n\r\nclass MyApp(web.application):\r\n \"\"\"\r\n Override the default method of web.application to take specific Host address, Port\r\n \"\"\"\r\n def run(self, server_address=('0.0.0.0', 8080), *middleware):\r\n func = self.wsgifunc(*middleware)\r\n return web.httpserver.runsimple(func, server_address)\r\n\r\n\r\ndef parse_file(filename):\r\n # @param: filename\r\n # parse the text file and extract the words\r\n words_list = []\r\n with open(filename, 'r') as f_handle:\r\n line = f_handle.read()\r\n p = re.compile('\\w+', re.M)\r\n # lists = p.findall('drummers0?drumming#11\\npipers$piping,y10&sorry lords-aleaping000 sorry 1')\r\n words_list.extend(p.findall(line.lower()))\r\n if words_list:\r\n return words_list\r\n else:\r\n return None\r\n\r\n\r\nclass ParseWorker(Thread):\r\n def __init__(self, queue, comp_words_list=None):\r\n Thread.__init__(self)\r\n self.queue = queue\r\n self.w = comp_words_list\r\n\r\n def run(self):\r\n\r\n while True:\r\n\r\n # Get the work from the queue\r\n file_name = self.queue.get()\r\n logging.info('%s : Parses %s', currentThread().getName(), os.path.basename(file_name))\r\n words = parse_file(file_name)\r\n if words is not None:\r\n self.w.extend(words)\r\n self.queue.task_done()\r\n\r\n\r\ndef main(path):\r\n\r\n # Create a queue to communicate with the worker threads\r\n ts = time()\r\n queue = Queue()\r\n words_list = []\r\n\r\n try:\r\n files = extract_zip(path)\r\n except Exception as e:\r\n logging.error(e.message)\r\n #raise e.message\r\n\r\n if not files:\r\n logging.warning(\"Does not contains any files to process:\")\r\n return json.dumps({'msg': \"Uploaded Archive does not contains any file to process\"}, indent=1)\r\n\r\n # Create N=3 worker threads\r\n for x in range(3):\r\n worker = ParseWorker(queue, words_list)\r\n # Setting daemon to True will let the main thread exit even though the workers are blocking\r\n worker.daemon = True\r\n worker.start()\r\n # Put the tasks into the queue\r\n\r\n for f in files:\r\n logging.info('Queueing {}'.format(os.path.basename(f)))\r\n queue.put(f)\r\n # Causes the main thread to wait for the queue to finish processing all the tasks\r\n queue.join()\r\n logging.info('Took {}'.format(time() - ts))\r\n dir_path = os.path.dirname(path)\r\n base_name = os.path.splitext(path)[0]\r\n extract_path = os.path.join(dir_path, base_name)\r\n\r\n if os.path.exists(extract_path):\r\n shutil.rmtree(extract_path)\r\n logging.info(\"Removed extracted temporary files to read!!!\")\r\n\r\n if not words_list:\r\n return json.dumps({'msg': \"No words available in the file present under uploaded zip\"}, indent=1)\r\n # print words_list\r\n wordcount = {}\r\n for word in words_list:\r\n\r\n if wordcount.get(word, None):\r\n\r\n wordcount[word] += 1\r\n else:\r\n wordcount[word] = 1\r\n\r\n # print wordcount\r\n top_words = sorted(wordcount.items(), key=lambda item: item[1], reverse=True)\r\n # print top_words\r\n return json.dumps({'Top_words': collections.OrderedDict(top_words[:10])}, indent=1,separators=(',', ': '))\r\n\r\n\r\ndef extract_zip(path_zip):\r\n\r\n # @param: Archive path\r\n if not zipfile.is_zipfile(path_zip) and not tarfile.is_tarfile(path_zip):\r\n raise \"Please upload correct zip file\"\r\n\r\n dir_path = os.path.dirname(path_zip)\r\n base_name = os.path.splitext(path_zip)[0]\r\n ext = os.path.splitext(path_zip)[1]\r\n\r\n if path_zip.endswith('.zip'):\r\n opener, mode = zipfile.ZipFile, 'r'\r\n elif path_zip.endswith('.tar'):\r\n opener, mode = tarfile.open, 'r:'\r\n elif path_zip.endswith('.tar.gz') or path_zip.endswith('.tgz'):\r\n opener, mode = tarfile.open, 'r:gz'\r\n elif path_zip.endswith('.tar.bz2') or path_zip.endswith('.tbz'):\r\n opener, mode = tarfile.open, 'r:bz2'\r\n else:\r\n raise ValueError, \"Could not extract `%s` as no appropriate extractor is found\" % ext\r\n\r\n extract_path = os.path.join(dir_path, base_name)\r\n\r\n with opener(path_zip, mode) as zip_ref:\r\n\r\n # namelist = zip_ref.namelist()\r\n zip_ref.extractall(extract_path)\r\n\r\n if os.path.exists(extract_path):\r\n\r\n logging.info('Archive File extracted to process')\r\n else:\r\n raise \"Failed: File archive extraction\"\r\n\r\n file_paths = []\r\n for root, dirs, files in os.walk(extract_path):\r\n for f in files:\r\n\r\n file_paths.append(os.path.join(root, f))\r\n\r\n return file_paths\r\n\r\n\r\nif __name__ == '__main__':\r\n\r\n app = MyApp(urls, globals())\r\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n s.connect((\"gmail.com\", 80))\r\n host_ip = s.getsockname()[0]\r\n s.close()\r\n logging.info(\"WSGI server started:\" + str((host_ip, 50026)))\r\n app.run(('localhost', 50026))\r\n"
},
{
"alpha_fraction": 0.5489549040794373,
"alphanum_fraction": 0.5547304749488831,
"avg_line_length": 34.369998931884766,
"blob_id": "154433d9abfb64faacdb7dedb2fa3e5c5154b7c3",
"content_id": "bcecac8bbdf3bd95faf9033dc21cfc58ab3ada80",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7272,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 200,
"path": "/top_count.py",
"repo_name": "Thangarajsubramani/Topwords",
"src_encoding": "UTF-8",
"text": "import json\r\nimport re\r\nimport collections\r\nfrom threading import *\r\nfrom Queue import Queue\r\nimport logging\r\nfrom time import time\r\nimport zipfile\r\nimport os\r\nimport shutil\r\nimport socket\r\nimport tarfile\r\nfrom bottle import route, request, static_file, run,response\r\n\r\nlogging.basicConfig(level=logging.DEBUG, format='%(asctime)s - %(name)s - %(levelname)s - %(message)s')\r\nlogging.getLogger('requests').setLevel(logging.CRITICAL)\r\nlogger = logging.getLogger(__name__)\r\n\r\n\r\n@route('/')\r\ndef root():\r\n \"\"\"\r\n @GET HTTP method : return Web server Index\"\"\"\r\n return \"Sample WSGI APP\"\r\n\r\n\r\n@route('/upload', method='POST')\r\ndef do_upload():\r\n\r\n \"\"\"\r\n @POST HTTP method: return top10 words\"\"\"\r\n data = request.files.keys()[0]\r\n upload = request.files.get(data)\r\n name, file_ext = os.path.splitext(upload.filename)\r\n if file_ext not in ('.zip', '.gz', '.tgz', '.bz2', '.tbz', '.tar'):\r\n response.status = 400\r\n response.content_type = 'application/json'\r\n data = {'error': 'file format not supported'}\r\n logger.error(data['error'])\r\n return json.dumps(data)\r\n cwd = os.path.dirname(__file__)\r\n save_path = cwd\r\n\r\n file_path = \"{path}/{file}\".format(path=save_path, file=upload.filename)\r\n logger.info(file_path)\r\n\r\n try:\r\n upload.save(file_path)\r\n except IOError as e:\r\n logging.error(e)\r\n\r\n if os.path.exists(file_path):\r\n logging.info(\"File successfully saved to '{0}'.\".format(save_path))\r\n return main(file_path)\r\n else:\r\n logging.error(\"File not saved\")\r\n response.status = 400\r\n response.content_type = 'application/json'\r\n data = {'error': \"File not saved\"}\r\n return json.dumps(data)\r\n\r\n\r\ndef parse_file(filename):\r\n # @param: filename\r\n # parse the text file and extract the words\r\n words_list = []\r\n with open(filename, 'r') as f_handle:\r\n line = f_handle.read()\r\n p = re.compile('\\w+', re.M)\r\n # lists = p.findall('drummers0?drumming#11\\npipers$piping,y10&sorry lords-aleaping000 sorry 1')\r\n words_list.extend(p.findall(line.lower()))\r\n if words_list:\r\n return words_list\r\n else:\r\n return None\r\n\r\n\r\nclass ParseWorker(Thread):\r\n def __init__(self, queue, comp_words_list=None):\r\n Thread.__init__(self)\r\n self.queue = queue\r\n self.w = comp_words_list\r\n\r\n def run(self):\r\n\r\n while True:\r\n # Get the work from the queue\r\n file_name = self.queue.get()\r\n logging.info('%s : Parses %s', currentThread().getName(), os.path.basename(file_name))\r\n words = parse_file(file_name)\r\n wordcount = {}\r\n if words is not None:\r\n for word in words:\r\n if wordcount.get(word, None):\r\n wordcount[word] += 1\r\n else:\r\n wordcount[word] = 1\r\n self.w.extend(wordcount.items())\r\n self.queue.task_done()\r\n\r\n\r\ndef main(path):\r\n\r\n # Create a queue to communicate with the worker threads\r\n ts = time()\r\n queue = Queue()\r\n words_list = []\r\n try:\r\n files = extract_zip(path)\r\n except Exception as e:\r\n logging.error(e)\r\n raise Exception(e)\r\n if not files:\r\n logging.warning(\"Does not contains any files to process:\")\r\n return json.dumps({'msg': \"Uploaded Archive does not contains any file to process\"}, indent=1)\r\n\r\n # Create N=3 worker threads\r\n for x in range(3):\r\n worker = ParseWorker(queue, words_list)\r\n # Setting daemon to True will let the main thread exit even though the workers are blocking\r\n worker.daemon = True\r\n worker.start()\r\n # Put the tasks into the queue\r\n for f in files:\r\n logger.info('Queueing {}'.format(os.path.basename(f)))\r\n queue.put(f)\r\n # Causes the main thread to wait for the queue to finish processing all the tasks\r\n queue.join()\r\n logging.info('Took {}'.format(time() - ts))\r\n dir_path = os.path.dirname(path)\r\n base_name = os.path.splitext(path)[0]\r\n extract_path = os.path.join(dir_path, base_name)\r\n if os.path.exists(extract_path):\r\n try:\r\n\r\n shutil.rmtree(extract_path)\r\n logging.info(\"Removed extracted temporary files to read!!!\")\r\n except Exception, e:\r\n logging.error(e)\r\n if os.path.exists(path):\r\n os.remove(path)\r\n logging.info(\"Removed the uploaded file\")\r\n if not words_list:\r\n return json.dumps({'msg': \"No words available in the file present under uploaded zip\"}, indent=1)\r\n # print words_list\r\n wordcount = {}\r\n for word, count in words_list:\r\n if wordcount.get(word, None):\r\n wordcount[word] += count\r\n else:\r\n wordcount[word] = count\r\n top_words = sorted(wordcount.items(), key=lambda item: item[1], reverse=True)\r\n # response.content_type = 'application/json'\r\n return json.dumps({'Top_words': collections.OrderedDict(top_words[:10])}, indent=1,separators=(',', ': '))\r\n\r\n\r\ndef extract_zip(path_zip):\r\n # @param: Archive path\r\n if not zipfile.is_zipfile(path_zip) and not tarfile.is_tarfile(path_zip):\r\n raise \"Please upload correct zip file\"\r\n dir_path = os.path.dirname(path_zip)\r\n base_name = os.path.splitext(path_zip)[0]\r\n ext = os.path.splitext(path_zip)[1]\r\n\r\n if path_zip.endswith('.zip'):\r\n opener, mode = zipfile.ZipFile, 'r'\r\n elif path_zip.endswith('.tar'):\r\n opener, mode = tarfile.open, 'r:'\r\n elif path_zip.endswith('.tar.gz') or path_zip.endswith('.tgz'):\r\n opener, mode = tarfile.open, 'r:gz'\r\n elif path_zip.endswith('.tar.bz2') or path_zip.endswith('.tbz'):\r\n opener, mode = tarfile.open, 'r:bz2'\r\n else:\r\n raise ValueError, \"Could not extract `%s` as no appropriate extractor is found\" % ext\r\n extract_path = os.path.join(dir_path, base_name)\r\n with opener(path_zip, mode) as zip_ref:\r\n # namelist = zip_ref.namelist()\r\n if not os.path.exists(extract_path):\r\n zip_ref.extractall(extract_path)\r\n elif os.path.exists(extract_path):\r\n logging.info('Archive File extracted to process')\r\n else:\r\n raise \"Failed: File archive extraction\"\r\n\r\n file_paths = []\r\n for root, dirs, files in os.walk(extract_path):\r\n for f in files:\r\n file_paths.append(os.path.join(root, f))\r\n return file_paths\r\n\r\nif __name__ == '__main__':\r\n try:\r\n s = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n s.connect((\"netapp.com\", 80))\r\n host_ip = s.getsockname()[0]\r\n s.close()\r\n except Exception as e:\r\n logging.error(e)\r\n host_ip = socket.gethostbyname(socket.gethostname())\r\n run(host=host_ip, port=8089)"
},
{
"alpha_fraction": 0.7402377128601074,
"alphanum_fraction": 0.8183361887931824,
"avg_line_length": 33.64706039428711,
"blob_id": "b471fdea82ad0b128bc97b3deef07ddcdfd3181a",
"content_id": "bc7124029de5cac0edc3b2023f2e169094517a6c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 589,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 17,
"path": "/README.md",
"repo_name": "Thangarajsubramani/Topwords",
"src_encoding": "UTF-8",
"text": "# Topwords\n\nDependencies:\n\nInstall the web.py light MVC framework python Bindings.\n\n1.http://webpy.org/static/web.py-0.38.tar.gz\n\n2. Extract and install - python setup.py install or use web folder in the directory.\n\nInput: file1.txt\n\ndrummers0?drumming#11\\npipers$piping,y10&sorry lords-aleaping000 sorry\ndrummers0?drumming#11\\npipers$piping,y10&sorry lords-aleaping000 sorry\ndrummers0?drumming#11\\npipers$piping,y10&sorry lords-aleaping000 sorry\ndrummers0?drumming#11\\npipers$piping,y10&sorry lords-aleaping000 sorry\ndrummers0?drumming#11\\npipers$piping,y10&sorry lords-aleaping000 sorry\n"
}
] | 3 |
schulzjona/CaesarChiffre | https://github.com/schulzjona/CaesarChiffre | 7b3bfc433dac92bd3c26424ffd7a6a3feb9f80c5 | 02de37b71ee3c66aab34f483e51456a868f9a71a | 6e456230bbbdd08ea676c417406faffb99927865 | refs/heads/master | 2020-09-26T00:16:28.772697 | 2019-12-05T14:39:49 | 2019-12-05T14:39:49 | 226,121,607 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7200000286102295,
"alphanum_fraction": 0.7400000095367432,
"avg_line_length": 11.5,
"blob_id": "674adec9ecd71274f87912fbe8bb344f06a3ddf4",
"content_id": "5dc6a8d35d90435114e0e590c75a0ace03343ecc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 50,
"license_type": "no_license",
"max_line_length": 22,
"num_lines": 4,
"path": "/README.md",
"repo_name": "schulzjona/CaesarChiffre",
"src_encoding": "UTF-8",
"text": "# CaesarChiffre\n \nRequired pip packages:\n - PyQt5\n"
},
{
"alpha_fraction": 0.5147727131843567,
"alphanum_fraction": 0.5249999761581421,
"avg_line_length": 22.157894134521484,
"blob_id": "644a8cb8d7f6e697f8fbd303224de948894f02cd",
"content_id": "452b252c5141d0f7d97d75af85c5b86f3483b90d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 880,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 38,
"path": "/GUI/caesar_lib.py",
"repo_name": "schulzjona/CaesarChiffre",
"src_encoding": "UTF-8",
"text": "import string\n\nlower = string.ascii_lowercase\nupper = string.ascii_uppercase\n\ndef encrypt(text, enc_ziffer):\n ziffer = int(enc_ziffer)\n buchstaben_liste = list(text)\n\n\n m = []\n\n i = 0\n while i < len(buchstaben_liste):\n if buchstaben_liste[i] == ' ':\n m.append(' ')\n i = i + 1\n continue\n if buchstaben_liste[i] in lower:\n index = lower.find(buchstaben_liste[i])\n temp = lower[(index + int(enc_ziffer))%26]\n m.append(temp)\n elif buchstaben_liste[i] in upper:\n index = upper.find(buchstaben_liste[i])\n temp = upper[(index + int(enc_ziffer))%26]\n m.append(temp)\n \n i = i + 1\n\n \n ausgabe_string = \"\"\n\n zs = 0\n while zs < len(m):\n ausgabe_string = ausgabe_string + m[zs]\n zs = zs + 1\n\n return ausgabe_string\n"
},
{
"alpha_fraction": 0.6457267999649048,
"alphanum_fraction": 0.6471877098083496,
"avg_line_length": 30.86046600341797,
"blob_id": "3828d68d4d4857a0ce11ff6ff238d5613e5075e2",
"content_id": "d9e05aef9f9918a8c177bdae7e0bd0d1f773590c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1369,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 43,
"path": "/GUI/CaesarChiffre.py",
"repo_name": "schulzjona/CaesarChiffre",
"src_encoding": "UTF-8",
"text": "import sys\nfrom PyQt5 import QtCore, QtGui, QtWidgets,uic\n\nimport caesar_lib\n\nqtCreatorfile = \"GUI.ui\"\n\nUi_MainWindow, QtBaseClass = uic.loadUiType(qtCreatorfile)\n\nclass MyApp(QtWidgets.QMainWindow, Ui_MainWindow):\n def __init__(self):\n QtWidgets.QMainWindow.__init__(self)\n Ui_MainWindow.__init__(self)\n self.setupUi(self)\n self.btnOpn.clicked.connect(self.datei_oeffnen)\n self.btnEnc.clicked.connect(self.start_encryption)\n self.btnExport.clicked.connect(self.save_to_file)\n\n def datei_oeffnen(self):\n datei_auswahl = QtWidgets.QFileDialog.getOpenFileName(self, 'Open File')\n datei_offen = open(datei_auswahl[0], 'r')\n with datei_offen:\n klartext = datei_offen.read()\n self.klar_text.setText(klartext)\n datei_offen.close()\n\n def start_encryption(self):\n if self.klar_text.toPlainText() == \"\" or self.enc_ziffer_input.toPlainText() == \"\":\n return\n self.enc_text.setText(caesar_lib.encrypt(self.klar_text.toPlainText(), self.enc_ziffer_input.toPlainText()))\n\n def save_to_file(self):\n datei = open('verschluesselt.txt', 'w')\n datei.write(self.enc_text.toPlainText())\n\ndef main():\n app = QtWidgets.QApplication(sys.argv)\n window = MyApp()\n window.show()\n sys.exit(app.exec_())\n\nif __name__ == \"__main__\":\n main()"
},
{
"alpha_fraction": 0.4004913866519928,
"alphanum_fraction": 0.4406224489212036,
"avg_line_length": 32.4383544921875,
"blob_id": "5b33f99816a87224209199ebb07ff58875d684f6",
"content_id": "741a86d4fe0bd2960c76d07fdafefc9da43d68f8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2443,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 73,
"path": "/Kommandozeilenanwendung (Ohne Dateidialog)/caesar.py",
"repo_name": "schulzjona/CaesarChiffre",
"src_encoding": "UTF-8",
"text": "# Caeser Chiffre Verfahren \n# Version 1.0\n# Autor: Jona Schulz, Marvin Daniel\n# Klasse: CN1 WS2019\n\n#In Datei schreiben\n\nd = open('Klartext.txt','w')\n\n# Buchstaben --> Zahlen\nb_z_z = { \"a\":0 , \"b\":1 , \"c\":2 , \"d\":3 , \"e\":4 ,\n \"f\":5 , \"g\":6 , \"h\":7 , \"i\":8 , \"j\":9 ,\n \"k\":10, \"l\":11, \"m\":12, \"n\":13, \"o\":14,\n \"p\":15, \"q\":16, \"r\":17, \"s\":18, \"t\":19,\n \"u\":20, \"v\":21, \"w\":22, \"x\":23, \"y\":24, \"z\":25 }\n \n# Zahlen --> Buchstaben\nz_z_b = { 0 :\"a\", 1 :\"b\", 2 :\"c\", 3 :\"d\", 4 :\"e\",\n 5 :\"f\", 6 :\"g\", 7 :\"h\", 8 :\"i\", 9 :\"j\",\n 10:\"k\", 11:\"l\", 12:\"m\", 13:\"n\", 14:\"o\",\n 15:\"p\", 16:\"q\", 17:\"r\", 18:\"s\", 19:\"t\",\n 20:\"u\", 21:\"v\", 22:\"w\", 23:\"x\", 24:\"y\", 25:\"z\" }\n \n \n\nziffer = int(input(\"Bitte Verschluesselungsziffer eingeben #> \"))\ninput_text = input(\"Bitte geben Sie den Text ein, der verschluesselt werden soll #> \").lower()\n\n# Der string wird in eine Liste umgewandelt, damit man auf alle buchstaben einzeln zugreifen kann\nbuchstaben_liste = list(input_text)\n\n\n\n##################################################################################################\n# #\n# Verschlüsselung #\n# #\n# #\n##################################################################################################\n\n# Hilfsliste erstellen, in der die einzelnen Buchstaben nach der verrechnung eingespeichert werden\nm = []\n\n# Verschluesselung der Buchstaben innerhalb einer sogenannten while-Schleife\ni = 0\nwhile i < len(buchstaben_liste):\n if buchstaben_liste[i] == ' ':\n m.append(' ')\n i = i + 1\n continue\n m.append(z_z_b[ ( b_z_z[ buchstaben_liste[i] ] + ziffer ) % 26])\n i = i + 1\n\n# String definieren, in den die Buchstaben wieder zusammengesetzt werden\nausgabe_string = \"\"\n\n# Mithilfe einer while-Schleife die Buchstaben wieder in einen String umwandeln\nzs = 0\nwhile zs < len(m):\n ausgabe_string = ausgabe_string + m[zs]\n zs = zs + 1\n\nprint()\nprint(input_text)\nprint()\nprint(m)\nprint()\nprint(ausgabe_string.upper())\n\n#Ausgabe der Werte in Datei\n\nd.write(input_text + \"\\n\" +str(m) + \"\\n\"+ ausgabe_string.upper())\nd.close()\n\n"
}
] | 4 |
mansikulkarni96/Algorithms | https://github.com/mansikulkarni96/Algorithms | 4f79c46f407a2db8d1383b5de9bfa9f059c1d521 | 3c0bb7f6413305ac47d28f2693ad4d9d8cef298b | c7815f9b032005964b11bd5731fe8b0c98de9c0d | refs/heads/master | 2020-04-19T19:32:52.650424 | 2019-02-03T20:48:26 | 2019-02-03T20:48:26 | 168,391,866 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.43670886754989624,
"alphanum_fraction": 0.45886075496673584,
"avg_line_length": 25.81818199157715,
"blob_id": "84331225da75e16710c9dae024d2180c5b163597",
"content_id": "0eae8a49bbfb215fcfae7b80a27b87f6a9d6961b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 316,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 11,
"path": "/plusOne.py",
"repo_name": "mansikulkarni96/Algorithms",
"src_encoding": "UTF-8",
"text": "class Solution(object):\n def plusOne(self, digits):\n \"\"\"\n :type digits: List[int]\n :rtype: List[int]\n \"\"\"\n sum=0\n sum1=[]\n for i in range(0,len(digits)):\n sum=sum+digits[i]*pow(10,len(digits)-1-i)\n return map(int,str(sum+1))\n \n "
},
{
"alpha_fraction": 0.4259520471096039,
"alphanum_fraction": 0.4626234173774719,
"avg_line_length": 19.285715103149414,
"blob_id": "dd14c55a31edca272b12d1f8d1facad6ec1278c6",
"content_id": "688714eb33d05e5388cf33fd4a7abebdb111136a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 709,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 35,
"path": "/counting.java",
"repo_name": "mansikulkarni96/Algorithms",
"src_encoding": "UTF-8",
"text": "package algo;\n\npublic class counting {\n\tvoid countingSort(int arr[]) \n { \n int index=0;\n int[] freq_arr;\n freq_arr = new int[] {0,0,0,0,0,0,0,0,0,0};\n for(int i=0;i<arr.length;i++)\n {\n \tint val=arr[i];\n \tfreq_arr[val-1]=freq_arr[val-1]+1;\n \t\n }\n for(int j=0;j<freq_arr.length;j++)\n \tfor(int k=0 ; k < freq_arr[j]; k++)\n\n \t\t\t{\n\n \t\t\tarr[index++]=j+1;\n\n \t\t\t}\n}\n\npublic static void main(String[] args) \n{ \n counting op = new counting(); \n int arr[] = {1, 6, 3, 1, 3, 4, 6}; \n op.countingSort(arr); \n for (int i=0; i < arr.length; i++) {\n System.out.println(\"sorted array\"+arr[i]);\n\n }\n}\n}"
},
{
"alpha_fraction": 0.5445815920829773,
"alphanum_fraction": 0.5610425472259521,
"avg_line_length": 19.27777862548828,
"blob_id": "cc1565c21b38dfac5f795689fd82dcb08ea53b77",
"content_id": "a00dcf1de0c8828f45f97ad90f4cb760e3c6e4c5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 729,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 36,
"path": "/triangleType.java",
"repo_name": "mansikulkarni96/Algorithms",
"src_encoding": "UTF-8",
"text": "public class TriangleType {\n\n static Triangle getType(int a, int b, int c)\n {\n if(a<=0||b<=0||c<=0)\n throw new IllegalArgumentException(\"Length of sides cannot be equal to or less than zero\");\n\n if(a==b&&b==c&&c==a)\n return Triangle.EQUILATERAL;\n else if((a==b)||(b==c)||(c==a))\n return Triangle.ISOSCELES;\n else if(a!=b&&b!=c&&c!=a)\n return Triangle.SCALENE;\n else\n return Triangle.ERROR;\n }\n\n\n public static void main(String[] args)\n {\n System.out.println(TriangleType.getType(13, 13, 0));\n\n }\n}\n\nenum Triangle\n{\nISOSCELES(0),\nEQUILATERAL(1),\nSCALENE(2),\nERROR(3);\n\nprivate int n;\nTriangle(int n)\n{this.n = n;}\n}"
}
] | 3 |
yoos/omnikiwi | https://github.com/yoos/omnikiwi | bd95bffa06c3695cb6f263d1da898dc8f86913b2 | 60ea6e3398981ceede878a0950699bcdf06218b3 | e51a4948d3124f5d665f68cd4fdf4f586df77c4c | refs/heads/master | 2021-01-21T23:04:40.555218 | 2013-03-06T20:43:03 | 2013-03-06T20:43:03 | 2,666,889 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6367999911308289,
"alphanum_fraction": 0.646399974822998,
"avg_line_length": 17.909090042114258,
"blob_id": "0761a456f31416f2d6deed914933cf45a5423644",
"content_id": "eaa8ae6ccc0aa0902c1086259acc6457cf038cc3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 625,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 33,
"path": "/src/maze_solver.h",
"repo_name": "yoos/omnikiwi",
"src_encoding": "UTF-8",
"text": "/*! \\file maze_solver.h\n * \\author Soo-Hyun Yoo\n * \\brief Maze solver bot.\n */\n\n#ifndef MAZE_SOLVER_H\n#define MAZE_SOLVER_H\n\n#include \"globals.h\"\n#include \"motors.h\"\n#include \"movements.cpp\"\n\nclass MazeSolver {\n // Controllers\n void mazeSolver();\n void lightFollower();\n void wallFollower();\n\n bool okayToTurnRight;\n\n // Current and target wall \"statuses\", i.e., whether or not there is a wall to the right, front, left, and back.\n uint8_t currentWalls[4];\n uint8_t targetWalls[4];\n uint8_t lastWalls[4];\n\n void updateWalls();\n\npublic:\n MazeSolver();\n void run();\n};\n\n#endif // MAZE_SOLVER_H\n\n"
},
{
"alpha_fraction": 0.6441351771354675,
"alphanum_fraction": 0.6461232900619507,
"avg_line_length": 18.30769157409668,
"blob_id": "6fc7a69e00653d1e8d1bc718e56545948514ac18",
"content_id": "cf042341f8bc048689bcaa2fab3bca6172f9e04b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 503,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 26,
"path": "/src/sensors.h",
"repo_name": "yoos/omnikiwi",
"src_encoding": "UTF-8",
"text": "/*! \\file sensors.h\n * \\author Soo-Hyun Yoo\n * \\brief Sensor readings.\n */\n\n#ifndef SENSORS_H\n#define SENSORS_H\n\n#include \"globals.h\"\n\n#define SENSORS_LPF_DEPTH 5 // Enable low-pass filter.\n\nclass Sensors {\n #ifdef SENSORS_LPF_DEPTH\n int lpfIndex[NUM_OF_LEDS];\n float lpfVal[NUM_OF_LEDS][SENSORS_LPF_DEPTH]; // Low-pass filter values for each LED.\n #endif // SENSORS_LPF_DEPTH\n\npublic:\n Sensors();\n void chargeLED(int);\n void readLED(int);\n void read();\n};\n\n#endif // SENSORS_H\n\n"
},
{
"alpha_fraction": 0.6062697768211365,
"alphanum_fraction": 0.6131722927093506,
"avg_line_length": 30.889907836914062,
"blob_id": "47e07593256e72a5bab55ddfab1e1e232fd52be9",
"content_id": "0b6638a8b5e1c033b16e5149baee425a65c27f33",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3477,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 109,
"path": "/src/sensors.cpp",
"repo_name": "yoos/omnikiwi",
"src_encoding": "UTF-8",
"text": "/*! \\file sensors.cpp\n * \\author Soo-Hyun Yoo\n * \\brief Read sensors.\n */\n\n#include \"sensors.h\"\n\nSensors::Sensors() {\n for (int i=0; i<NUM_OF_LEDS; i++) {\n pinMode(anodePins[i], OUTPUT);\n pinMode(cathodePins[i], OUTPUT);\n\n #ifdef SENSORS_LPF_DEPTH\n lpfIndex[i] = 0;\n for (int j=0; j<SENSORS_LPF_DEPTH; j++) {\n lpfVal[i][j] = 0;\n }\n #endif // SENSORS_LPF_DEPTH\n\n chargeReadings[i] = 0;\n ledReadings[i] = 0;\n ledFiltered[i] = 0;\n }\n}\n\n/*! Charge LED and take first analog reading.\n *\n * \\param ledNum Index of LED to charge and read.\n */\nvoid Sensors::chargeLED(int ledNum) {\n // Reverse bias LED.\n digitalWrite(cathodePins[ledNum], HIGH);\n digitalWrite(anodePins[ledNum], LOW);\n\n // Take first analog reading from cathode pin.\n pinMode(cathodePins[ledNum], INPUT);\n digitalWrite(cathodePins[ledNum], LOW); // Disable pullup resistor.\n chargeReadings[ledNum] = analogRead(ledNum);\n}\n\n/*! Take second analog reading and discharge LED.\n *\n * \\param ledNum Index of LED to read and discharge.\n */\nvoid Sensors::readLED(int ledNum) {\n // Take second analog reading from cathode pin and calculate voltage drop\n // between first and second readings. Sometimes, this drop is insanely big\n // -- ignore those.\n uint16_t tmp = chargeReadings[ledNum] - analogRead(ledNum);\n ledReadings[ledNum] = (tmp < LED_MAX_SANE_READING) ? tmp : ledReadings[ledNum];\n\n // Low-pass filter.\n #ifdef SENSORS_LPF_DEPTH\n lpfVal[ledNum][lpfIndex[ledNum]] = ((float) ledReadings[ledNum]) / SENSORS_LPF_DEPTH;\n\n ledFiltered[ledNum] = 0;\n for (int i=0; i<SENSORS_LPF_DEPTH; i++) {\n ledFiltered[ledNum] += lpfVal[ledNum][i];\n }\n lpfIndex[ledNum] = (lpfIndex[ledNum] + 1) % SENSORS_LPF_DEPTH; // Increment index by 1 and loop back from SENSORS_LPF_DEPTH.\n\n #else\n ledFiltered[ledNum] = ledReadings[ledNum];\n #endif // SENSORS_LPF_DEPTH\n\n // Forward bias LED.\n pinMode(cathodePins[ledNum], OUTPUT);\n digitalWrite(anodePins[ledNum], HIGH);\n}\n\nvoid Sensors::read() {\n\n // DEPRECATED 2/24/12\n //// Charge LEDs (reverse bias)\n //for (int i=0; i<NUM_OF_LEDS; i++) {\n // digitalWrite(cathodePins[i], HIGH);\n // digitalWrite(anodePins[i], LOW);\n //}\n\n //// Should I try a delay here?\n\n //// Take first analog readings from cathode pins.\n //for (int i=0; i<NUM_OF_LEDS; i++) {\n // pinMode(cathodePins[i], INPUT);\n // digitalWrite(cathodePins[i], LOW); // Disable pullup resistor.\n // ledReadings[i] = analogRead(i);\n // // Should I try a delay after the analogRead()?\n //}\n\n //// Let LEDs discharge TODO: Make this non-locking! Maybe read() should\n //// toggle between charge and read?\n //// Making the delay too low makes the readings drift.\n ////delay(LED_DISCHARGE_TIME);\n\n //// Take second readings and calculate voltage drop between first and second\n //// readings.\n ////for (int i=NUM_OF_LEDS-1; i>-1; i--) { // Reverse order to reduce crosstalk.\n //for (int i=0; i<NUM_OF_LEDS; i++) {\n // ledReadings[i] -= analogRead(i);\n // // Should I try a delay after the analogRead()?\n //}\n\n //// Fully discharge LEDs (forward bias)\n //for (int i=0; i<NUM_OF_LEDS; i++) {\n // pinMode(cathodePins[i], OUTPUT);\n // digitalWrite(cathodePins[i], LOW); // Is this line necessary?\n // digitalWrite(anodePins[i], HIGH);\n //}\n}\n\n"
},
{
"alpha_fraction": 0.39390090107917786,
"alphanum_fraction": 0.399301141500473,
"avg_line_length": 29.852941513061523,
"blob_id": "140624b4683570b6ed94d3411578df2b9b8c8e89",
"content_id": "e428d026194002849dd76962821e90c266971673",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3148,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 102,
"path": "/src/omnikiwi.cpp",
"repo_name": "yoos/omnikiwi",
"src_encoding": "UTF-8",
"text": "/*! \\file omnikiwi.cpp\n * \\author Soo-Hyun Yoo\n * \\brief Main loop.\n *\n * Details.\n */\n\n#include <Wire.h>\n#include \"maze_solver.cpp\"\n#include \"pilot.cpp\"\n#include \"imu.cpp\"\n#include \"sensors.cpp\"\n#include \"globals.h\"\n#include \"telemetry.h\"\n\nint main(void) {\n init(); // For Arduino.\n\n // Begin Arduino services.\n Wire.begin();\n\n Serial.begin(BAUDRATE);\n\n pinMode(MT_DIG, OUTPUT);\n pinMode(MR_DIG, OUTPUT);\n pinMode(ML_DIG, OUTPUT);\n\n // Initialize bot.\n IMU imu;\n imu.init();\n\n Sensors sensors;\n Pilot pilot;\n MazeSolver mazer;\n\n // Variables\n\n uint64_t nextRuntime = micros();\n loopCount = 0;\n\n while (1) {\n if (micros() >= nextRuntime) {\n // ================================================================\n // System loop\n // ================================================================\n nextRuntime += MASTER_DT; // Update next loop start time.\n\n // ================================================================\n // Sensor loop\n //\n // WARNING: This loop is extremely time-sensitive! Make sure the\n // looptime never exceeds MASTER_DT!\n // ================================================================\n imu.update();\n\n for (int i=0; i<NUM_OF_LEDS; i++) {\n if (loopCount % SENSOR_LOOP_INTERVAL == i) {\n // Charge up the LED two pins down the list since a delay\n // of 16 ms seems to work well while our master loop time\n // is 8 ms. Do this before readLED() to reduce noise! TODO:\n // Figure out why doing this before readLED() makes the\n // readings less noisy.\n sensors.chargeLED((i+2) % NUM_OF_LEDS);\n\n // Read requested LED.\n sensors.readLED(i);\n }\n }\n\n // ================================================================\n // Control loop\n // ================================================================\n if (loopCount % CONTROL_LOOP_INTERVAL == 0) {\n //mazer.run();\n pilot.fly();\n\n analogWrite(MT_PWM, analogOut[MOTOR_T]);\n analogWrite(MR_PWM, analogOut[MOTOR_R]);\n analogWrite(ML_PWM, analogOut[MOTOR_L]);\n\n digitalWrite(MT_DIG, digOut[MOTOR_T]);\n digitalWrite(MR_DIG, digOut[MOTOR_R]);\n digitalWrite(ML_DIG, digOut[MOTOR_L]);\n }\n if (loopCount % CONTROL_LOOP_INTERVAL == 1) {\n pilot.listen();\n }\n\n // ================================================================\n // Telemetry loop\n // ================================================================\n if (loopCount % TELEMETRY_LOOP_INTERVAL == 0) {\n sendTelemetry(nextRuntime);\n }\n\n loopCount++;\n loopCount = loopCount % 1000;\n } // endif\n } // endwhile\n\n return 0;\n}\n\n"
},
{
"alpha_fraction": 0.37654322385787964,
"alphanum_fraction": 0.39043208956718445,
"avg_line_length": 25.616437911987305,
"blob_id": "5fcf9ef8f17d034d7d833b8a3d4b6e1ad5faeef1",
"content_id": "c7103135ee864976c9a3568f495acbe2bf0a9658",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1944,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 73,
"path": "/src/telemetry.h",
"repo_name": "yoos/omnikiwi",
"src_encoding": "UTF-8",
"text": "/*! \\file telemetry.h\n * \\author Soo-Hyun Yoo\n * \\brief Some functions to make sending telemetry data simpler to code.\n *\n * Details.\n */\n\n#ifndef TELEMETRY_H\n#define TELEMETRY_H\n\n#include \"globals.h\"\n\nvoid sendTelemetry(uint64_t nextRuntime) {\n // Send move number.\n #ifdef SEND_MOVE_COUNTER\n sw(moveCounter);\n sw(FIELD_SER_TAG); sw(FIELD_SER_TAG);\n #endif // SEND_MOVE_COUNTER\n\n // ========================================================================\n // Report motor values.\n // ========================================================================\n #ifdef SEND_MOTOR_VALUES\n sp(\"M( \");\n for (int i=0; i<3; i++) {\n if (digOut[i]) {\n sp(\"+\");\n }\n else {\n sp(\"-\");\n }\n sp(analogOut[i]);\n sp(\" \");\n }\n sp(\") \");\n sw(FIELD_SER_TAG); sw(FIELD_SER_TAG);\n #endif // SEND_MOTOR_VALUES\n\n // ========================================================================\n // Read LED distance sensors.\n // ========================================================================\n #ifdef SEND_SENSOR_READINGS\n sw(SEN_SER_TAG);\n for (int i=0; i<NUM_OF_LEDS; i++) {\n sw((ledFiltered[i]+1)*250.0/1024.0);\n }\n sw(FIELD_SER_TAG); sw(FIELD_SER_TAG);\n #endif // SEND_SENSOR_READINGS\n\n // ========================================================================\n // Send direction?\n // ========================================================================\n #ifdef SEND_DIR\n sp(\"Dir( \");\n for (int i=0; i<NUM_OF_LEDS; i++) {\n if (ledFiltered[i] > MAZE_THRESHOLD_6CM) {\n sp(\"1\");\n }\n else {\n sp(\"0\");\n }\n }\n sp(\" ) \");\n sw(FIELD_SER_TAG); sw(FIELD_SER_TAG);\n #endif // SEND_DIR\n\n // Report loop time.\n sp((float) (micros() - (nextRuntime - MASTER_DT))/1000);\n\n sw(0xde); sw(0xad); sw(0xbe); sw(0xef);\n}\n\n#endif // TELEMETRY_H\n\n"
},
{
"alpha_fraction": 0.519318163394928,
"alphanum_fraction": 0.5568181872367859,
"avg_line_length": 24.852941513061523,
"blob_id": "2bb3c070a713f247e5596e1b911d19068f0f3d5d",
"content_id": "1999e9519d4acc4ac5b56981bbc490622be5a78d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 880,
"license_type": "no_license",
"max_line_length": 147,
"num_lines": 34,
"path": "/src/kiwiconfig.py",
"repo_name": "yoos/omnikiwi",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\n# =============================================================================\n# Communication\n# =============================================================================\n\n# General\n#serialPort = \"/dev/ttyUSB0\" # Uncomment to specify serial port. Otherwise, will connect to first available port.\nbaudRate = 57600\n\n# TX\ndataSendInterval = 0.040 # 40 ms interval = 25 hz. NOTE: This frequency should be LOWER than the microcontroller's communications loop frequency!\ndogFeedInterval = 0.1\nserHeader = chr(255)\ndogBone = chr(254)\n\n# RX\nnewlineSerTag = '\\xde\\xad\\xbe\\xef'\nfieldSerTag = '\\xff\\xff'\nsensorSerTag = '\\xfb'\nrotationSerTag = '\\xfc'\nmotorSerTag = '\\xfd'\npidSerTag = '\\xfe'\n\n\n# Joystick axis sign flips.\naxisSigns = [1, -1, 1, -1, -1, 1]\n\n# Joystick axis indices.\naxisX = 0\naxisY = 1\naxisT = 3\naxisZ = 2\n\n"
},
{
"alpha_fraction": 0.44771721959114075,
"alphanum_fraction": 0.4590083360671997,
"avg_line_length": 27.690141677856445,
"blob_id": "7da336ea420c2e2e14fd5d2ae4abcc82d16dc546",
"content_id": "e074c58fb46c8b33e16b00e28cb9105fbdc6dcc5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4074,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 142,
"path": "/src/maze_solver.cpp",
"repo_name": "yoos/omnikiwi",
"src_encoding": "UTF-8",
"text": "/*! \\file maze_solver.cpp\n * \\author Soo-Hyun Yoo\n * \\brief Maze solver bot source.\n */\n\n#include \"maze_solver.h\"\n\nMazeSolver::MazeSolver() {\n rotSpeed = 0;\n transDir = 0;\n transSpeed = 0;\n\n runUnitAction = &stop;\n\n moveCounter = 0;\n\n okayToTurnRight = true;\n\n for (int i=0; i<4; i++) {\n currentWalls[i] = 0;\n targetWalls[i] = 0;\n lastWalls[i] = 0;\n }\n}\n\nvoid MazeSolver::run() {\n updateWalls();\n //mazeSolver();\n //lightFollower();\n wallFollower();\n}\n\nvoid MazeSolver::mazeSolver() {\n //if (micros() > unitMoveEndTime) {\n // if (ledReadings[2] < MAZE_THRESHOLD_FORWARD) { // Nothing ahead.\n // if (ledReadings[0] > MAZE_THRESHOLD_RIGHT_HIGH) { // Right wall too close\n // runUnitAction = &veerLeft;\n // }\n // else if (ledReadings[0] < MAZE_THRESHOLD_RIGHT_LOW) {\n // runUnitAction = &veerRight;\n // }\n // else {\n // runUnitAction = &transForward;\n // }\n // }\n // else {\n // runUnitAction = &rotateRight;\n // }\n\n // if (ledReadings[3] < MAZE_THRESHOLD_NOWALL) {\n // runUnitAction = &rotateLeft;\n // }\n\n // runUnitAction(); // Unit controller function pointer.\n // calculate_pwm_outputs(rotSpeed, transDir, transSpeed);\n //}\n}\n\nvoid MazeSolver::lightFollower() {\n //bool stimulus = false;\n\n //float ledDir = 0;\n //for (int i=0; i<NUM_OF_LEDS; i++) {\n // if (ledReadings[i] > MAZE_THRESHOLD_FORWARD) {\n // ledDir = PI/3 * i;\n // stimulus = true;\n // }\n //}\n\n //if (stimulus) {\n // transDir = ledDir;\n // transSpeed = MAZE_TRANS_SPEED;\n //}\n //else {\n // transSpeed = 0;\n //}\n}\n\nvoid MazeSolver::wallFollower() {\n if (micros() > unitMoveEndTime) {\n if (nextUnitAction == NULL) {\n if (!currentWalls[0]) { // No wall to right\n if (okayToTurnRight) {\n runUnitAction = &turnRight;\n nextUnitAction = &transUnit;\n\n //for (int i=0; i<4; i++) {\n // lastWalls[i] = currentWalls[(i-1)%4];\n //}\n //okayToTurnRight = false;\n }\n else {\n if (currentWalls[1]) {\n runUnitAction = &rotateLeft;\n }\n else {\n runUnitAction = &transForward;\n }\n }\n }\n else if (currentWalls[1]) { // Wall in front.\n if (!currentWalls[2]) { // No wall to left?\n runUnitAction = &rotateLeft;\n }\n else {\n runUnitAction = &rotateBack;\n }\n }\n else if (!currentWalls[1]) { // No wall in front.\n //if (ledFiltered[1] > MAZE_THRESHOLD_RIGHT_AHEAD) {\n // runUnitAction = &veerLeft;\n //}\n //else if (ledFiltered[5] > MAZE_THRESHOLD_RIGHT_BEHIND) {\n // runUnitAction = &veerRight;\n //}\n //else {\n runUnitAction = &transForward;\n //}\n\n for (int i=0; i<4; i++) {\n if (currentWalls[i] != lastWalls[i]) {\n okayToTurnRight = true;\n }\n }\n }\n }\n else {\n runUnitAction = nextUnitAction;\n nextUnitAction = NULL;\n }\n\n runUnitAction(); // Unit controller function pointer.\n calculate_pwm_outputs(rotSpeed, transDir, transSpeed);\n }\n}\n\nvoid MazeSolver::updateWalls() {\n currentWalls[0] = (ledFiltered[0] > MAZE_THRESHOLD_RIGHT) ? 1 : 0;\n currentWalls[1] = (ledFiltered[1] > MAZE_THRESHOLD_FRONT) ? 1 : 0;\n currentWalls[2] = (ledFiltered[2] > MAZE_THRESHOLD_LEFT) ? 1 : 0;\n currentWalls[3] = (ledFiltered[3] > MAZE_THRESHOLD_BACK) ? 1 : 0;\n}\n"
},
{
"alpha_fraction": 0.5430711507797241,
"alphanum_fraction": 0.5655430555343628,
"avg_line_length": 10.565217018127441,
"blob_id": "7bfb40286c62581cf808f6f5f358ac3682660fd8",
"content_id": "eae5edb58861ed2bb0ca046c4c5c745ca40df23c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 267,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 23,
"path": "/src/imu.h",
"repo_name": "yoos/omnikiwi",
"src_encoding": "UTF-8",
"text": "/*! \\file imu.h\n * \\author Soo-Hyun Yoo\n * \\brief Header for IMU class.\n *\n * Details.\n */\n\n#ifndef IMU_H\n#define IMU_H\n\n#include \"lsm303.cpp\"\n#include \"globals.h\"\n\nclass IMU {\n LSM303 mag;\n\npublic:\n IMU();\n void init();\n void update();\n};\n\n#endif // IMU_H\n\n"
},
{
"alpha_fraction": 0.3807692229747772,
"alphanum_fraction": 0.38333332538604736,
"avg_line_length": 21.91176414489746,
"blob_id": "cf76e24d2a5baedbca2d6923e9b58a4d4a7a133f",
"content_id": "621996f7d19fdecbb6fb3cc471ad744601651622",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 780,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 34,
"path": "/src/imu.cpp",
"repo_name": "yoos/omnikiwi",
"src_encoding": "UTF-8",
"text": "/*! \\file imu.cpp\n * \\author Soo-Hyun Yoo\n * \\brief Source for IMU class.\n */\n\n#include \"imu.h\"\n\nIMU::IMU() {\n}\n\nvoid IMU::init() {\n spln(\"IMU here!\");\n update();\n}\n\nvoid IMU::update() {\n // ========================================================================\n // Magnetometer\n // Frame of reference: BODY\n // Units: N/A\n // Purpose: Measure the magnetic north vector mVec with components\n // codirectional with the body's i, j, and k vectors.\n // ========================================================================\n mag.poll();\n heading = mag.getHeading();\n //sp(\"M(\");\n //for (int i=0; i<3; i++) {\n // sp(mag.get(i));\n // sp(\" \");\n //}\n //sp(\") \");\n //sp(\"H: \");\n //spln(heading);\n}\n\n"
},
{
"alpha_fraction": 0.5412784218788147,
"alphanum_fraction": 0.5990248918533325,
"avg_line_length": 33.05535125732422,
"blob_id": "036d2f78acb61f3102bddd1ccd139654cc03489d",
"content_id": "c8d99cfad10c93556321505013c4f5e5e56de063",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 9230,
"license_type": "no_license",
"max_line_length": 223,
"num_lines": 271,
"path": "/src/globals.h",
"repo_name": "yoos/omnikiwi",
"src_encoding": "UTF-8",
"text": "/*! \\file globals.h\n * \\author Soo-Hyun Yoo\n * \\brief Various global definitions and variables.\n *\n * Details.\n */\n\n#ifndef GLOBALS_H\n#define GLOBALS_H\n\n// ============================================================================\n// Variables\n// ============================================================================\nint loopCount; // Count system loops.\nuint8_t digOut[3]; // Motor digital outputs.\nfloat analogOut[3]; // Motor PWM outputs.\nfloat bodyDCM[3][3]; // Current body orientation calculated by IMU.\nfloat targetHeading, targetRot; // Target heading and rotation.\nfloat rotSpeed, transDir, transSpeed; // Target speeds.\n\nfloat heading;\n\nuint16_t moveCounter;\n\n// LED distance sensor readings.\nuint16_t chargeReadings[4];\nuint16_t ledReadings[4];\nuint16_t ledFiltered[4];\n\n\n// ============================================================================\n// PID\n// Match the number of structs to the number of PID value defines.\n// ============================================================================\n//struct PIDdata {\n// float P, I, D;\n// float lastValue;\n// float integral;\n//} PID[4];\n//\n//#define PID_ROT_X 0\n//#define PID_ROT_Y 1\n//#define PID_ROT_Z 2\n//\n//#define XY_P_GAIN 32.0 // 17 30 35 42\n//#define XY_I_GAIN 10.0 // 10 20 50 24\n//#define XY_D_GAIN -8.0 // 6 10 9 10\n//\n//#define Z_P_GAIN 100.0\n//#define Z_I_GAIN 0.0\n//#define Z_D_GAIN 0.0\n\n// ============================================================================\n// SERIAL IN\n// ============================================================================\n#define BAUDRATE 57600\n#define SERHEAD 255 // Serial header byte. Pilot interprets the four bytes following this header byte as motor commands.\n#define PACKETSIZE 6 // Each packet contains (excluding header) X, Y, Twist, Z, and two bytes for button values.\n#define INPUT_MIN 0 // Minimum integer input value from joystick.\n#define INPUT_MAX 250 // Maximum integer input value from joystick.\n#define SX 0 // Serial byte location for joystick X axis.\n#define SY 1 // Serial byte location for joystick Y axis.\n#define ST 2 // Serial byte location for joystick T (twist) axis.\n#define SZ 3 // Serial byte location for joystick Z axis.\n#define SB1 4 // Serial byte location for joystick buttons (0 to 7).\n#define SB2 5 // Serial byte location for joystick buttons (8 to 15).\n\n// ============================================================================\n// SERIAL OUT\n// ============================================================================\n#define SEND_MOVE_COUNTER\n#define SEND_TARGET_ROTATION\n//#define SEND_MOTOR_VALUES\n#define SEND_SENSOR_READINGS\n//#define SEND_DCM\n//#define SEND_PID\n//#define SEND_DIR\n\n#define SEN_SER_TAG 0xfb\n#define ROT_SER_TAG 0xfc\n#define MOT_SER_TAG 0xfd\n#define PID_SER_TAG 0xfe\n#define FIELD_SER_TAG 0xff\n\n// ============================================================================\n// Software configuration: any parameter that is purely code-related or is\n// relatively frequently changed.\n// ============================================================================\n// TODO: might want to consider changing MASTER_DT back to 8000 or changing the\n// sensor lead count from 2 to 3.\n#define MASTER_DT 5200 // 8000 us interval = 125 Hz master loop.\n#define CONTROL_LOOP_INTERVAL 2 // 2x master = 62.5 Hz. NOTE: This frequency should be HIGHER than comm.py's dataSend frequency!\n#define SENSOR_LOOP_INTERVAL 6 // 1/6 master = 20.83 Hz.\n#define TELEMETRY_LOOP_INTERVAL 4 // 1/4 master = 31.25 Hz.\n\n#define MOVE_REL_BODY // Move relative to body.\n//#define MOVE_REL_WORLD // Move relative to world.\n\n#define TMIN 0 // Min analog out.\n#define TMAX 255 // Max analog out.\n\n#define MOTOR_T 0 // Tail motor array index.\n#define MOTOR_R 1 // Right motor array index.\n#define MOTOR_L 2 // Left motor array index.\n\n// Maze solver\n#define COV022\n//#define KELLEY\n\n#define UNIT_DISTANCE 0.35 // \"Unit\" distance for maze solver.\n#define UNIT_ROT (PI/2) * 1.0 // \"Unit\" rotation for maze solver.\n\n// When an obstacle knocks the robot off the desired heading, this gain helps\n// the robot steer clear of the obstacle. If the heading error and this gain\n// have opposite signs, the robot will strafe to the right. If the error and\n// gain have the same signs, the robot will strafe to the left.\n#define STRAFE_CORRECTION_GAIN 0 // 1.5\n\n#define MAZE_TRANS_SPEED 0.6\n#define MAZE_ROT_SPEED 4.0\n#define MAZE_VEER_TRANS_SPEED 0.6\n#define MAZE_VEER_ROT_SPEED 2.0\n#define MAZE_TURN_TRANS_SPEED 0.2\n#define MAZE_TURN_ROT_SPEED 4.0\n\n#ifdef COV022\n\n#define LED_0_THRESHOLD_2CM 395\n#define LED_0_THRESHOLD_4CM 395\n#define LED_0_THRESHOLD_6CM 395\n#define LED_0_THRESHOLD_8CM 395\n#define LED_0_THRESHOLD_10CM 395\n#define LED_0_THRESHOLD_15CM 385\n#define LED_0_THRESHOLD_20CM 375\n#define LED_0_THRESHOLD_25CM 368\n#define LED_0_THRESHOLD_INFTY 340\n\n#define LED_1_THRESHOLD_2CM 405\n#define LED_1_THRESHOLD_4CM 400\n#define LED_1_THRESHOLD_6CM 390\n#define LED_1_THRESHOLD_8CM 360\n#define LED_1_THRESHOLD_10CM 344\n#define LED_1_THRESHOLD_15CM 320\n#define LED_1_THRESHOLD_20CM 300\n#define LED_1_THRESHOLD_25CM 290\n#define LED_1_THRESHOLD_INFTY 190\n\n#define LED_2_THRESHOLD_2CM 462\n#define LED_2_THRESHOLD_4CM 462\n#define LED_2_THRESHOLD_6CM 421\n#define LED_2_THRESHOLD_8CM 385\n#define LED_2_THRESHOLD_10CM 372\n#define LED_2_THRESHOLD_15CM 350\n#define LED_2_THRESHOLD_20CM 340\n#define LED_2_THRESHOLD_25CM 335\n#define LED_2_THRESHOLD_INFTY 290\n\n#define LED_3_THRESHOLD_2CM 495\n#define LED_3_THRESHOLD_4CM 495\n#define LED_3_THRESHOLD_6CM 440\n#define LED_3_THRESHOLD_8CM 360\n#define LED_3_THRESHOLD_10CM 345\n#define LED_3_THRESHOLD_15CM 335\n#define LED_3_THRESHOLD_20CM 325\n#define LED_3_THRESHOLD_25CM 315\n#define LED_3_THRESHOLD_INFTY 295\n\n#define LED_MAX_SANE_READING 700\n\nstruct ledThresholdsData {\n uint16_t cm2;\n uint16_t cm4;\n uint16_t cm6;\n uint16_t cm8;\n uint16_t cm10;\n uint16_t infty;\n} ledThresholds[4];\n\n#define MAZE_THRESHOLD_RIGHT LED_0_THRESHOLD_25CM\n#define MAZE_THRESHOLD_FRONT LED_1_THRESHOLD_10CM\n#define MAZE_THRESHOLD_LEFT LED_2_THRESHOLD_15CM\n#define MAZE_THRESHOLD_BACK LED_3_THRESHOLD_15CM\n\n#define MAZE_THRESHOLD_RIGHT_AHEAD 390\n#define MAZE_THRESHOLD_RIGHT_BEHIND 420\n#endif // COV022\n\n#ifdef KELLEY\nuint16_t ledZero[] = {0, 0, 0, 0};\n#define LED_MAX_SANE_READING 500\n\n#define MAZE_FORWARD_THRES 600\n#define MAZE_RIGHT_THRES_LOW 400\n#define MAZE_RIGHT_THRES_HIGH 540\n#define MAZE_LEFT_THRES_NOWALL 300\n#endif // KELLEY\n\n\n// Sensors\n//#define LED_DISCHARGE_TIME 17 // Time in milliseconds.\n\n\n// ============================================================================\n// Buttons\n// ============================================================================\n#define BUTTON_PILOT_MODE_TOGGLE 0\n#define BUTTON_RESET_YAW 1\n#define BUTTON_ZERO_INTEGRAL 2\n#define BUTTON_DECREASE_TRIM 3\n#define BUTTON_UNDEFINED 4\n#define BUTTON_INCREASE_TRIM 5\n#define BUTTON_DECREASE_XY_P_GAIN 6\n#define BUTTON_INCREASE_XY_P_GAIN 7\n#define BUTTON_DECREASE_XY_I_GAIN 8\n#define BUTTON_INCREASE_XY_I_GAIN 9\n#define BUTTON_DECREASE_XY_D_GAIN 10\n#define BUTTON_INCREASE_XY_D_GAIN 11\n\n// ============================================================================\n// Hardware configuration: any parameter that is changed so infrequently that\n// it may as well be hard-coded.\n// ============================================================================\n#define ROBOT_RADIUS 0.071 // Robot wheelbase radius in meters.\n#define WHEEL_RADIUS 0.0254 // Effective wheel radius in meters.\n#define MAX_MOTOR_SPEED 70.0 // Maximum motor speed in rad/s (350 RPM at 6V == 700 RPM at 12 V). TODO: This varies based on battery voltage. Either make this dynamic or implement rotation sensing using a gyro or encoders.\n\n#define MAX_ROT_SPEED (MAX_MOTOR_SPEED * WHEEL_RADIUS / ROBOT_RADIUS)\n\n#define NUM_OF_LEDS 4 // Number of LED sensors.\n\n// Digital pin assignments\n#define MT_DIG 2 // Tail motor digital pin.\n#define MT_PWM 3 // Tail motor PWM pin.\n#define MR_DIG 4 // Right motor digital pin.\n#define MR_PWM 5 // Right motor PWM pin.\n#define ML_PWM 6 // Left motor PWM pin.\n#define ML_DIG 7 // Left motor digital pin.\n\n// LED pins\nstatic int anodePins[] = {8, 9, 12, 13};\nstatic int cathodePins[] = {14, 15, 16, 17};\n\n// Calibration values for magnetometer.\n#define MAG_X_MIN -314\n#define MAG_X_MAX 320\n#define MAG_Y_MIN -316\n#define MAG_Y_MAX 317\n#define MAG_Z_MIN -427\n#define MAG_Z_MAX 165\n\n\n// ============================================================================\n// Constants\n// ============================================================================\n#define PI 3.141592653589793238462643383279502884197f\n\n\n// ============================================================================\n// Functions\n// ============================================================================\nvoid zeroStr(char *sStr) {\n for (int i=0; i<sizeof(sStr); i++) {\n sStr[i] = 0;\n }\n}\n\n#define sp Serial.print\n#define spln Serial.println\n#define sw Serial.write\n\n#endif // GLOBALS_H\n\n"
},
{
"alpha_fraction": 0.4779520630836487,
"alphanum_fraction": 0.5039952397346497,
"avg_line_length": 26.68852424621582,
"blob_id": "e36d2ff16a864e7c2cf668ece771a589e7efbf3f",
"content_id": "2742eb2f765abebc9b139ffbd7ceea29c3e6e083",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3379,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 122,
"path": "/src/movements.cpp",
"repo_name": "yoos/omnikiwi",
"src_encoding": "UTF-8",
"text": "/*! \\file movements.cpp\n * \\author Soo-Hyun Yoo\n * \\brief Movements for maze solver.\n */\n\n#include \"movements.h\"\n\n// ============================================================================\n// TRANSLATE\n//\n// Linear movements with zero rotation.\n// ============================================================================\nvoid transUnit() {\n unitMoveStartTime = micros();\n unitMoveEndTime = unitMoveStartTime + UNIT_DISTANCE/MAZE_TRANS_SPEED * 1000000;\n\n rotSpeed = 0;\n transDir = PI/2;\n transSpeed = MAZE_TRANS_SPEED;\n}\n\nvoid transForward() {\n unitMoveStartTime = micros();\n unitMoveEndTime = unitMoveStartTime + 1000; // Increment by only 1 ms since we need to check for turns.\n\n rotSpeed = 0;\n transDir = PI/2;\n transSpeed = MAZE_TRANS_SPEED;\n}\n\n// ============================================================================\n// VEER\n//\n// Nearly linear movement with slight skew to one side for course corrections.\n// ============================================================================\nvoid veerRight() {\n unitMoveStartTime = micros();\n unitMoveEndTime = unitMoveStartTime + 1000;\n\n rotSpeed = -MAZE_VEER_ROT_SPEED;\n transDir = PI/2 * 0.95;\n transSpeed = MAZE_VEER_TRANS_SPEED;\n}\n\nvoid veerLeft() {\n unitMoveStartTime = micros();\n unitMoveEndTime = unitMoveStartTime + 1000;\n\n rotSpeed = MAZE_VEER_ROT_SPEED;\n transDir = PI/2 * 1.05;\n transSpeed = MAZE_VEER_TRANS_SPEED;\n}\n\n// ============================================================================\n// TURN\n//\n// Sharp, non-zero-radius turns for fast change in direction with minimal loss\n// of speed.\n// ============================================================================\nvoid turnRight() {\n unitMoveStartTime = micros();\n unitMoveEndTime = unitMoveStartTime + (PI/2 * 1.5) / MAZE_TURN_ROT_SPEED * 1000000;\n\n rotSpeed = -MAZE_TURN_ROT_SPEED;\n transDir = PI/2;\n transSpeed = MAZE_TURN_TRANS_SPEED;\n}\n\nvoid turnLeft() {\n unitMoveStartTime = micros();\n unitMoveEndTime = unitMoveStartTime + (PI/2) / MAZE_TURN_ROT_SPEED * 1000000;\n\n rotSpeed = MAZE_TURN_ROT_SPEED;\n transDir = PI/2;\n transSpeed = MAZE_TURN_TRANS_SPEED;\n}\n\n// ============================================================================\n// ROTATE\n//\n// Zero-radius rotations for maneuvering out of dead ends.\n// ============================================================================\nvoid rotateRight() {\n unitMoveStartTime = micros();\n unitMoveEndTime = unitMoveStartTime + (PI/2) / MAZE_ROT_SPEED * 1000000;\n\n rotSpeed = -MAZE_ROT_SPEED;\n transDir = 0;\n transSpeed = 0;\n}\n\nvoid rotateLeft() {\n unitMoveStartTime = micros();\n unitMoveEndTime = unitMoveStartTime + (PI/2) / MAZE_ROT_SPEED * 1000000;\n\n rotSpeed = MAZE_ROT_SPEED;\n transDir = 0;\n transSpeed = 0;\n}\n\nvoid rotateBack() {\n unitMoveStartTime = micros();\n unitMoveEndTime = unitMoveStartTime + PI / MAZE_ROT_SPEED * 1000000;\n\n rotSpeed = MAZE_ROT_SPEED;\n transDir = 0;\n transSpeed = 0;\n}\n\n// ============================================================================\n// STOP\n//\n// Stop moving.\n// ============================================================================\nvoid stop() {\n unitMoveStartTime = micros();\n unitMoveEndTime = unitMoveStartTime + 1000;\n\n rotSpeed = 0;\n transDir = 0;\n transSpeed = 0;\n}\n\n"
},
{
"alpha_fraction": 0.5311139225959778,
"alphanum_fraction": 0.5440371036529541,
"avg_line_length": 37.475677490234375,
"blob_id": "b9c8644fe7628c458b7ea2a0076aa72856cc34dd",
"content_id": "ca6f70cba9185ddbf9d96dcb99da71d7ac4b3b65",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7119,
"license_type": "no_license",
"max_line_length": 251,
"num_lines": 185,
"path": "/src/groundstation.py",
"repo_name": "yoos/omnikiwi",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport sys\nimport serial\nimport threading\nfrom threading import Timer, Thread\nfrom signal import signal, SIGINT\n\n# ROS\nimport roslib; roslib.load_manifest(\"omnikiwi\")\nimport rospy\nfrom sensor_msgs.msg import Joy\n\n# Omnikiwi\nimport kiwiconfig as cfg # Import config.\n\narmed = False # System arm status. Set to True once throttle is set to zero. Communication will not start until this is True.\n\naxisValues = [125, 125, 125, 3] # [X, Y, T, Z] -- Initialize Z as some non-zero value (albeit very low so the omnikiwi doesn't fly off if something goes awry) so user is forced to fiddle with throttle before motors arm. Hopefully prevents disasters.\nbuttonValues = 0 # Bitfield.\n\n\n# =============================================================================\n# Process joystick input.\n# =============================================================================\n\n# Convert joystick values of [-1.0, 1.0] to [0, 250] so we can send them over\n# serial as bytes.\ndef joy2byte (joyVal, axisIndex):\n return int(250 * ((cfg.axisSigns[axisIndex] * joyVal + 1) / 2))\n\n# Update axisValues when joystick is updated. Raw axis values [-1, 1] for X, Y,\n# and T axes are cubed to facilitate fine control before being scaled and\n# mapped to [0, 1]. All of this is then mapped to [0, 250] to be sent as bytes.\ndef joyCallback (myJoy):\n global axisValues, buttonValues\n\n axisValues[cfg.axisX] = joy2byte(myJoy.axes[0], cfg.axisX) # X\n axisValues[cfg.axisY] = joy2byte(myJoy.axes[1], cfg.axisY) # Y\n\n if len(myJoy.axes) == 2: # Using laptop as joystick\n axisValues[cfg.axisT] = joy2byte(0, cfg.axisT) # Dummy T\n axisValues[cfg.axisZ] = joy2byte(1, cfg.axisZ) # Dummy Z, always full throttle.\n elif len(myJoy.axes) == 3: # Non-twisty joystick\n axisValues[cfg.axisT] = joy2byte(0, cfg.axisT) # Dummy T\n axisValues[cfg.axisZ] = joy2byte(myJoy.axes[2], cfg.axisZ) # Z\n elif len(myJoy.axes) == 6: # Attack3D twisty joystick\n axisValues[cfg.axisT] = joy2byte(myJoy.axes[2], cfg.axisT) # T\n axisValues[cfg.axisZ] = joy2byte(myJoy.axes[3], cfg.axisZ) # Z\n\n # Mars Rover joystick (swap T and Z axis indices)\n #axisValues[cfg.axisT] = joy2byte(myJoy.axes[3], cfg.axisT) # T\n #axisValues[cfg.axisZ] = joy2byte(myJoy.axes[2], cfg.axisZ) # Z\n elif len(myJoy.axes) == 7: # Saitek Cyborg X joystick\n axisValues[cfg.axisZ] = joy2byte(myJoy.axes[2], cfg.axisZ) # Z\n axisValues[cfg.axisT] = joy2byte(myJoy.axes[3], cfg.axisT) # T\n\n buttonValues = 0\n for i in range(len(myJoy.buttons)):\n buttonValues += myJoy.buttons[i]<<i\n\n\n# =============================================================================\n# Communicate.\n# =============================================================================\ndef transmit():\n global armed\n\n if armed:\n serWrite(cfg.serHeader +\n chr(axisValues[cfg.axisX]) +\n chr(axisValues[cfg.axisY]) +\n chr(axisValues[cfg.axisT]) +\n chr(axisValues[cfg.axisZ]) +\n chr(buttonValues & 0b01111111) +\n chr(buttonValues >> 7))\n rospy.loginfo(str(axisValues[cfg.axisX]) + \" \" +\n str(axisValues[cfg.axisY]) + \" \" +\n str(axisValues[cfg.axisT]) + \" \" +\n str(axisValues[cfg.axisZ]) + \" \" +\n str(buttonValues))\n elif not armed:\n rospy.loginfo(\"[GS] Current throttle value: \" + str(axisValues[cfg.axisZ]))\n if axisValues[cfg.axisZ] == 0: # If throttle is at minimum position\n armed = True\n rospy.loginfo(\"[GS] Joystick throttle at minimum! Initialized communication!\")\n\n# Serial write.\ndef serWrite(myStr):\n try:\n for i in range(len(myStr)):\n ser.write(myStr[i])\n rospy.sleep(0.0001) # Sometimes, a delay seems to help. Maybe?\n except:\n rospy.logerr(\"[GS] Unable to send data. Check connection.\")\n # TODO: Comm should do something to ensure safety when it loses connection.\n\n\n# =============================================================================\n# Threads\n# =============================================================================\nclass KiwiSubscriber(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.running = True\n def run(self):\n while self.running and not rospy.is_shutdown():\n rospy.Subscriber(\"joy\", Joy, joyCallback, queue_size=1)\n rospy.spin()\n\nclass KiwiTX(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.running = True\n self.times = 0\n def run(self):\n while self.running and not rospy.is_shutdown():\n transmit()\n self.times += 1\n rospy.sleep(cfg.dataSendInterval)\n\nclass KiwiWatchdog(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.running = True\n self.times = 0\n def run(self):\n while self.running and not rospy.is_shutdown():\n serWrite(cfg.dogBone)\n self.times += 1\n rospy.sleep(cfg.dogFeedInterval)\n\n\n###############################################################################\n\nif __name__ == \"__main__\":\n rospy.init_node(\"omnikiwi_ground_station\", anonymous=False)\n\n # =========================================================================\n # Try to initialize a serial connection. If serialPort is defined, try\n # opening that. If it is not defined, loop through a range of integers\n # starting from 0 and try to connect to /dev/ttyUSBX where X is the\n # integer. In either case, process dies if serial port cannot be opened.\n #\n # TODO: This needs to be made more concise.\n # =========================================================================\n try:\n ser = serial.Serial(cfg.serialPort, cfg.baudRate, timeout=0)\n except serial.SerialException:\n rospy.logerr(\"[GS] Unable to open specified serial port! Exiting...\")\n exit(1)\n except AttributeError:\n for i in range(4):\n try:\n ser = serial.Serial(\"/dev/ttyUSB\"+str(i), cfg.baudRate, timeout=0)\n rospy.loginfo(\"[GS] Opened serial port at /dev/ttyUSB%d.\", i)\n break\n except serial.SerialException:\n rospy.logerr(\"[GS] No serial at /dev/ttyUSB%d.\", i)\n if i == 3:\n rospy.logerr(\"[GS] No serial found. Giving up!\")\n exit(1)\n\n try:\n sub = KiwiSubscriber()\n sub.start()\n tx = KiwiTX()\n tx.start()\n dog = KiwiWatchdog()\n dog.start()\n raw_input(\"Hit <enter> to quit.\")\n\n # Stop the while loops.\n sub.running = False\n tx.running = False\n dog.running = False\n\n # Wait for threads to finish jobs.\n sub.join()\n tx.join()\n dog.join()\n\n except rospy.ROSInterruptException:\n pass\n\n"
},
{
"alpha_fraction": 0.48275861144065857,
"alphanum_fraction": 0.49975013732910156,
"avg_line_length": 29.160804748535156,
"blob_id": "342724f185a34a151b657e96293cb9fd39ebfa12",
"content_id": "302329f942b7474361f63f19a9813d02a2ed11c5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 6003,
"license_type": "no_license",
"max_line_length": 140,
"num_lines": 199,
"path": "/src/pilot.cpp",
"repo_name": "yoos/omnikiwi",
"src_encoding": "UTF-8",
"text": "/*! \\file pilot.cpp\n * \\author Soo-Hyun Yoo\n * \\brief Source for Pilot class.\n *\n * Details.\n */\n\n#include \"pilot.h\"\n\nPilot::Pilot() {\n //Serial.begin(BAUDRATE);\n hasFood = false;\n okayToFly = false;\n\n // Assume serial inputs, all axes zeroed.\n serInput[SX] = 125;\n serInput[SY] = 125;\n serInput[ST] = 125;\n /* Keep Z value at some non-zero value (albeit very low so the tricopter \n * doesn't fly off if something goes awry) so user is forced to adjust \n * throttle before motors arm. */\n serInput[SZ] = 3;\n\n // Initialize trim to 0.\n throttleTrim = 0;\n\n //PID[PID_ROT_X].P = PID[PID_ROT_Y].P = XY_P_GAIN;\n //PID[PID_ROT_X].I = PID[PID_ROT_Y].I = XY_I_GAIN;\n //PID[PID_ROT_X].D = PID[PID_ROT_Y].D = XY_D_GAIN;\n\n //PID[PID_ROT_Z].P = Z_P_GAIN;\n //PID[PID_ROT_Z].I = Z_I_GAIN;\n //PID[PID_ROT_Z].D = Z_D_GAIN;\n\n numGoodComm = 0; // Number of good communication packets.\n numBadComm = 0; // Number of bad communication packets.\n\n // Set targetHeading to current heading. Initialize IMU first!\n targetHeading = heading;\n}\n\nvoid Pilot::listen() {\n if (Serial.available()) {\n serRead = Serial.read();\n\n if (serRead == SERHEAD) { // Receive header.\n hasFood = true; // Prepare food for watchdog.\n for (int i=0; i<PACKETSIZE; i++) {\n serRead = Serial.read();\n\n if (serRead >= INPUT_MIN && serRead <= INPUT_MAX) {\n serInput[i] = serRead;\n okayToFly = true;\n numGoodComm++;\n }\n else {\n i = 10;\n okayToFly = false;\n numBadComm++;\n // Flush remaining buffer to avoid taking in the wrong values.\n Serial.flush();\n }\n }\n }\n else {\n okayToFly = false;\n }\n }\n}\n\nvoid Pilot::fly() {\n //sp(\"(\");\n //sp(numGoodComm);\n //sp(\"/\");\n //sp(numBadComm);\n //sp(\") \");\n\n if (okayToFly) {\n // Process inputs.\n update_joystick_input();\n process_joystick_buttons();\n\n // Calculate target values.\n targetHeading += joy.axes[ST]/125 * 1.5 / (MASTER_DT * CONTROL_LOOP_INTERVAL); // Change target heading by a maximum of 1.5 rad/s.\n\n // Keep targetHeading within [-PI, PI].\n if (targetHeading > PI) {\n targetHeading -= 2*PI;\n }\n else if (targetHeading < -PI) {\n targetHeading += 2*PI;\n }\n\n\n targetRot = targetHeading - heading;\n\n // Keep targetRot within [-PI, PI].\n if (targetRot > PI) {\n targetRot -= 2*PI;\n }\n else if (targetRot < -PI) {\n targetRot += 2*PI;\n }\n\n // Calculate target speeds.\n if (joy.axes[SZ] > 0) {\n rotSpeed = targetRot * MAX_ROT_SPEED / PI;\n transDir = atan2(joy.axes[SY], joy.axes[SX]) + targetRot + STRAFE_CORRECTION_GAIN*targetRot;\n\n if (isCartesian) { transDir += heading; }\n\n transSpeed = 2.5 * sqrt(pow(joy.axes[SX]/125, 2) + pow(joy.axes[SY]/125, 2)) * joy.axes[SZ] / 250.;\n }\n\n // Scale speeds by throttle value.\n rotSpeed *= joy.axes[SZ]/250.;\n transSpeed *= joy.axes[SZ]/250.;\n\n // Calculate PWM duty cycles for the three wheels.\n calculate_pwm_outputs(rotSpeed, transDir, transSpeed);\n\n okayToFly = false;\n }\n else {\n // spln(\"Pilot not okay to fly.\");\n }\n}\n\n// Just update orientation and such and keep hands off controls.\nvoid Pilot::navigate() {\n // Keep targetHeading within [-PI, PI].\n if (targetHeading > PI) {\n targetHeading -= 2*PI;\n }\n else if (targetHeading < -PI) {\n targetHeading += 2*PI;\n }\n\n targetRot = targetHeading - heading;\n\n // Keep targetRot within [-PI, PI].\n if (targetRot > PI) {\n targetRot -= 2*PI;\n }\n else if (targetRot < -PI) {\n targetRot += 2*PI;\n }\n\n // Override some speeds.\n rotSpeed = targetRot * MAZE_ROT_SPEED / PI;\n transDir = PI/2 + targetRot + STRAFE_CORRECTION_GAIN*targetRot;\n\n // Calculate PWM duty cycles for the three wheels.\n calculate_pwm_outputs(rotSpeed, transDir, transSpeed);\n}\n\nvoid Pilot::die() {\n // ========================================================================\n // When communication is lost, pilot should set a bunch of stuff to safe\n // values.\n // ========================================================================\n okayToFly = false;\n}\n\nvoid Pilot::update_joystick_input(void) {\n // ========================================================================\n // Shift serial input values [0, 250] to correct range for each axis. Z\n // stays positive for ease of calculation.\n // ========================================================================\n joy.axes[SX] = (float) serInput[SX] - 125; // [-125, 125]\n joy.axes[SY] = (float) serInput[SY] - 125; // [-125, 125]\n joy.axes[ST] = (float) serInput[ST] - 125; // [-125, 125]\n joy.axes[SZ] = (float) serInput[SZ]; // [ 0, 250]\n\n // ========================================================================\n // Set button values. We utilize only the lower 7 bits, since doing\n // otherwise would cause overlaps with serial headers.\n // ========================================================================\n for (int i=0; i<7; i++) {\n joy.buttons[i] = serInput[SB1] & (1<<i);\n joy.buttons[7+i] = serInput[SB2] & (1<<i);\n }\n}\n\nvoid Pilot::process_joystick_buttons(void) {\n // Toggle pilot mode.\n if (joy.buttons[BUTTON_PILOT_MODE_TOGGLE]) {\n isCartesian = true;\n }\n else {\n isCartesian = false;\n }\n\n // Reset targetHeading to heading if thumb button is pressed.\n if (joy.buttons[BUTTON_RESET_YAW]) {\n targetHeading = heading;\n targetHeading += joy.axes[ST]/125. * 1.5;\n }\n}\n\n"
},
{
"alpha_fraction": 0.6038251519203186,
"alphanum_fraction": 0.6092896461486816,
"avg_line_length": 14.891304016113281,
"blob_id": "56df0397fd97bb005acacdd036e8477b7b7e76e4",
"content_id": "84c61f9df5145cfd5ea456c8ea1f272137813f9b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 732,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 46,
"path": "/src/pilot.h",
"repo_name": "yoos/omnikiwi",
"src_encoding": "UTF-8",
"text": "/*! \\file pilot.h\n * \\author Soo-Hyun Yoo\n * \\brief Header for Pilot class.\n *\n * Details.\n */\n\n#ifndef PILOT_H\n#define PILOT_H\n\n#include \"globals.h\"\n#include <math.h>\n\nclass Pilot {\n byte serRead;\n uint8_t serInput[PACKETSIZE];\n float throttle;\n int throttleTrim;\n float mapLower, mapUpper;\n// double dir; // Direction in radians\n bool okayToFly;\n long numGoodComm;\n long numBadComm;\n\n bool isCartesian;\n\n struct joyInput {\n float axes[6];\n bool buttons[14];\n } joy;\n\n void update_joystick_input(void);\n void process_joystick_buttons(void);\n\npublic:\n Pilot();\n void listen();\n void fly();\n void navigate();\n void die();\n\n bool hasFood;\n\n};\n\n#endif // PILOT_H\n\n"
},
{
"alpha_fraction": 0.6900452375411987,
"alphanum_fraction": 0.6990950107574463,
"avg_line_length": 13.699999809265137,
"blob_id": "e622c0089fea1e20750185fe774dc25615cb41ca",
"content_id": "090ead2c7d0df600366411c46d3d9c87c3775357",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 442,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 30,
"path": "/src/movements.h",
"repo_name": "yoos/omnikiwi",
"src_encoding": "UTF-8",
"text": "/*! \\file movements.h\n * \\author Soo-Hyun Yoo\n * \\brief Movements for maze solver.\n */\n\n#ifndef MOVEMENTS_H\n#define MOVEMENTS_H\n\nuint64_t unitMoveStartTime;\nuint64_t unitMoveEndTime;\n\nvoid (*runUnitAction) ();\nvoid (*nextUnitAction) ();\n\nvoid transUnit();\nvoid transForward();\n\nvoid veerRight();\nvoid veerLeft();\n\nvoid turnRight();\nvoid turnLeft();\n\nvoid rotateRight();\nvoid rotateLeft();\nvoid rotateBack();\n\nvoid stop();\n\n#endif // MOVEMENTS_H\n\n"
},
{
"alpha_fraction": 0.37428513169288635,
"alphanum_fraction": 0.3895016312599182,
"avg_line_length": 40.841880798339844,
"blob_id": "d762fd5bcf1183672fd0571d8c578ba91c92e56b",
"content_id": "629dd97bd1be2f9eae42ca5b2bd989a0f145ac0a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9792,
"license_type": "no_license",
"max_line_length": 125,
"num_lines": 234,
"path": "/src/serialmon.py",
"repo_name": "yoos/omnikiwi",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\n# =============================================================================\n# serialmon.py\n# =============================================================================\n\nimport serial\nimport string\nfrom time import sleep\nimport threading\nfrom threading import Timer, Thread\nfrom signal import signal, SIGINT\nfrom math import pi\n\n# ROS stuff\nimport roslib; roslib.load_manifest(\"tricopter\")\nimport rospy\nfrom omnikiwi.msg import Telemetry\n\nimport kiwiconfig as cfg # Import config.\n\n# =============================================================================\n# Telemetry data\n# =============================================================================\n\n# Initial sensor readings.\nledRaw = [0.0] * 4\nledRawLast = [0.0] * 4\nledFiltered = [0.0] * 4\nledFilteredLast = [0.0] * 4\nledVar = [100.0] * 4\nledUpdateSig = 150.\nledPredictSig = 0.2\n\n# Target rotation values\ntargetRot = [0.0] * 3\n\n# Motor/servo values (MT, MR, ML)\nmotorVal = [0.0] * 3\n\n# PID data\npidData = [0.0] * 3\n\n\n# Kalman filter\ndef update(mean1, var1, mean2, var2):\n new_mean = (var2 * mean1 + var1 * mean2) / (var1 + var2)\n new_var = 1/(1/var1 + 1/var2)\n return [new_mean, new_var]\n\ndef predict(mean1, var1, mean2, var2):\n new_mean = mean1 + mean2\n new_var = var1 + var2\n return [new_mean, new_var]\n\n# Low-pass filter\ndef lpf(currentVal, lastVal, dt, freq):\n rc = 1 / (2 * pi * freq)\n output = lastVal + (dt / (rc + dt)) * (currentVal - lastVal)\n return output\n\n\nclass telemetryThread(threading.Thread):\n def __init__(self):\n threading.Thread.__init__(self)\n self.running = True\n def run(self):\n global ledRaw, targetRot, motorVal, pidData\n sensorDataIndex = 0 # Do I see IMU data?\n rotationDataIndex = 0 # Do I see rotation data?\n motorDataIndex = 0 # Do I see motor data?\n pidDataIndex = 0 # Do I see PID data?\n serBuffer = ''\n serLines = ''\n\n while self.running and not rospy.is_shutdown():\n try:\n if ser.inWaiting() > 0:\n # =========================================================\n # Update buffer, adding onto incomplete line if necessary.\n # =========================================================\n serBuffer = serBuffer + ser.read(ser.inWaiting())\n\n # =========================================================\n # Check for separator tag and split one entry off buffer.\n # =========================================================\n if cfg.newlineSerTag in serBuffer:\n serLines = serBuffer.split(cfg.newlineSerTag)\n\n # Parse fields separated by 0xf0f0.\n fields = serLines[-2].split(cfg.fieldSerTag)\n\n # Save second to last line and discard rest.\n serBuffer = serLines[-1]\n\n # =========================================================\n # Scan for data field headers.\n # TODO: Move this someplace else so it's run only once.\n # =========================================================\n for i in range(1, len(fields)):\n if not sensorDataIndex and fields[i][0] == cfg.sensorSerTag:\n sensorDataIndex = i\n elif not rotationDataIndex and fields[i][0] == cfg.rotationSerTag:\n rotationDataIndex = i\n elif not motorDataIndex and fields[i][0] == cfg.motorSerTag:\n motorDataIndex = i\n elif not pidDataIndex and fields[i][0] == cfg.pidSerTag:\n pidDataIndex = i\n\n # =========================================================\n # Check if we're receiving sensor data.\n # =========================================================\n if sensorDataIndex:\n try:\n for i in range(4):\n ledRaw[i] = float(int(fields[sensorDataIndex][i+1:i+2].encode('hex'), 16)*1024.0)/250.0\n #[ledFiltered[i], ledVar[i]] = update(ledFiltered[i], ledVar[i], ledRaw[i], ledUpdateSig)\n #[ledFiltered[i], ledVar[i]] = predict(ledFiltered[i], ledVar[i], 0.0, ledPredictSig)\n\n\n except Exception, e:\n print \"SEN:\", str(e)\n\n # =========================================================\n # Check if we're receiving target rotation data.\n # =========================================================\n if rotationDataIndex:\n try:\n for i in range(3):\n targetRot[i] = float(int(fields[rotationDataIndex][i+1:i+2].encode('hex'), 16)-1)/250*2*pi-pi\n #targetRot[i] = struct.unpack('f', fields[rotationDataIndex][3+i*4:3+i*4+4])[0]\n except Exception, e:\n print \"ROT:\", str(e)\n\n # =========================================================\n # Check if we're receiving motor/servo output data.\n # =========================================================\n if motorDataIndex:\n try:\n for i in range(3):\n motorVal[i] = int(fields[motorDataIndex][i+1:i+2].encode('hex'), 16)\n #motorVal[i] = struct.unpack('f', fields[motorDataIndex][3+i*4:3+(i+1)*4])[0]\n except Exception, e:\n print \"MTR:\", str(e)\n\n\n # =========================================================\n # Check if we're receiving PID gains and values.\n # =========================================================\n if pidDataIndex:\n try:\n for i in range(3):\n pidData[i] = int(fields[pidDataIndex][i+1:i+2].encode('hex'), 16)\n except Exception, e:\n print \"PID:\", str(e)\n\n # =========================================================\n # Printout\n # =========================================================\n #print fields\n #print [dcm, fields[-1]]\n print \"Move counter:\", int(fields[0].encode('hex'), 16)\n print \"Motors: \", motorVal\n print \"LED raw: \", ledRaw\n print \"LED filtered:\", ledFiltered\n print \"LED variance:\", ledVar\n print \"Loop time: \", fields[-1]\n print \"\\n--\\n\"\n\n pub.publish(Telemetry(ledRaw[0],\n ledRaw[1],\n ledRaw[2],\n ledRaw[3],\n ledFiltered[0],\n ledFiltered[1],\n ledFiltered[2],\n ledFiltered[3],\n motorVal[0],\n motorVal[1],\n motorVal[2],\n pidData[0],\n pidData[1],\n pidData[2]))\n\n except:\n pass\n rospy.sleep(0.005)\n\n\n###############################################################################\n\nif __name__ == \"__main__\":\n # Initialize ROS node.\n rospy.init_node(\"tricopter_receiver\", anonymous=False)\n pub = rospy.Publisher(\"telemetry\", Telemetry)\n\n # =========================================================================\n # Try to initialize a serial connection. If serialPort is defined, try\n # opening that. If it is not defined, loop through a range of integers\n # starting from 0 and try to connect to /dev/ttyUSBX where X is the\n # integer. In either case, process dies if serial port cannot be opened.\n #\n # TODO: This needs to be made more concise.\n # =========================================================================\n try:\n ser = serial.Serial(cfg.serialPort, cfg.baudRate, timeout=0)\n except serial.SerialException:\n rospy.logerr(\"[SM] Unable to open specified serial port! Exiting...\")\n exit(1)\n except AttributeError:\n for i in range(4):\n try:\n ser = serial.Serial(\"/dev/ttyUSB\"+str(i), cfg.baudRate, timeout=0)\n rospy.loginfo(\"[SM] Opened serial port at /dev/ttyUSB%d.\", i)\n break\n except serial.SerialException:\n rospy.logerr(\"[SM] No serial at /dev/ttyUSB%d.\", i)\n if i == 3:\n rospy.logerr(\"[SM] No serial found. Giving up!\")\n exit(1)\n\n try:\n telemetry = telemetryThread()\n telemetry.start()\n raw_input(\"Hit <enter> to quit.\")\n\n # Stop the loops.\n telemetry.running = False\n\n # Wait for threads to finish jobs.\n telemetry.join()\n\n except rospy.ROSInterruptException:\n pass\n\n"
},
{
"alpha_fraction": 0.589205801486969,
"alphanum_fraction": 0.5953579545021057,
"avg_line_length": 35.479591369628906,
"blob_id": "e7ca93d44ff7f39ff39b0a3c9f6f9286a9798638",
"content_id": "6665de7fee394c319bcf44c73c50999e96bf43f6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 3576,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 98,
"path": "/src/motors.h",
"repo_name": "yoos/omnikiwi",
"src_encoding": "UTF-8",
"text": "/*! \\file motors.h\n * \\author Soo-Hyun Yoo\n * \\brief Calculate PWM outputs for motors based on target rotation and translation.\n */\n\n#ifndef MOTORS_H\n#define MOTORS_H\n\n#include \"globals.h\"\n#include <math.h>\n\n/*! Convert wheel rotation speed (rad/s) to PWM.\n */\nfloat w2analog(float rotSpeed) {\n int sign = (rotSpeed > 0) ? 1 : -1;\n if (rotSpeed > 0) {\n return (TMAX - (TMAX - TMIN) * ( rotSpeed / MAX_MOTOR_SPEED));\n }\n else {\n return (TMIN + (TMAX - TMIN) * (-rotSpeed / MAX_MOTOR_SPEED));\n }\n}\n\n/*! Convert linear velocity (m/s) to required wheel rotation speed (rad/s).\n */\nfloat v2w(float velocity) {\n return velocity / WHEEL_RADIUS;\n}\n\n/*! Calculate PWM outputs for an input rotation speed (rad/s) and translation direction (rad) at some speed (m/s).\n *\n * \\param rotSpeed Rotation speed in radians/s\n * \\param transDir Translation direction in radians\n * \\param transSpeed Translation speed in m/s\n */\nvoid calculate_pwm_outputs(float rotSpeed, float transDir, float transSpeed) {\n float rotComponent; // Rotational component of motor spin.\n float motorSpeed[3];\n\n #ifdef MOVE_REL_BODY\n // Calculate motor outputs to move relative to the body.\n\n rotComponent = rotSpeed * ROBOT_RADIUS / WHEEL_RADIUS;\n\n motorSpeed[MOTOR_T] = rotComponent + v2w(transSpeed * cos(transDir));\n motorSpeed[MOTOR_R] = rotComponent + v2w(transSpeed * cos(transDir - 2*PI/3));\n motorSpeed[MOTOR_L] = rotComponent + v2w(transSpeed * cos(transDir + 2*PI/3));\n\n //sp(\"MS( \");\n //for (int i=0; i<3; i++) {\n // sp(motorSpeed[i]);\n // sp(\" \");\n //}\n //sp(\") \");\n\n // ====================================================================\n // After finding the maximum and minimum motor values, limit, but NOT\n // fit, motor values to minimum and maximum throttle [TMIN, TMAX]).\n // Doing this incorrectly will result in motor values seemingly stuck\n // mostly at either extremes.\n // ====================================================================\n float mapUpper = motorSpeed[MOTOR_T] > motorSpeed[MOTOR_R] ? motorSpeed[MOTOR_T] : motorSpeed[MOTOR_R];\n mapUpper = mapUpper > motorSpeed[MOTOR_L] ? mapUpper : motorSpeed[MOTOR_L];\n mapUpper = mapUpper > MAX_MOTOR_SPEED ? mapUpper : MAX_MOTOR_SPEED;\n\n float mapLower = motorSpeed[MOTOR_T] < motorSpeed[MOTOR_R] ? motorSpeed[MOTOR_T] : motorSpeed[MOTOR_R];\n mapLower = mapLower < motorSpeed[MOTOR_L] ? mapLower : motorSpeed[MOTOR_L];\n mapLower = mapLower < -MAX_MOTOR_SPEED ? mapLower : -MAX_MOTOR_SPEED;\n\n // ====================================================================\n // If map bounds are reasonable, remap range to [mapLower, mapUpper].\n // Otherwise, kill motors. Note that map(), an Arduino function, does\n // integer math and truncates fractions.\n //\n // TODO: motorSpeed (and other quantities the Pilot calculates) should be\n // an integer representing the number of milliseconds of PWM duty\n // cycle.\n // ====================================================================\n float scale = MAX_MOTOR_SPEED / (fabs(mapUpper) > fabs(mapLower) ? fabs(mapUpper) : fabs(mapLower));\n\n for (int i=0; i<3; i++) {\n // Set direction of motors.\n digOut[i] = (motorSpeed[i] > 0) ? 1 : 0; // TODO: Check this!\n\n // Set speed of motors.\n analogOut[i] = w2analog(motorSpeed[i] * scale);\n }\n #endif // MOVE_REL_BODY\n\n\n #ifdef MOVE_REL_WORLD\n\n // Calculate motor outputs to move relative to the world.\n\n #endif // MOVE_REL_WORLD\n}\n\n#endif // MOTORS_H\n\n"
}
] | 17 |
trunghlt/cape-api-helpers | https://github.com/trunghlt/cape-api-helpers | 8ec23461d348ac9bc9881d39fffc8770e252e1e0 | 76881b2ec208451e03bd4f2f22c77fb4de184bde | 675227a13fc13add8c1e6364df8136b92ddcdb74 | refs/heads/master | 2020-04-14T00:49:38.104384 | 2018-08-10T14:22:10 | 2018-08-10T14:22:10 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.3529411852359772,
"alphanum_fraction": 0.529411792755127,
"avg_line_length": 13,
"blob_id": "58fcb32902478aecfd9cf20a82d338500726e390",
"content_id": "b6950c448f3126ddb8b0f47d4dc5287b6610e8ed",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 34,
"license_type": "permissive",
"max_line_length": 13,
"num_lines": 2,
"path": "/requirements.txt",
"repo_name": "trunghlt/cape-api-helpers",
"src_encoding": "UTF-8",
"text": "pytest==3.6.4\npydevd==1.1.1\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.6271496415138245,
"alphanum_fraction": 0.6295279860496521,
"avg_line_length": 34.96052551269531,
"blob_id": "e3a9f6d876b623a90c702cfa446e88a14de5ffa2",
"content_id": "5a263c8d03d17d3500aad749d759d43f8d3d0b92",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5466,
"license_type": "permissive",
"max_line_length": 116,
"num_lines": 152,
"path": "/cape_api_helpers/input.py",
"repo_name": "trunghlt/cape-api-helpers",
"src_encoding": "UTF-8",
"text": "# Copyright 2018 BLEMUNDSBURY AI LIMITED\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\nimport json\nfrom functools import wraps\nfrom cape_api_helpers.exceptions import UserException\nfrom cape_api_helpers.text_responses import ERROR_REQUIRED_PARAMETER, ERROR_INVALID_BOUNDING_BOX, ERROR_INVALID_JSON\n\n\ndef required_parameter(request, parameter):\n if parameter.lower() not in request['args']:\n raise UserException(ERROR_REQUIRED_PARAMETER % parameter)\n return request['args'][parameter.lower()]\n\n\ndef optional_parameter(request, parameter, default):\n if parameter.lower() in request['args']:\n return request['args'][parameter.lower()]\n else:\n return default\n\n\ndef list_document_ids(wrapped):\n \"\"\"\n Decorator for handling API calls that take as input a list of document ids.\n Calls the wrapped function with the parsed document ids\n selected by the API user.\n \"\"\"\n @wraps(wrapped)\n def decorated(request, *args, **kwargs):\n if 'documentids' in request['args']:\n if '[' == request['args']['documentids'][0]:\n document_ids = json.loads(request['args']['documentids'])\n else:\n document_ids = request['args']['documentids'].split(',')\n else:\n document_ids = None\n return wrapped(request,*args,**kwargs,document_ids=document_ids)\n\n return decorated\n\n\ndef list_saved_reply_ids(wrapped):\n \"\"\"\n Decorator for handling API calls that take as input a list of saved reply ids.\n Calls the wrapped function with the parsed saved reply ids selected by the\n API user.\n \"\"\"\n @wraps(wrapped)\n def decorated(request, *args, **kwargs):\n if 'savedreplyids' in request['args']:\n if '[' == request['args']['savedreplyids'][0]:\n saved_reply_ids = json.loads(request['args']['savedreplyids'])\n else:\n saved_reply_ids = request['args']['savedreplyids'].split(',')\n else:\n saved_reply_ids = None\n return wrapped(request, *args, **kwargs, saved_reply_ids=saved_reply_ids)\n\n return decorated\n\n\ndef list_annotation_ids(wrapped):\n \"\"\"\n Decorator for handling API calls that take as input a list of annotation ids.\n Calls the wrapped function with the parsed annotation ids selected by the\n API user.\n \"\"\"\n @wraps(wrapped)\n def decorated(request, *args, **kwargs):\n if 'annotationids' in request['args']:\n if '[' == request['args']['annotationids'][0]:\n annotation_ids = json.loads(request['args']['annotationids'])\n else:\n annotation_ids = request['args']['annotationids'].split(',')\n else:\n annotation_ids = None\n return wrapped(request, *args, **kwargs, annotation_ids=annotation_ids)\n\n return decorated\n\n\ndef list_bounding_boxes(wrapped):\n \"\"\"\n Decorator for handling API calls that take as input a list of bounding boxes.\n Calls the wrapped function with the parsed bounding boxes provided by the\n API user.\n \"\"\"\n @wraps(wrapped)\n def decorated(request, *args, **kwargs):\n if 'boundingboxes' in request['args']:\n if '[' == request['args']['boundingboxes'][0]:\n bounding_boxes = json.loads(request['args']['boundingboxes'])\n for bounding_box in bounding_boxes:\n required_keys = ['x1', 'y1', 'x2', 'y2']\n for key in required_keys:\n if key not in bounding_box.keys():\n raise UserException(ERROR_INVALID_BOUNDING_BOX % key)\n else:\n raise UserException(ERROR_INVALID_JSON)\n else:\n bounding_boxes = None\n return wrapped(request, *args, **kwargs, bounding_boxes=bounding_boxes)\n\n return decorated\n\n\ndef list_pages(wrapped):\n \"\"\"\n Decorator for handling API calls that take as input a list of pages.\n Calls the wrapped function with the parsed pages provided by the\n API user.\n \"\"\"\n @wraps(wrapped)\n def decorated(request, *args, **kwargs):\n if 'pages' in request['args']:\n if '[' == request['args']['pages'][0]:\n pages = json.loads(request['args']['pages'])\n else:\n pages = [int(page) for page in request['args']['pages'].split(',')]\n else:\n pages = None\n return wrapped(request, *args, **kwargs, pages=pages)\n\n return decorated\n\n\ndef dict_metadata(wrapped):\n \"\"\"\n Decorator for handling API calls that provide a metadata dictionary as input.\n Calls the wrapped function with the parsed metadata provided by the API user.\n \"\"\"\n @wraps(wrapped)\n def decorated(request, *args, **kwargs):\n if 'metadata' in request['args']:\n metadata = json.loads(request['args']['metadata'])\n else:\n metadata = None\n return wrapped(request, *args, **kwargs, metadata=metadata)\n\n return decorated\n"
},
{
"alpha_fraction": 0.6253501176834106,
"alphanum_fraction": 0.6276844143867493,
"avg_line_length": 37.5945930480957,
"blob_id": "8fe89b04bb47cd8cb2e9c4361dd6fe5263adaa37",
"content_id": "4aae54960b00d48b6c380f3eda6fc67846f08306",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4284,
"license_type": "permissive",
"max_line_length": 104,
"num_lines": 111,
"path": "/cape_api_helpers/output.py",
"repo_name": "trunghlt/cape-api-helpers",
"src_encoding": "UTF-8",
"text": "# Copyright 2018 BLEMUNDSBURY AI LIMITED\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\nfrom functools import wraps\n\nfrom cape_api_helpers.api_helpers_settings import SECRET_DEBUG_KEYWORD\nfrom cape_api_helpers.exceptions import UserException\nfrom cape_api_helpers.text_responses import ERROR_NUMERIC_REQUIRED, ERROR_TRUE_FALSE_BOTH_REQUIRED, \\\n DEBUG_SERVER_CONNECTION_FAILURE\n\n\ndef list_response(wrapped):\n \"\"\"\n Decorator for handling API calls that return a list of items.\n Calls the wrapped function with the number of items and offset\n requested by the API user.\n \"\"\"\n\n @wraps(wrapped)\n def decorated(request, *args, **kwargs):\n number_of_items = None\n offset = None\n if 'numberofitems' in request['args']:\n if request['args']['numberofitems'].isnumeric():\n number_of_items = int(request['args']['numberofitems'])\n else:\n raise UserException(ERROR_NUMERIC_REQUIRED % 'numberOfItems')\n if 'offset' in request['args']:\n if request['args']['offset'].isnumeric():\n offset = int(request['args']['offset'])\n else:\n raise UserException(ERROR_NUMERIC_REQUIRED % 'offset')\n\n if number_of_items is not None and offset is not None:\n return wrapped(request, number_of_items, offset)\n elif number_of_items is not None:\n return wrapped(request, number_of_items)\n elif offset is not None:\n return wrapped(request, offset=offset)\n else:\n return wrapped(request)\n\n return decorated\n\n\ndef true_false_both_filter(request, items, parameter):\n \"\"\"\n Filter a list of items based on an attribute being true, false or either.\n\n :param request: HTTP request\n :param items: list of items consisting of dictionaries\n :param parameter: The request argument to retrieve the filtering option from\n :return: A filtered list of items\n \"\"\"\n if parameter in request['args']:\n test = request['args'][parameter].lower()\n if test == 'true':\n items = [item for item in items if item[parameter]]\n elif test == 'false':\n items = [item for item in items if not item[parameter]]\n elif test == 'both':\n # Otherwise return both true and false values\n pass\n else:\n raise UserException(ERROR_TRUE_FALSE_BOTH_REQUIRED % parameter)\n\n return items\n\n\ndef debuggable(wrapped):\n @wraps(wrapped)\n def decorated(request, *args, **kwargs):\n debug_server = request['args'].get(SECRET_DEBUG_KEYWORD, False)\n if debug_server:\n import pydevd\n import socket\n hostname, port = debug_server.split(\":\")\n port = int(port)\n try:\n # we cannot check if port is open since otherwise\n # setting the wrong hostname:port will trigger an irrecoverable system exit, because :\n # We cannot monkey patch due to pydevd already heavily monkey patching\n # from _pydevd_bundle import pydevd_comm\n # pydevd_comm.start_client = start_client...\n # And this makes weird and undefined behaviour:\n # s = socket.socket()\n # s.settimeout(0.5)\n # s.connect((hostname, port))\n # s.close()\n pydevd.settrace(host=hostname, stdoutToServer=True, stderrToServer=True, port=int(port))\n except Exception:\n raise UserException(DEBUG_SERVER_CONNECTION_FAILURE)\n try:\n result = wrapped(request, *args, **kwargs)\n finally:\n if debug_server:\n pydevd.stoptrace()\n return result\n\n return decorated\n"
},
{
"alpha_fraction": 0.5950238108634949,
"alphanum_fraction": 0.6103758811950684,
"avg_line_length": 27.19403076171875,
"blob_id": "9fca7fb5c02921e0f60464b3d5cd9002547879a0",
"content_id": "65f951089739ee389a9b7d2bc8778edf1c732b2e",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1889,
"license_type": "permissive",
"max_line_length": 74,
"num_lines": 67,
"path": "/cape_api_helpers/tests/test_output.py",
"repo_name": "trunghlt/cape-api-helpers",
"src_encoding": "UTF-8",
"text": "# Copyright 2018 BLEMUNDSBURY AI LIMITED\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\nimport pytest\nfrom cape_api_helpers.output import list_response, true_false_both_filter\n\n\ndef test_list_defaults():\n \n @list_response\n def list_user(request, number_of_items=30, offset=0):\n assert number_of_items == 30\n assert offset == 0\n\n request = {'args': {}}\n list_user(request)\n\n\ndef test_list_arguments():\n\n @list_response\n def list_user(request, number_of_items=30, offset=0):\n assert number_of_items == 10\n assert offset == 5\n\n request = {'args': {'numberofitems' : '10', 'offset' : '5'}}\n list_user(request)\n\n\ndef test_filter():\n request = {'args' : {'read' : 'true'}}\n items = [\n {\n 'title' : 'Test 1',\n 'read' : True\n },\n {\n 'title' : 'Test 2',\n 'read' : False\n },\n {\n 'title' : 'Test 3',\n 'read' : False\n }\n ]\n\n filtered_items = true_false_both_filter(request, items, 'read')\n assert len(filtered_items) == 1\n \n request = {'args' : {'read' : 'false'}}\n filtered_items = true_false_both_filter(request, items, 'read')\n assert len(filtered_items) == 2\n\n request = {'args' : {'read' : 'both'}}\n filtered_items = true_false_both_filter(request, items, 'read')\n assert len(filtered_items) == 3\n"
},
{
"alpha_fraction": 0.7394800782203674,
"alphanum_fraction": 0.7411632537841797,
"avg_line_length": 66.68354797363281,
"blob_id": "26834e78db5c22c2ee56952cd06f7ff6c1c48c4d",
"content_id": "864ae9d36ce70c5679ed0b246c7cb68c96289db9",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5347,
"license_type": "permissive",
"max_line_length": 163,
"num_lines": 79,
"path": "/cape_api_helpers/text_responses.py",
"repo_name": "trunghlt/cape-api-helpers",
"src_encoding": "UTF-8",
"text": "# Copyright 2018 BLEMUNDSBURY AI LIMITED\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# Text to show the api users\nINVALID_CREDENTIALS_TEXT = 'Invalid credentials supplied'\nVALID_CREDENTIALS_TEXT = 'Valid credentials supplied'\nLOGGED_OUT_TEXT = 'User logged out'\nNOT_LOGGED_TEXT = 'This operation needs authentication. Please ensure that you have either logged in or that you are using the adminToken parameter.'\nTIMEOUT_TEXT = 'Operation took longer than anticipated and was aborted.'\nNOT_FOUND_TEXT = 'Could not find the resources to execute the operation.'\nINVALID_TOKEN = \"Token '%s' does not exist.\"\nINVALID_DOC_ID = \"One or more documents in '%s' do not exist.\"\nADMIN_ONLY = \"This functionality is only available to administrators.\"\nERROR_INVALID_PLAN = \"The plan provided is invalid got : %s was expecting : %s\"\nERROR_MAX_SIZE_INLINE_TEXT = \"This endpoint accepts text of at most %d characters but got %d\"\nERROR_TEXT = 'Something went wrong while processing the request.'\nERROR_NUMERIC_REQUIRED = \"Parameter '%s' requires a numeric value.\"\nERROR_TRUE_FALSE_BOTH_REQUIRED = \"Parameter '%s' requires a value of either 'true', 'false' or 'both'.\"\nERROR_REQUIRED_PARAMETER = \"The parameter '%s' must be set for this request.\"\nERROR_INBOX_DOES_NOT_EXIST = \"Inbox item '%s' does not exist.\"\nERROR_DOCUMENT_ALREADY_EXISTS = \"A document with the ID '%s' already exists. To replace this document please specify 'replace=true'.\"\nERROR_UPLOAD_FAILED = \"The upload was unable to complete successfully.\"\nERROR_DOCUMENT_DOES_NOT_EXIST = \"Document '%s' does not exist.\"\nERROR_INVALID_THRESHOLD = \"Threshold must be 'verylow', 'low', 'medium', 'high' or 'veryhigh'.\"\nERROR_QUESTION_DOES_NOT_EXIST = \"A question with the ID '%s' does not exist.\"\nERROR_ANSWER_DOES_NOT_EXIST = \"An answer with the ID '%s' does not exist.\"\nCANNOT_BE_POST_PARAM = \"Parameter '%s' is special and can only be a GET parameter, i.e. in the url.\"\nCANNOT_BE_GET_PARAM = \"Parameter '%s' is special and can only be a POST parameter.\"\nERROR_INVALID_JSON = \"Could not read the request, if using JSON please check the format, i.e. use \\\"double-quotes\\\" and not 'single-quotes'.\"\nERROR_INVALID_SOURCE_TYPE = \"Invalid sourceType, must be either 'document', 'saved_reply' or 'all'.\"\nERROR_INVALID_SPEED_OR_ACCURACY = \"Invalid speedOrAccuracy, must be either 'speed', 'balanced' or 'accuracy' but got %s.\"\nERROR_INVALID_TERMS = \"Invalid termsAgreed, must be either 'true' or 'false' but got %s.\"\nERROR_INVALID_USAGE = \"Invalid usage of API, for example requests containing invalid utf-8 characters.\"\nERROR_USER_DOES_NOT_EXIST = \"User '%s' does not exist.\"\n# Saved Replies\nERROR_REPLY_DOES_NOT_EXIST = \"Saved reply '%s' does not exist.\"\nERROR_REPLY_ALREADY_EXISTS = \"A reply for the question '%s' already exists.\"\nERROR_NO_SAVED_REPLY_STORE = \"Could not find any saved reply.\"\nERROR_INVALID_SLACK_RESPONSE = \"Invalid response from Slack.\"\nERROR_SLACKBOT_ALREADY_EXISTS = \"Slackbot '%s' already exists.\"\nERROR_ANNOTATION_DOES_NOT_EXIST = \"Annotation '%s' does not exist.\"\nERROR_ANNOTATION_LAST_ANSWER = \"At least one answer must be associated with an annotation.\"\nERROR_ANNOTATION_MISSING_PARAMS = \"Both the 'startOffset' and 'endOffset' parameters must be set.\"\nERROR_ANNOTATION_ALREADY_EXISTS = \"An annotation for the question '%s' already exists for this document.\"\nERROR_INVALID_BOUNDING_BOX = \"Bounding boxes must contain a '%s' key.\"\nERROR_UNRECOGNISED_SENDER = \"Sorry, your email address (%s) does not have permission to modify saved replies.\"\nERROR_EMAIL_UNCONFIGURED = \"Sorry, this Cape AI account has not yet been configured for email access.<br /><br />\" \\\n \"Please contact your Cape administrator to set this up.\"\nERROR_INVALID_EMAIL = \"Invalid email address '%s'\"\nERROR_EMAIL_TOKEN_NOT_FOUND = \"Sorry, a user with the token '%s' could not be found.<br /><br />\" \\\n \"Please contact your Cape administrator for the correct token.\"\nERROR_NO_SUGGESTIONS = \"Unfortunately Cape was unable to find any suggestions for this question.\"\n\n# Remote debugging\nDEBUG_SERVER_CONNECTION_FAILURE = \"Connection failure to debug server\"\n\n# PDF Service\nERROR_FAILED_TO_PROCESS_PDF = \"Failed to process pdf, please retry later.\"\n\n# Email\nMAILGUN_INVALID_SIGNATURE = \"Invalid credential supplied\"\nERROR_INVALID_EMAIL_TOKEN = \"Invalid verification token supplied %s, make sure you are logged-in with the user that provided the email where this token was found.\"\nERROR_EMAIL_UNVALIDATED =\"Sorry, this Cape AI account has an email that has not been verified.<br /><br />\" \\\n \"Please contact your Cape administrator to set this up.\"\n\n# Bots\nERROR_FILE_TYPE_UNSUPPORTED = \"Sorry, I can only understand plain text and markdown files at the moment.\"\nBOT_FILE_UPLOADED = \"Thanks! I'll use that to help me answer your questions.\"\n"
},
{
"alpha_fraction": 0.6921593546867371,
"alphanum_fraction": 0.6973007917404175,
"avg_line_length": 32.10638427734375,
"blob_id": "164100eea2abfee708e8014705283c1a73d4dca4",
"content_id": "f03732f2f66cad0fe92295b4cd1eaf680819d9a3",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1556,
"license_type": "permissive",
"max_line_length": 74,
"num_lines": 47,
"path": "/cape_api_helpers/tests/test_input.py",
"repo_name": "trunghlt/cape-api-helpers",
"src_encoding": "UTF-8",
"text": "# Copyright 2018 BLEMUNDSBURY AI LIMITED\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\nimport pytest\nfrom cape_api_helpers.input import required_parameter, optional_parameter\nfrom cape_api_helpers.exceptions import UserException\n\n\ndef test_required_parameter():\n request = {'args': {'test' : 'testing'}}\n test = required_parameter(request, 'test')\n assert test == 'testing'\n\n\ndef test_case_insensitive():\n request = {'args': {'test' : 'testing'}}\n test = required_parameter(request, 'TEST')\n assert test == 'testing'\n \n\ndef test_missing_required_parameter():\n with pytest.raises(UserException):\n request = {'args': {'test' : 'testing'}}\n test = required_parameter(request, 'missing')\n\n\ndef test_optional_parameter():\n request = {'args': {'test': 'testing'}}\n test = optional_parameter(request, 'test', 'hello')\n assert test == 'testing'\n\n\ndef test_missing_optional_parameter():\n request = {'args': {'test': 'testing'}}\n test = optional_parameter(request, 'missing', 'hello')\n assert test == 'hello'\n"
},
{
"alpha_fraction": 0.7966101765632629,
"alphanum_fraction": 0.7966101765632629,
"avg_line_length": 117,
"blob_id": "708f168d33436dd110869408aec17d8157a9df40",
"content_id": "5e8a131ac92a0c05761011d5acda87f1b274a8f5",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 236,
"license_type": "permissive",
"max_line_length": 180,
"num_lines": 2,
"path": "/README.md",
"repo_name": "trunghlt/cape-api-helpers",
"src_encoding": "UTF-8",
"text": "# cape-api-helpers [](https://circleci.com/gh/bloomsburyai/cape-api-helpers)\nCommon utility methods for handling API implementation\n"
},
{
"alpha_fraction": 0.6907749176025391,
"alphanum_fraction": 0.6966789960861206,
"avg_line_length": 45.72413635253906,
"blob_id": "f0daaece2cacd8c3dfa1a579637909610ec33c01",
"content_id": "e2f7cebc1934f286dbf7496facc3ea672a7e1cc8",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1355,
"license_type": "permissive",
"max_line_length": 117,
"num_lines": 29,
"path": "/cape_api_helpers/headers.py",
"repo_name": "trunghlt/cape-api-helpers",
"src_encoding": "UTF-8",
"text": "# Copyright 2018 BLEMUNDSBURY AI LIMITED\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\nfrom logging import debug\n\ndef generate_cors_headers(request):\n CORS_HEADERS = {'Access-Control-Allow-Origin': '*',\n 'Access-Control-Allow-Credentials': 'true',\n 'Access-Control-Allow-Methods': 'GET, POST, PATCH, PUT, DELETE, OPTIONS',\n 'Access-Control-Allow-Headers': 'Origin, Content-Type, X-Auth-Token'}\n\n # To support full cross site access we need to add the requesting origin to the access control headers explicitly\n for header in request.headers.keys():\n if header.lower() == 'origin':\n CORS_HEADERS['Access-Control-Allow-Origin'] = request.headers['origin']\n break\n debug(f'Added CORS headers to request {getattr(request,\"url\",None)}')\n return CORS_HEADERS\n"
}
] | 8 |
Vyacheslau/behave-example-python | https://github.com/Vyacheslau/behave-example-python | 42525873e807ad67747731030ea8c7fb5908e941 | b3a39e4966db0e0de88bd50cbf7d2280a71d3b2e | 7d51f0d37eba76c5dcd1ba1da07d2c3c666ef240 | refs/heads/master | 2016-09-06T19:02:38.538800 | 2015-05-16T13:10:25 | 2015-05-16T13:10:25 | 35,723,977 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6423221230506897,
"alphanum_fraction": 0.6423221230506897,
"avg_line_length": 24.4761905670166,
"blob_id": "7b05ef3a6ae9a9d051b936a4e55442367468427d",
"content_id": "f471e3d43f526ed9b429ff313cbce86a2c3c54d6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 534,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 21,
"path": "/features/steps/arithmetic_steps.py",
"repo_name": "Vyacheslau/behave-example-python",
"src_encoding": "UTF-8",
"text": "__author__ = 'Vyacheslau Karachun'\n\n\nfrom behave import *\n\n\n@given('\"{var_name}\" is equal \"{value}\"')\ndef assign_var(context, var_name, value):\n context.vars_dict[var_name] = int(value)\n\n\n@when('\"{var_one}\" \"{operation_arg}\" \"{var_two}\"')\ndef operation(context, var_one, var_two, operation_arg):\n if operation_arg == \"+\":\n context.result = context.vars_dict[var_one] + context.vars_dict[var_two]\n\n\n@then('result is \"{result}\"')\ndef verify_result(context, result):\n if not context.result == int(result):\n raise AssertionError"
},
{
"alpha_fraction": 0.6000000238418579,
"alphanum_fraction": 0.6000000238418579,
"avg_line_length": 15,
"blob_id": "87c553b04e22560d218bc0495fd59965b5f62307",
"content_id": "ef9a851cbe6cc1ea9e5aafb42c1e64a608a0fedc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 80,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 5,
"path": "/features/environment.py",
"repo_name": "Vyacheslau/behave-example-python",
"src_encoding": "UTF-8",
"text": "__author__ = 'Vyacheslau Karachun'\n\n\ndef before_all(context):\n context.vars_dict = dict()\n"
},
{
"alpha_fraction": 0.4545454680919647,
"alphanum_fraction": 0.4545454680919647,
"avg_line_length": 21,
"blob_id": "e88faee3b8f1658f9bbab640ab2b5748f815c1ea",
"content_id": "e6a4ebb25bdd3a92b1a1fd2c993bbdd321e3315f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 22,
"license_type": "no_license",
"max_line_length": 21,
"num_lines": 1,
"path": "/features/steps/__init__.py",
"repo_name": "Vyacheslau/behave-example-python",
"src_encoding": "UTF-8",
"text": "__author__ = 'Vyacheslau Karachun'\n"
}
] | 3 |
HarshaSatyavardhan/Image-denosing | https://github.com/HarshaSatyavardhan/Image-denosing | 1657f102351ead0fac555c3eb146b0069d32c075 | 45de9352d4269c5d2df2c256b4f0dc7fd8063dad | a59a6041709198c03863ca87c91cc8ee6265e64b | refs/heads/main | 2023-05-29T20:30:21.707423 | 2021-06-12T07:31:01 | 2021-06-12T07:31:01 | 373,574,456 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6391982436180115,
"alphanum_fraction": 0.6614699363708496,
"avg_line_length": 19.285715103149414,
"blob_id": "dc9f5e5a9ae4b449e1dbfc2bd550b77b03bdf038",
"content_id": "449bbbb4e5998a0ca0335759c357fdb83bbfbd4a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 449,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 21,
"path": "/add guassian blur.py",
"repo_name": "HarshaSatyavardhan/Image-denosing",
"src_encoding": "UTF-8",
"text": "#\r\n\r\nimport cv2\r\nimport numpy as np\r\nimport skimage\r\nimport os\r\n\r\n#load images from a folder\r\n\r\ndef load_images_folder(folder):\r\n images = []\r\n for filename in os.listdir(folder):\r\n img = cv2.imread(os.path.join(folder, filename))\r\n\r\n noise_img = skimage.util.random_noise(img, mode='gaussian', var=0.01)\r\n noise_img = (255*noise_img).astype(np.uint8)\r\n cv2.imwrite(filename, noise_img)\r\n \r\n\r\n\r\nload_images_folder('/content/data')\r\n\r\n"
},
{
"alpha_fraction": 0.6153846383094788,
"alphanum_fraction": 0.6678321957588196,
"avg_line_length": 22,
"blob_id": "97eb1b3039368200115f8a2e05565d8954c0217e",
"content_id": "bf07352765f7454c560a9172b96c874f98723d91",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 286,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 12,
"path": "/file path change.py",
"repo_name": "HarshaSatyavardhan/Image-denosing",
"src_encoding": "UTF-8",
"text": "#128*128\r\n#tif to jpeg\r\nimport os\r\nimport cv2\r\n\r\npath = '/content/chasedb1/'\r\ndata = '/content/data/'\r\n\r\nfor filename in os.listdir(path):\r\n img = cv2.imread(path+filename)\r\n outfile = filename.split('.')[0]+'.jpg'\r\n cv2.imwrite(data+outfile,img,[int(cv2.IMWRITE_JPEG_QUALITY), 200])"
}
] | 2 |
ChadAMiller/roguelike-2019 | https://github.com/ChadAMiller/roguelike-2019 | 1811ede0483bb57f8ea62f90a3c75d1500bd259f | 8eca444209eb8eb0eee090b604249205465508a5 | f96c68fbbb8dee65c23019bb3398c4ccb30d2c5f | refs/heads/master | 2022-09-28T11:25:01.175198 | 2022-08-29T01:15:30 | 2022-08-29T01:15:30 | 194,747,815 | 5 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6120442152023315,
"alphanum_fraction": 0.6136829257011414,
"avg_line_length": 34.39130401611328,
"blob_id": "22eaf6efc1da5a584955a262c4b52df311a6a88f",
"content_id": "0f77181ec722bb85bd8d66ce063e2ad48d7614c5",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2441,
"license_type": "permissive",
"max_line_length": 153,
"num_lines": 69,
"path": "/components/status_effects.py",
"repo_name": "ChadAMiller/roguelike-2019",
"src_encoding": "UTF-8",
"text": "from components.component import Component\n\nfrom game_messages import Message\n\nclass StatusEffect(Component):\n def __init__(self, status_name, effect, duration):\n super().__init__('status_effect')\n self.status_name = status_name\n self.effect = effect\n self.duration = duration\n\nclass StatusEffects(Component):\n def __init__(self):\n super().__init__('status_effects')\n self.active_statuses = {}\n\n def add_status(self, status):\n # Current stacking rules are that adding another status of the same name resets the duration. They don't stack, so you can't be 'double poisoned'\n self.active_statuses[status.status_name] = status\n\n def process_statuses(self):\n\n results = []\n\n to_delete = set()\n for name, status in self.active_statuses.items():\n if status.duration >= 1:\n status.duration -= 1\n results.extend(status.effect(self.owner))\n\n if status.duration == 0:\n to_delete.add(name)\n\n for name in to_delete:\n del self.active_statuses[name]\n results.append({'message': Message(\"{0} wore off.\".format(name))})\n\n return results\n\nclass HealOverTime(StatusEffect):\n def __init__(self, status_name, amount, duration):\n self.amount = amount\n def effect(target):\n target.fighter.heal(amount)\n return []\n\n super().__init__(status_name, effect, duration)\n\n def __getstate__(self):\n # This getstate/setstate business is so that the effect can be incorporated in a save game. Don't know how I'll generalize this yet.\n return {'status_name': self.status_name, 'amount': self.amount, 'duration': self.duration}\n\n def __setstate__(self, state):\n self.__init__(state['status_name'], state['amount'], state['duration'])\n \nclass DamageOverTime(StatusEffect):\n def __init__(self, status_name, amount, duration):\n self.amount = amount\n def effect(target):\n # unlike healing, take_damage returns results\n return target.fighter.take_damage(amount)\n \n super().__init__(status_name, effect, duration)\n\n def __getstate__(self):\n return {'status_name': self.status_name, 'amount': self.amount, 'duration': self.duration}\n\n def __setstate__(self, state):\n self.__init__(state['status_name'], state['amount'], state['duration'])"
},
{
"alpha_fraction": 0.5952380895614624,
"alphanum_fraction": 0.5952380895614624,
"avg_line_length": 21.46666717529297,
"blob_id": "b7d7e191cd943007fe3ae330f25eb19417c0c547",
"content_id": "2b94e8d8ad29f9e4e533aeb87866338fe8025098",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 336,
"license_type": "permissive",
"max_line_length": 29,
"num_lines": 15,
"path": "/game_states.py",
"repo_name": "ChadAMiller/roguelike-2019",
"src_encoding": "UTF-8",
"text": "from enum import Enum, auto\n\nclass GameStates(Enum):\n PLAYERS_TURN = auto()\n ENEMY_TURN = auto()\n PLAYER_DEAD = auto()\n SHOW_INVENTORY = auto()\n DROP_INVENTORY = auto()\n TARGETING = auto()\n LEVEL_UP = auto()\n CHARACTER_SCREEN = auto()\n WON_GAME = auto()\n\nif __name__ == '__main__':\n print(list(GameStates))"
},
{
"alpha_fraction": 0.7044673562049866,
"alphanum_fraction": 0.7044673562049866,
"avg_line_length": 51.90909194946289,
"blob_id": "3731d045908ef4314e8fc8b901fbae9f16ee71c7",
"content_id": "ee75ad8d38a3cc8e498bf831d29b5ab66a8d1a9f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 582,
"license_type": "permissive",
"max_line_length": 150,
"num_lines": 11,
"path": "/components/item.py",
"repo_name": "ChadAMiller/roguelike-2019",
"src_encoding": "UTF-8",
"text": "from components.component import Component\n\nclass Item(Component):\n def __init__(self, use_function=None, targeting=False, targeting_message=None, targeting_radius=None, **kwargs):\n super().__init__('item')\n self.use_function = use_function\n self.targeting = targeting\n self.targeting_message = targeting_message\n self.targeting_radius = targeting_radius\n kwargs['targeting_radius'] = targeting_radius # this allows the spells to see their own radius while also leaving it available to the renderer\n self.function_kwargs = kwargs\n"
},
{
"alpha_fraction": 0.5990098714828491,
"alphanum_fraction": 0.6041584014892578,
"avg_line_length": 35.07143020629883,
"blob_id": "36b096441222d811cde20ad32100ab490b01e778",
"content_id": "3de4c2574c7fed0d54f4665404eda404f54a832e",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5050,
"license_type": "permissive",
"max_line_length": 121,
"num_lines": 140,
"path": "/components/ai.py",
"repo_name": "ChadAMiller/roguelike-2019",
"src_encoding": "UTF-8",
"text": "import tcod as libtcod\n\nfrom random import randint\n\nfrom components.component import Component\nfrom game_messages import Message\n\nfrom components import status_effects\n\nimport map_objects.monsters as monsters\n\nclass AiComponent(Component):\n def __init__(self):\n super().__init__('ai')\n\nclass BasicMonster(AiComponent):\n def take_turn(self, target, fov_map, game_map):\n results = []\n\n monster = self.owner\n if libtcod.map_is_in_fov(fov_map, monster.x, monster.y):\n\n if monster.distance_to(target) >= 2:\n monster.move_astar(target, game_map)\n\n elif target.fighter.hp > 0:\n attack_results = monster.fighter.attack(target)\n results.extend(attack_results)\n\n return results\n\nclass ConfusedMonster(AiComponent):\n def __init__(self, previous_ai, number_of_turns=10):\n super().__init__()\n self.previous_ai = previous_ai\n self.number_of_turns = number_of_turns\n\n def take_turn(self, target, fov_map, game_map):\n results = []\n\n if self.number_of_turns > 0:\n random_x = self.owner.x + randint(0, 2) - 1\n random_y = self.owner.y + randint(0, 2) - 1\n\n if random_x != self.owner.x and random_y != self.owner.y:\n self.owner.move_towards(random_x, random_y, game_map)\n\n self.number_of_turns -= 1\n\n else:\n self.owner.ai = self.previous_ai\n results.append({'message': Message('The {0} is no longer confused!'.format(self.owner.name), libtcod.red)})\n\n return results\n\nclass WraithMonster(AiComponent):\n def __init__(self):\n super().__init__()\n self.player_spotted = False\n\n def take_turn(self, target, fov_map, game_map):\n results = []\n monster = self.owner\n\n # Return without doing anything until it spots the player for the first time\n if not self.player_spotted and not libtcod.map_is_in_fov(fov_map, monster.x, monster.y):\n return results\n\n self.player_spotted = True\n self.owner.move_towards(target.x, target.y, game_map, ignore_blocking=True)\n\n if monster.distance_to(target) == 0:\n results.append({'message': Message(\"The wraith has haunted you!\")})\n target.status_effects.add_status(status_effects.DamageOverTime('Haunted', 5, 10))\n results.extend(monster.fighter.take_damage(1))\n \n return results\n\nclass SnakeMonster(AiComponent):\n def take_turn(self, target, fov_map, game_map):\n results = []\n\n monster = self.owner\n if libtcod.map_is_in_fov(fov_map, monster.x, monster.y):\n\n if 'Poisoned' in target.status_effects.active_statuses:\n # run for the exit if player is already poisoned, or in a random direction if path to the exit is blocked\n current_position = monster.x, monster.y\n stairs = game_map.find_exit()\n monster.move_astar(stairs, game_map, max_path=None)\n if current_position == (monster.x, monster.y):\n monster.flee(target, game_map)\n \n elif monster.distance_to(target) >= 2:\n monster.move_astar(target, game_map)\n\n elif target.fighter.hp > 0:\n attack_results = monster.fighter.attack(target)\n results.append({'message': Message(\"The snake has poisoned you!\")})\n target.status_effects.add_status(status_effects.DamageOverTime('Poisoned', 1, 20))\n results.extend(attack_results)\n\n return results\n\nclass ArcherMonster(AiComponent):\n def take_turn(self, target, fov_map, game_map):\n results = []\n monster = self.owner\n if libtcod.map_is_in_fov(fov_map, monster.x, monster.y):\n if monster.distance_to(target) <= 2:\n monster.flee(target, game_map)\n\n elif target.fighter.hp > 0:\n attack_results = monster.fighter.attack(target)\n results.extend(attack_results)\n\n return results\n\nclass NecromancerMonster(AiComponent):\n def take_turn(self, target, fov_map, game_map):\n results = []\n monster = self.owner\n\n nearest_corpse = game_map.find_entity(lambda e: e.char == '%', lambda e: e.distance_to(monster))\n\n if libtcod.map_is_in_fov(fov_map, monster.x, monster.y):\n results.extend(monster.fighter.attack(target))\n elif not nearest_corpse:\n # hunt player if no corpses on the floor\n monster.move_astar(target, game_map, max_path=None)\n elif monster.distance_to(nearest_corpse) <= 3:\n # use nearest corpse to spawn a skeleton\n x, y = nearest_corpse.x, nearest_corpse.y\n game_map.entities.remove(nearest_corpse)\n game_map.entities.append(monsters.Skeleton(x, y))\n else:\n # hunt down the nearest corpse to reanimate\n monster.move_astar(nearest_corpse, game_map, max_path=None)\n\n return results\n"
},
{
"alpha_fraction": 0.6494969725608826,
"alphanum_fraction": 0.6503018140792847,
"avg_line_length": 42.596492767333984,
"blob_id": "f920a8ced2db90f17ba61eec5f0757095ce01c3e",
"content_id": "ca5f32519d9d044c84d073afde0a008c9764dbf7",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2485,
"license_type": "permissive",
"max_line_length": 112,
"num_lines": 57,
"path": "/components/exit.py",
"repo_name": "ChadAMiller/roguelike-2019",
"src_encoding": "UTF-8",
"text": "from components.component import Component\nfrom game_messages import Message\n\nimport map_objects.monsters as monsters\n\nclass Exit(Component):\n def __init__(self, destination=tuple(), new_floor=None): \n super().__init__('exit')\n # destination defaults to the empty tuple because we want a falsy, immutable, ordered container\n # if a destination isn't given here, the new floor will have to be defined some other way\n self.destination = destination\n # Sets the destination now if a new floor was provided\n self.new_floor = new_floor\n\n def take_exit(self, player, message_log):\n # This is here for subclasses to override if they want to add logic before moving to the next room\n # e.g. the default game's healing before progressing to a new floor\n return self.next_floor\n\n @property\n def next_floor(self):\n if not self.new_floor:\n # construct the new floor if it doesn't exist yet\n # currently just letting this throw an exception if no destination was ever defined\n floor_constructor, args, kwargs = self.destination\n self.new_floor = floor_constructor(*args, **kwargs)\n\n return self.new_floor\n\nclass DownStairsExit(Exit):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.already_taken = False\n\n def take_exit(self, player, message_log):\n if not self.already_taken:\n self.already_taken = True\n player.fighter.heal(player.fighter.max_hp // 2)\n message_log.add_message(Message('You take a moment to rest, and recover your strength.'))\n\n return super().take_exit(player, message_log)\n\nclass UpStairsExit(Exit):\n def __init__(self, *args, **kwargs):\n super().__init__(*args, **kwargs)\n self.taken_with_chalice = False\n\n def take_exit(self, player, message_log):\n if not self.taken_with_chalice and any(item.name == 'Magic Chalice' for item in player.inventory.items):\n self.taken_with_chalice = True\n player.fighter.heal(player.fighter.max_hp // 5)\n message_log.add_message(Message('You feel energized by the Chalice.'))\n next_upstairs = self.next_floor.find_entity(lambda e: e.name == \"Stairs (Up)\")\n if next_upstairs:\n self.next_floor.entities.append(monsters.Necromancer(next_upstairs.x, next_upstairs.y))\n\n return super().take_exit(player, message_log)\n"
},
{
"alpha_fraction": 0.6496930122375488,
"alphanum_fraction": 0.67136150598526,
"avg_line_length": 29.09782600402832,
"blob_id": "356f1c56137e37aae8eb01986360b00147ba085e",
"content_id": "2e905e96381ca0900530ab88d66861402dde07cc",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2769,
"license_type": "permissive",
"max_line_length": 109,
"num_lines": 92,
"path": "/loader_functions/initialize_new_game.py",
"repo_name": "ChadAMiller/roguelike-2019",
"src_encoding": "UTF-8",
"text": "import tcod as libtcod\n\nfrom components.equipment import Equipment\nfrom components.equippable import Equippable\nfrom components.fighter import Fighter\nfrom components.inventory import Inventory\nfrom components.level import Level\nfrom components.status_effects import StatusEffects\n\nfrom entity import Entity\nfrom equipment_slots import EquipmentSlots\nfrom game_messages import MessageLog\nfrom game_states import GameStates\nfrom map_objects.game_map import World\nfrom render_functions import RenderOrder\n\n\ndef get_constants():\n window_title = 'Roguelike Tutorial Overhauled'\n\n screen_width = 80\n screen_height = 50\n\n bar_width = 20\n panel_height = 7\n panel_y = screen_height - panel_height\n\n message_x = bar_width + 2\n message_width = screen_width - bar_width - 2\n message_height = panel_height - 1\n\n map_width = 80\n map_height = 43\n\n fov_algorithm = 0\n fov_light_walls = True\n fov_radius = 10\n\n colors = {\n 'dark_wall': libtcod.Color(0, 0, 100),\n 'dark_ground': libtcod.Color(50, 50, 150),\n 'light_wall': libtcod.Color(130, 110, 50),\n 'light_ground': libtcod.Color(200, 180, 50),\n }\n\n constants = {\n 'window_title': window_title,\n 'screen_width': screen_width,\n 'screen_height': screen_height,\n 'bar_width': bar_width,\n 'panel_height': panel_height,\n 'panel_y': panel_y,\n 'message_x': message_x,\n 'message_width': message_width,\n 'message_height': message_height,\n 'map_width': map_width,\n 'map_height': map_height,\n 'fov_algorithm': fov_algorithm,\n 'fov_light_walls': fov_light_walls,\n 'fov_radius': fov_radius,\n 'colors': colors,\n }\n\n return constants\n\ndef get_game_variables(constants):\n player = Entity(0, 0, '@', libtcod.white, 'Player', blocks=True, render_order=RenderOrder.ACTOR)\n Fighter(hp=100, defense=11, power=2, hit=11).add_to_entity(player)\n Level().add_to_entity(player)\n\n inventory_component = Inventory(26)\n inventory_component.add_to_entity(player)\n \n equipment_component = Equipment()\n equipment_component.add_to_entity(player)\n\n dagger = Entity(0, 0, '-', libtcod.sky, 'Dagger')\n equippable_component = Equippable(EquipmentSlots.MAIN_HAND, power_bonus=2)\n equippable_component.add_to_entity(dagger) \n \n inventory_component.add_item(dagger)\n equipment_component.toggle_equip(dagger)\n\n StatusEffects().add_to_entity(player)\n \n world = World(player, constants['map_width'], constants['map_height'])\n\n message_log = MessageLog(constants['message_x'], constants['message_width'], constants['message_height'])\n\n game_state = GameStates.PLAYERS_TURN\n\n return player, world, message_log, game_state\n"
},
{
"alpha_fraction": 0.7331887483596802,
"alphanum_fraction": 0.735357940196991,
"avg_line_length": 26.117647171020508,
"blob_id": "5e35b83da2708d1ba130cc029261ad1f59a0fe94",
"content_id": "4d5c8b3731791744db636d265bad9150a0205ef4",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 461,
"license_type": "permissive",
"max_line_length": 93,
"num_lines": 17,
"path": "/death_functions.py",
"repo_name": "ChadAMiller/roguelike-2019",
"src_encoding": "UTF-8",
"text": "import tcod as libtcod\n\nfrom game_messages import Message\nfrom game_states import GameStates\nfrom render_functions import RenderOrder\n\ndef kill_player(player):\n player.char = '%'\n player.color = libtcod.dark_red\n\n return Message('You died!', libtcod.red), GameStates.PLAYER_DEAD\n\n\ndef kill_monster(monster):\n death_message = Message('{0} is dead!'.format(monster.name.capitalize()), libtcod.orange)\n monster.set_corpse()\n return death_message\n"
},
{
"alpha_fraction": 0.6857048273086548,
"alphanum_fraction": 0.6903268694877625,
"avg_line_length": 46.328125,
"blob_id": "5ec1c35d23f3db1d2587115c41f53f85892fc823",
"content_id": "5f51c4efa8a6ccd32d9b135575740b306a976a2c",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3029,
"license_type": "permissive",
"max_line_length": 241,
"num_lines": 64,
"path": "/map_objects/items.py",
"repo_name": "ChadAMiller/roguelike-2019",
"src_encoding": "UTF-8",
"text": "import tcod as libtcod\n\nfrom functools import partial\n\nimport item_functions\n\nfrom components.equippable import Equippable\nfrom components.item import Item\nfrom entity import Entity\nfrom equipment_slots import EquipmentSlots\nfrom game_messages import Message\nfrom render_functions import RenderOrder\n\nclass HealingPotion(Entity):\n def __init__(self, x, y):\n super().__init__(x, y, '!', libtcod.violet, 'Healing Potion', render_order=RenderOrder.ITEM)\n Item(use_function=item_functions.heal, amount=40).add_to_entity(self)\n\nclass RejuvenationPotion(Entity):\n def __init__(self, x, y):\n super().__init__(x, y, '!', libtcod.desaturated_blue, \"Potion of Rejuvenation\", render_order=RenderOrder.ITEM)\n Item(use_function=item_functions.regenerate, name=\"Potion of Rejuvenation\", amount=10, duration=4).add_to_entity(self)\n\nclass Sword(Entity):\n def __init__(self, x, y, bonus=3):\n super().__init__(x, y, '/', libtcod.sky, 'Sword (+{})'.format(bonus))\n Equippable(EquipmentSlots.MAIN_HAND, power_bonus=bonus).add_to_entity(self)\n\nclass Shield(Entity):\n def __init__(self, x, y, bonus=1):\n super().__init__(x, y, '[', libtcod.orange, 'Shield (+{})'.format(bonus))\n Equippable(EquipmentSlots.OFF_HAND, defense_bonus=bonus).add_to_entity(self)\n\nclass FireballScroll(Entity):\n def __init__(self, x, y):\n super().__init__(x, y, '#', libtcod.red, 'Fireball Scroll', render_order=RenderOrder.ITEM)\n Item(use_function=item_functions.cast_fireball, targeting=True, targeting_message=Message('Left-click a target tile for the fireball, or right-click to cancel.', libtcod.light_cyan), targeting_radius=3, damage=25).add_to_entity(self)\n\n def valid_target(self, mouse, fov_map, entity):\n return libtcod.map_is_in_fov(fov_map, mouse.cx, mouse.cy) and entity.try_component('fighter')\n\nclass LightningScroll(Entity):\n def __init__(self, x, y):\n super().__init__(x, y, '#', libtcod.yellow, 'Lightning Scroll', render_order=RenderOrder.ITEM)\n Item(use_function=item_functions.cast_lightning, damage=40, maximum_range=5).add_to_entity(self)\n\nclass ConfusionScroll(Entity):\n def __init__(self, x, y):\n super().__init__(x, y, '#', libtcod.light_pink, 'Confusion Scroll', render_order=RenderOrder.ITEM)\n Item(use_function=item_functions.cast_confuse, targeting=True, targeting_message=Message('Left-click and enemy to confuse it, or right-click to cancel.', libtcod.light_cyan), targeting_radius=0).add_to_entity(self)\n\n def valid_target(self, mouse, fov_map, entity):\n return libtcod.map_is_in_fov(fov_map, mouse.cx, mouse.cy) and entity.try_component('ai')\n\nclass Chalice(Entity):\n def __init__(self, x, y):\n super().__init__(x, y, 'y', libtcod.violet, 'Magic Chalice', render_order=RenderOrder.ITEM)\n Item(use_function=item_functions.rub_chalice).add_to_entity(self)\n\ndef sword_class(bonus):\n return partial(Sword, bonus=bonus)\n\ndef shield_class(bonus):\n return partial(Shield, bonus=bonus)\n"
},
{
"alpha_fraction": 0.5865921974182129,
"alphanum_fraction": 0.5865921974182129,
"avg_line_length": 24.571428298950195,
"blob_id": "2052f8567ea51b16c1f4c7e6ed944b92eab530de",
"content_id": "049426abbab7e013117468df44eed8787ba6ceb4",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 179,
"license_type": "permissive",
"max_line_length": 40,
"num_lines": 7,
"path": "/components/component.py",
"repo_name": "ChadAMiller/roguelike-2019",
"src_encoding": "UTF-8",
"text": "class Component:\n def __init__(self, name):\n self.name = name\n\n def add_to_entity(self, entity):\n setattr(entity, self.name, self)\n self.owner = entity\n"
},
{
"alpha_fraction": 0.7803992629051208,
"alphanum_fraction": 0.803992748260498,
"avg_line_length": 54.099998474121094,
"blob_id": "a063b5be2635aca58cc3de6636a6cce78100305b",
"content_id": "f3b79cd5cf50f099e179fa2bc50fe72c898b066a",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 551,
"license_type": "permissive",
"max_line_length": 170,
"num_lines": 10,
"path": "/README.md",
"repo_name": "ChadAMiller/roguelike-2019",
"src_encoding": "UTF-8",
"text": "# roguelike-2019\nPython roguelike inspired by \"RoguelikeDev Does The Complete Roguelike Tutorial\" on reddit\n\nThis is a learning project shared for discussion purposes. I've made practically no effort to make this run on any machine but my own. Suggestions/contributions welcomed.\n\n[Original tutorial](http://rogueliketutorials.com/tutorials/tcod/)\n\n[Reddit link](https://old.reddit.com/r/roguelikedev/wiki/python_tutorial_series)\n\n[Blog series on my changes](https://projectwirehead.home.blog/2019/07/02/roguelike-tutorial-week-2-sanding-some-edges/)\n"
},
{
"alpha_fraction": 0.6079610586166382,
"alphanum_fraction": 0.6274341344833374,
"avg_line_length": 36.956520080566406,
"blob_id": "e4451c08ba6c49749bec54878a5500acf38819ce",
"content_id": "ec2a29480ae220e6e45995ac9bb201703b79cce1",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3492,
"license_type": "permissive",
"max_line_length": 120,
"num_lines": 92,
"path": "/map_objects/monsters.py",
"repo_name": "ChadAMiller/roguelike-2019",
"src_encoding": "UTF-8",
"text": "import tcod as libtcod\n\nimport components.ai as ai\n\nfrom components.fighter import Fighter\nfrom entity import Entity\nfrom render_functions import RenderOrder\n\nclass Monster(Entity):\n def __init__(self, x, y, char, color, name, blocks=True, render_order=RenderOrder.ACTOR):\n super().__init__(x, y, char, color, name, blocks, render_order)\n\n def set_corpse(self):\n self.char = '%'\n self.color = libtcod.dark_red\n self.blocks = False\n self.fighter = None\n self.ai = None\n self.name = 'remains of ' + self.name\n self.render_order = RenderOrder.CORPSE\n\nclass Orc(Monster):\n def __init__(self, x, y):\n super().__init__(x, y, 'o', libtcod.desaturated_green, 'Orc', blocks=True, render_order=RenderOrder.ACTOR)\n\n Fighter(hp=20, defense=11, power=4, hit=5, xp=35).add_to_entity(self)\n ai.BasicMonster().add_to_entity(self)\n\nclass Troll(Monster):\n def __init__(self, x, y):\n super().__init__(x, y, 'T', libtcod.darker_green, 'Troll', blocks=True, render_order=RenderOrder.ACTOR)\n\n Fighter(hp=30, defense=13, power=8, hit=7, xp=100).add_to_entity(self)\n ai.BasicMonster().add_to_entity(self)\n\nclass Balrog(Monster):\n def __init__(self, x, y):\n super().__init__(x, y, 'B', libtcod.dark_flame, 'Balrog', blocks=True, render_order=RenderOrder.ACTOR)\n\n Fighter(hp=45, defense=16, power=12, hit=11, xp=250).add_to_entity(self)\n ai.BasicMonster().add_to_entity(self)\n\nclass Wraith(Monster):\n def __init__(self, x, y):\n super().__init__(x, y, 'w', libtcod.han, 'Wraith', blocks=False, render_order=RenderOrder.ACTOR)\n\n # currently player doesn't get XP for a monster that kills itself like the wraith usually does\n Fighter(hp=1, defense=0, power=0, hit=0, xp=50).add_to_entity(self)\n ai.WraithMonster().add_to_entity(self)\n\n def set_corpse(self):\n self.blocks = False\n self.fighter = None\n self.ai = None\n self.name = ''\n self.render_order = RenderOrder.INVISIBLE\n\nclass Snake(Monster):\n def __init__(self, x, y):\n super().__init__(x, y, 'S', libtcod.darkest_green, 'Snake', blocks=True, render_order=RenderOrder.ACTOR)\n\n # It has no power because it poisons you. Poison effect is in the AI.\n Fighter(hp=20, defense=11, power=0, hit=0, xp=50).add_to_entity(self)\n ai.SnakeMonster().add_to_entity(self)\n\nclass Archer(Monster):\n def __init__(self, x, y):\n super().__init__(x, y, 'a', libtcod.darkest_gray, 'Archer', blocks=True, render_order=RenderOrder.ACTOR)\n\n Fighter(hp=5, defense=11, power=2, hit=11, xp=75).add_to_entity(self)\n ai.ArcherMonster().add_to_entity(self)\n\nclass Skeleton(Monster):\n def __init__(self, x, y):\n super().__init__(x, y, 's', libtcod.white, 'Skeleton', blocks=True, render_order=RenderOrder.ACTOR)\n\n Fighter(hp=10, defense=5, power=10, hit=5, xp=25).add_to_entity(self)\n ai.BasicMonster().add_to_entity(self)\n\n def set_corpse(self):\n self.blocks = False\n self.fighter = None\n self.ai = None\n self.name = ''\n self.render_order = RenderOrder.INVISIBLE\n\nclass Necromancer(Monster):\n def __init__(self, x, y):\n super().__init__(x, y, 'n', libtcod.darkest_crimson, 'Necromancer', blocks=True, render_order=RenderOrder.ACTOR)\n\n Fighter(hp=40, defense=10, power=3, hit=15, xp=250).add_to_entity(self)\n ai.NecromancerMonster().add_to_entity(self)\n"
},
{
"alpha_fraction": 0.6200717091560364,
"alphanum_fraction": 0.6254480481147766,
"avg_line_length": 31.823530197143555,
"blob_id": "cd43d92413b250a743dd52b88ad7af9402787cea",
"content_id": "a2db59b1e1d883ec9e1ffbbbd8cde42afbb8795a",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 558,
"license_type": "permissive",
"max_line_length": 77,
"num_lines": 17,
"path": "/components/equippable.py",
"repo_name": "ChadAMiller/roguelike-2019",
"src_encoding": "UTF-8",
"text": "from components.component import Component\nfrom components.item import Item\n\nclass Equippable(Component):\n def __init__(self, slot, power_bonus=0, defense_bonus=0, max_hp_bonus=0):\n super().__init__('equippable')\n self.slot = slot\n self.power_bonus = power_bonus\n self.defense_bonus = defense_bonus\n self.max_hp_bonus = max_hp_bonus\n\n def add_to_entity(self, entity):\n super().add_to_entity(entity)\n\n if not entity.try_component('item'):\n item = Item()\n item.add_to_entity(entity)\n"
},
{
"alpha_fraction": 0.6566133499145508,
"alphanum_fraction": 0.6624273061752319,
"avg_line_length": 46.44827651977539,
"blob_id": "0a8db5deb3635432bdfc2c05a446375478c75e76",
"content_id": "97be802da33f353973ebf1a36ba72cecd6b5edee",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5504,
"license_type": "permissive",
"max_line_length": 188,
"num_lines": 116,
"path": "/render_functions.py",
"repo_name": "ChadAMiller/roguelike-2019",
"src_encoding": "UTF-8",
"text": "import tcod as libtcod\n\nfrom enum import Enum, auto\n\nfrom game_states import GameStates\nfrom menus import character_screen, inventory_menu, level_up_menu, win_screen\n\nclass RenderOrder(Enum):\n INVISIBLE = auto()\n STAIRS = auto()\n CORPSE = auto()\n ITEM = auto()\n ACTOR = auto()\n\ndef get_names_under_mouse(mouse, entities, fov_map):\n (x, y) = (mouse.cx, mouse.cy)\n\n names = [entity.name for entity in entities if entity.x == x and entity.y == y and libtcod.map_is_in_fov(fov_map, entity.x, entity.y) and entity.render_order != RenderOrder.INVISIBLE]\n names = ', '.join(names)\n\n return names.capitalize()\n\ndef render_bar(panel, x, y, total_width, name, value, maximum, bar_color, back_color):\n bar_width = int(float(value) / maximum * total_width)\n\n libtcod.console_set_default_background(panel, back_color)\n libtcod.console_rect(panel, x, y, total_width, 1, False, libtcod.BKGND_SCREEN)\n\n libtcod.console_set_default_background(panel, bar_color)\n if bar_width > 0:\n libtcod.console_rect(panel, x, y, bar_width, 1, False, libtcod.BKGND_SCREEN)\n\n libtcod.console_set_default_foreground(panel, libtcod.white)\n libtcod.console_print_ex(panel, int(x + total_width / 2), y, libtcod.BKGND_NONE, libtcod.CENTER, '{0}: {1}/{2}'.format(name, value, maximum))\n\ndef render_all(con, panel, player, game_map, fov_map, fov_recompute, message_log, screen_width, screen_height, bar_width, panel_height, panel_y, mouse, colors, game_state, targeting_item):\n if fov_recompute:\n for y in range(game_map.height):\n for x in range(game_map.width):\n visible = libtcod.map_is_in_fov(fov_map, x, y)\n wall = game_map.tiles[x][y].block_sight\n\n if visible:\n if wall:\n libtcod.console_set_char_background(con, x, y, colors.get('light_wall'), libtcod.BKGND_SET)\n else:\n libtcod.console_set_char_background(con, x, y, colors.get('light_ground'), libtcod.BKGND_SET)\n\n game_map.tiles[x][y].explored = True\n\n elif game_map.tiles[x][y].explored:\n if wall:\n libtcod.console_set_char_background(con, x, y, colors.get('dark_wall'), libtcod.BKGND_SET)\n else:\n libtcod.console_set_char_background(con, x, y, colors.get('dark_ground'), libtcod.BKGND_SET)\n\n # Draw all entities in the list\n visible_entities = [e for e in game_map.entities if e.render_order != RenderOrder.INVISIBLE]\n entities_in_render_order = sorted(visible_entities, key=lambda x: x.render_order.value)\n\n for entity in entities_in_render_order:\n if game_state == GameStates.TARGETING and targeting_item.valid_target(mouse, fov_map, entity) and entity.distance(mouse.cx, mouse.cy) <= targeting_item.item.targeting_radius:\n libtcod.console_set_default_foreground(con, libtcod.darkest_red)\n libtcod.console_put_char(con, entity.x, entity.y, entity.char, libtcod.BKGND_NONE)\n else:\n draw_entity(con, entity, fov_map, game_map)\n\n libtcod.console_blit(con, 0, 0, screen_width, screen_height, 0, 0, 0)\n\n libtcod.console_set_default_background(panel, libtcod.black)\n libtcod.console_clear(panel)\n\n # Print the game messages, one at a time\n y = 1\n for message in message_log.messages:\n libtcod.console_set_default_foreground(panel, message.color)\n libtcod.console_print_ex(panel, message_log.x, y, libtcod.BKGND_NONE, libtcod.LEFT, message.text)\n y += 1\n\n render_bar(panel, 1, 1, bar_width, 'HP', player.fighter.hp, player.fighter.max_hp, libtcod.light_red, libtcod.darker_red)\n libtcod.console_print_ex(panel, 1, 3, libtcod.BKGND_NONE, libtcod.LEFT, '{}'.format(game_map.name))\n\n libtcod.console_set_default_foreground(panel, libtcod.light_gray)\n libtcod.console_print_ex(panel, 1, 0, libtcod.BKGND_NONE, libtcod.LEFT, get_names_under_mouse(mouse, game_map.entities, fov_map))\n\n libtcod.console_blit(panel, 0, 0, screen_width, panel_height, 0, 0, panel_y)\n\n if game_state in (GameStates.SHOW_INVENTORY, GameStates.DROP_INVENTORY):\n if game_state == GameStates.SHOW_INVENTORY:\n inventory_title = 'Press the key next to an item to use it, or Esc to cancel.\\n'\n else:\n inventory_title = 'Press the key next to an item to drop it, or Esc to cancel.\\n'\n\n inventory_menu(con, inventory_title, player, 50, screen_width, screen_height)\n\n elif game_state == GameStates.LEVEL_UP:\n level_up_menu(con, 'Level up! Choose a stat to raise:', player, 40, screen_width, screen_height)\n\n elif game_state == GameStates.CHARACTER_SCREEN:\n character_screen(player, 30, 10, screen_width, screen_height)\n\n elif game_state == GameStates.WON_GAME:\n win_screen(con, screen_width, screen_height)\n\ndef clear_all(con, entities):\n for entity in entities:\n clear_entity(con, entity)\n\ndef draw_entity(con, entity, fov_map, game_map):\n if libtcod.map_is_in_fov(fov_map, entity.x, entity.y) or (entity.try_component('exit') and game_map.tiles[entity.x][entity.y].explored):\n libtcod.console_set_default_foreground(con, entity.color)\n libtcod.console_put_char(con, entity.x, entity.y, entity.char, libtcod.BKGND_NONE)\n\ndef clear_entity(con, entity):\n # erase the character that represents this object\n libtcod.console_put_char(con, entity.x, entity.y, ' ', libtcod.BKGND_NONE)\n"
},
{
"alpha_fraction": 0.6209068298339844,
"alphanum_fraction": 0.6209068298339844,
"avg_line_length": 32.08333206176758,
"blob_id": "6955ae609071c208c73d2b4614ad99b535e5d742",
"content_id": "6223b0da6cbf4fcb8014ea9d963329fbbead3cea",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 794,
"license_type": "permissive",
"max_line_length": 78,
"num_lines": 24,
"path": "/loader_functions/data_loaders.py",
"repo_name": "ChadAMiller/roguelike-2019",
"src_encoding": "UTF-8",
"text": "import os\nimport shelve\nimport dbm\n\ndef save_game(player, world, message_log, game_state):\n with shelve.open('savegame', 'n') as data_file:\n data_file['player_index'] = world.current_floor.entities.index(player)\n data_file['world'] = world\n data_file['message_log'] = message_log\n data_file['game_state'] = game_state\n\ndef load_game():\n try:\n with shelve.open('savegame', 'r') as data_file: \n player_index = data_file['player_index']\n world = data_file['world']\n message_log = data_file['message_log']\n game_state = data_file['game_state']\n except dbm.error:\n raise FileNotFoundError\n\n player = world.current_floor.entities[player_index]\n\n return player, world, message_log, game_state\n"
},
{
"alpha_fraction": 0.6830601096153259,
"alphanum_fraction": 0.6830601096153259,
"avg_line_length": 44.75,
"blob_id": "b83a2fcc39022e9c9c1a6f3fe684b98eef1b84d1",
"content_id": "ad920b706e37cb688249d3e6829e284bf30b206f",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 915,
"license_type": "permissive",
"max_line_length": 124,
"num_lines": 20,
"path": "/map_objects/exits.py",
"repo_name": "ChadAMiller/roguelike-2019",
"src_encoding": "UTF-8",
"text": "import tcod as libtcod\n\nimport components.exit # doesn't alias to exit because of builtin exit function\nfrom entity import Entity\nfrom render_functions import RenderOrder\n\nclass DownStairs(Entity):\n def __init__(self, x, y, destination):\n super().__init__(x, y, '>', libtcod.white, 'Stairs (Down)', render_order=RenderOrder.STAIRS)\n components.exit.DownStairsExit(destination).add_to_entity(self)\n\nclass UpStairs(Entity):\n def __init__(self, x, y, old_floor):\n super().__init__(x, y, '<', libtcod.white, 'Stairs (Up)', render_order=RenderOrder.STAIRS)\n components.exit.UpStairsExit(new_floor=old_floor).add_to_entity(self)\n\nclass Altar(Entity):\n '''Does not use exit component because it cannot be used normally. Game winning logic is in the Chalice item instead.'''\n def __init__(self, x, y):\n super().__init__(x, y, '=', libtcod.white, 'Altar of the Dark Magician')\n"
},
{
"alpha_fraction": 0.5707972645759583,
"alphanum_fraction": 0.5821608901023865,
"avg_line_length": 41.482757568359375,
"blob_id": "068bb4def8f2dfd8e6a3518882411b5c7d149b33",
"content_id": "1a2296779260262a1777cea2f344b767c25354f4",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11088,
"license_type": "permissive",
"max_line_length": 144,
"num_lines": 261,
"path": "/map_objects/game_map.py",
"repo_name": "ChadAMiller/roguelike-2019",
"src_encoding": "UTF-8",
"text": "import tcod as libtcod\nfrom random import randint\n\nfrom entity import Entity\nfrom game_messages import Message\nfrom random_utils import from_dungeon_level, random_choice_from_dict\nfrom render_functions import RenderOrder\n\nimport map_objects.exits as exits\nimport map_objects.items as items\nimport map_objects.monsters as monsters\n\nfrom map_objects.rectangle import Rect\nfrom map_objects.tile import Tile\n\nDEFAULTS = {\n 'room_max_size': 10,\n 'room_min_size': 6,\n 'max_rooms': 30,\n}\n\nDUNGEON_DEPTH = 10 # Not entirely happy with this, still thinking about it\n\ndef get_or_default(d, k):\n return d.get(k, DEFAULTS[k])\n\nclass World:\n def __init__(self, player, map_width, map_height):\n self.current_floor = StartingFloor(player, map_width, map_height)\n\n def change_room(self, player, entity, message_log):\n # remember the player's current position in case they come back to this room\n self.current_floor.last_player_position = (player.x, player.y)\n\n self.current_floor = entity.exit.take_exit(player, message_log)\n\n # reset the player's position if they've been here before\n # note: currently this does not work if a player has more than one way to reenter a room where they've already been\n if self.current_floor.last_player_position:\n player.x, player.y = self.current_floor.last_player_position\n\nclass DungeonFloor:\n def __init__(self, player, map_width, map_height, dungeon_level, **kwargs):\n\n # This could be turned into a for loop but not without confusing the linter\n self.room_max_size = get_or_default(kwargs, 'room_max_size')\n self.room_min_size = get_or_default(kwargs, 'room_min_size')\n self.max_rooms = get_or_default(kwargs, 'max_rooms')\n self.previous_floor = kwargs.get('previous_floor', None)\n self.name = kwargs.get('name', \"Dungeon Floor: {}\".format(dungeon_level))\n\n self.entities = [player]\n self.width = map_width\n self.height = map_height\n self.dungeon_level = dungeon_level\n self.initialize_tiles()\n self.make_map(player)\n\n # To handle the case where the player reenters a floor from an upward staircase\n self.last_player_position = None\n\n def make_map(self, player):\n '''This should be overridden by subclasses'''\n raise NotImplementedError\n\n def initialize_tiles(self):\n self.tiles = [[Tile(True) for y in range(self.height)] for x in range(self.width)]\n\n def create_room(self, room):\n # go through the tiles in the rectangle and make them passable\n for x in range(room.x1 + 1, room.x2):\n for y in range(room.y1 + 1, room.y2):\n self.tiles[x][y].blocked = False\n self.tiles[x][y].block_sight = False\n\n def create_h_tunnel(self, x1, x2, y):\n for x in range(min(x1, x2), max(x1, x2) + 1):\n self.tiles[x][y].blocked = False\n self.tiles[x][y].block_sight = False\n\n def create_v_tunnel(self, y1, y2, x):\n for y in range(min(y1, y2), max(y1, y2) + 1):\n self.tiles[x][y].blocked = False\n self.tiles[x][y].block_sight = False\n\n def is_blocked(self, x, y):\n return self.tiles[x][y].blocked\n\n def find_exit(self):\n '''For the snake AI. Currently the last exit in the list is the downward stairs'''\n return [e for e in self.entities if e.try_component('exit')][-1]\n\n def find_entity(self, condition, key=None):\n entities_list = sorted((e for e in self.entities if condition(e)), key=key)\n return entities_list[0] if entities_list else None\n\nclass StandardFloor(DungeonFloor):\n def make_map(self, player):\n rooms = []\n num_rooms = 0\n\n center_of_last_room_x = None\n center_of_last_room_y = None\n\n for _ in range(self.max_rooms):\n # random width and height\n w = randint(self.room_min_size, self.room_max_size)\n h = randint(self.room_min_size, self.room_max_size)\n # random position without going out of the boundaries of the map\n x = randint(0, self.width - w - 1)\n y = randint(0, self.height - h - 1)\n\n # \"Rect\" class makes rectangles easier to work with\n new_room = Rect(x, y, w, h)\n\n # run through the other rooms and see if they intersect with this one\n for other_room in rooms:\n if new_room.intersect(other_room):\n break\n else:\n # this means there are no intersections, so this room is valid\n\n # 'paint' it to the map's tiles\n self.create_room(new_room)\n\n # center coordinates of new room, will be useful later\n (new_x, new_y) = new_room.center()\n\n center_of_last_room_x = new_x\n center_of_last_room_y = new_y\n\n if num_rooms == 0:\n # this is the first room, where the player starts\n player.x = new_x\n player.y = new_y\n if self.previous_floor:\n self.entities.append(exits.UpStairs(new_x, new_y, self.previous_floor))\n else:\n # all rooms after the first\n # connect it to the previous room with a tunnel\n\n # center coordinates of previous room\n (prev_x, prev_y) = rooms[num_rooms - 1].center()\n\n # flip a coin (random number that is either 0 or 1)\n if randint(0, 1) == 1:\n # first move horizontally, then vertically\n self.create_h_tunnel(prev_x, new_x, prev_y)\n self.create_v_tunnel(prev_y, new_y, new_x)\n else:\n # first move vertically, then horizontally\n self.create_v_tunnel(prev_y, new_y, prev_x)\n self.create_h_tunnel(prev_x, new_x, new_y)\n\n self.place_entities(new_room)\n\n # finally, append the new room to the list\n rooms.append(new_room)\n num_rooms += 1\n\n if self.dungeon_level < DUNGEON_DEPTH:\n destination=(\n StandardFloor,\n (player, self.width, self.height, self.dungeon_level + 1),\n {'room_max_size': self.room_max_size, 'room_min_size': self.room_min_size, 'max_rooms': self.max_rooms, 'previous_floor': self})\n else:\n destination=(\n EndingFloor,\n (player, self.width, self.height, self.dungeon_level + 1),\n {'previous_floor': self})\n self.entities.append(exits.DownStairs(center_of_last_room_x, center_of_last_room_y, destination))\n\n def place_entities(self, room):\n # Get a random number of monsters\n max_monsters_per_room = from_dungeon_level([[2,1],[3,4],[5,6]], self.dungeon_level)\n max_items_per_room = from_dungeon_level([[1,1],[2,4]], self.dungeon_level)\n\n number_of_monsters = randint(0, max_monsters_per_room)\n number_of_items = randint(0, max_items_per_room)\n\n monster_chances = {\n monsters.Orc: 80,\n monsters.Archer: from_dungeon_level([(i*2, i) for i in range(DUNGEON_DEPTH)], self.dungeon_level),\n monsters.Snake: from_dungeon_level([(i*10, i) for i in range(DUNGEON_DEPTH)], self.dungeon_level),\n monsters.Troll: from_dungeon_level([[15, 3], [30, 5], [60, 7]], self.dungeon_level),\n monsters.Balrog: from_dungeon_level([(max(i-4*10, i), i) for i in range (DUNGEON_DEPTH)], self.dungeon_level),\n monsters.Wraith: from_dungeon_level([(i, i) for i in range(10)], self.dungeon_level),\n }\n\n item_chances = {}\n\n sword_chances = {items.sword_class(i+2): from_dungeon_level([[i*2, i]], self.dungeon_level) for i in range(DUNGEON_DEPTH)}\n item_chances.update(sword_chances)\n\n shield_chances = {items.shield_class(i): from_dungeon_level([[i*3, i]], self.dungeon_level) for i in range(DUNGEON_DEPTH)}\n item_chances.update(shield_chances)\n\n potion_chances = {\n items.HealingPotion: 5,\n items.RejuvenationPotion: 35,\n }\n item_chances.update(potion_chances)\n\n scroll_chances = {\n items.LightningScroll: from_dungeon_level([[25, 4]], self.dungeon_level),\n items.FireballScroll: from_dungeon_level([[25, 6]], self.dungeon_level),\n items.ConfusionScroll: from_dungeon_level([[10, 2]], self.dungeon_level),\n }\n item_chances.update(scroll_chances)\n\n for _ in range(number_of_monsters):\n # Choose a random location in the room\n x = randint(room.x1 + 1, room.x2 - 1)\n y = randint(room.y1 + 1, room.y2 - 1)\n\n if not any([entity for entity in self.entities if entity.x == x and entity.y == y]):\n monster_choice = random_choice_from_dict(monster_chances)\n self.entities.append(monster_choice(x, y))\n\n for _ in range(number_of_items):\n x = randint(room.x1 + 1, room.x2 - 1)\n y = randint(room.y1 + 1, room.y2 - 1)\n\n if not any([entity for entity in self.entities if entity.x == x and entity.y == y]):\n item_choice = random_choice_from_dict(item_chances)\n self.entities.append(item_choice(x, y))\n\nclass StartingFloor(DungeonFloor):\n def __init__(self, player, map_width, map_height):\n super().__init__(player, map_width, map_height, 0, name=\"Entry Chamber\")\n\n def make_map(self, player):\n starting_room = Rect(self.width // 2, self.height // 2, 6, 10)\n center = starting_room.center()\n self.create_room(starting_room)\n\n player.x, player.y = center\n player.y += 3\n\n self.entities.append(exits.Altar(player.x, player.y))\n\n destination=(\n StandardFloor,\n (player, self.width, self.height, self.dungeon_level + 1),\n {'room_max_size': self.room_max_size, 'room_min_size': self.room_min_size, 'max_rooms': self.max_rooms, 'previous_floor': self})\n self.entities.append(exits.DownStairs(center[0], center[1]-3, destination))\n\nclass EndingFloor(DungeonFloor):\n def __init__(self, player, map_width, map_height, dungeon_level, **kwargs):\n super().__init__(player, map_width, map_height, dungeon_level, name=\"Hall of the Chalice\", **kwargs)\n\n def make_map(self, player):\n ending_room = Rect(self.width // 2, self.height // 2, 6, 10)\n center = ending_room.center()\n self.create_room(ending_room)\n\n player.x, player.y = center\n player.y += 3\n\n self.entities.append(exits.UpStairs(player.x, player.y, self.previous_floor))\n self.entities.append(items.Chalice(center[0], center[1]-3))\n"
}
] | 16 |
121710308016/asignment3 | https://github.com/121710308016/asignment3 | 40489537c89194bb54e51fc47b34b009b278eb05 | 6532b865fff3bd3c2ec7e340b861dde8412fadb5 | e85d33e970a27e542fcb55ac5f35ddc81e87b5f0 | refs/heads/main | 2023-01-30T14:05:01.424031 | 2020-12-16T05:51:43 | 2020-12-16T05:51:43 | 321,882,517 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5703942179679871,
"alphanum_fraction": 0.6049879193305969,
"avg_line_length": 19.06779670715332,
"blob_id": "674909b0dadbf9f2a3f576d53c0e6638ff5ae551",
"content_id": "16fc6ed7dc7d41acf4f4a983066f310953079e13",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1243,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 59,
"path": "/04_is_rotating_prime.py",
"repo_name": "121710308016/asignment3",
"src_encoding": "UTF-8",
"text": "import unittest\r\nfrom itertools import permutations\r\n\r\nquestion_04 = \"\"\"\r\nRotating primes\r\n\r\nGiven an integer n, return whether every rotation of n is prime.\r\nExample 1:\r\nInput:\r\nn = 199\r\nOutput:\r\nTrue\r\nExplanation:\r\n199 is prime, 919 is prime, and 991 is prime.\r\n\r\nExample 2:\r\nInput:\r\nn = 19\r\nOutput:\r\nFalse\r\nExplanation:\r\nAlthough 19 is prime, 91 is not.\r\n\"\"\"\r\n\r\n\r\n# Implement the below function and run the program\r\n\r\ndef is_rotating_prime(num):\r\n def is_prime(num):\r\n for i in range(3,num,2):\r\n if num%i == 0:\r\n return False\r\n return True\r\n s=str(num)\r\n N=len(s)\r\n for i in range(N):\r\n if not is_prime(int(s[i:]+s[:i])):\r\n return False\r\n return True\r\nclass TestIsRotatingPrime(unittest.TestCase):\r\n\r\n def test_1(self):\r\n self.assertEqual(is_rotating_prime(2), True)\r\n\r\n def test_2(self):\r\n self.assertEqual(is_rotating_prime(199), True)\r\n\r\n def test_3(self):\r\n self.assertEqual(is_rotating_prime(19), False)\r\n\r\n def test_4(self):\r\n self.assertEqual(is_rotating_prime(791), False)\r\n\r\n def test_5(self):\r\n self.assertEqual(is_rotating_prime(919), True)\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main(verbosity=2)\r\n"
},
{
"alpha_fraction": 0.5636687278747559,
"alphanum_fraction": 0.5699020624160767,
"avg_line_length": 19.188678741455078,
"blob_id": "3a5f7ef505e0fecd8397d49894bdf5711395020f",
"content_id": "6ed08d43391be2fccb766a878b119dbce8c2d177",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1199,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 53,
"path": "/02_suffix_words.py",
"repo_name": "121710308016/asignment3",
"src_encoding": "UTF-8",
"text": "import unittest\r\n\r\nquestion_02 = \"\"\"\r\nGiven a query string s and a list of all possible words,\r\nreturn all words that have s as a suffix.\r\n\r\nExample 1:\r\nInput:\r\ns = “ed”\r\nwords = [“called”, “aged”, “land”]\r\n\r\nOutput:\r\n[“called”, “aged”]\r\n\r\nExplanation:\r\nOnly called and aged ends with ed.\r\n\r\nExample 2:\r\nInput:\r\ns = “d”\r\nwords = [“helped”, “held”, “land”, “mat”, “cat”, “bold”]\r\n\r\nOutput:\r\n[“helped”, “held”, “land”, “bold”]\r\n\r\nExplanation:\r\nAll these words ends with d, except for “mat” and “cat”.\r\n\"\"\"\r\n\r\n# Implement the below function and run the program\r\n\r\n\r\ndef suffix_words(suffix, words):\r\n lst=[]\r\n for word in words:\r\n if suffix in word:\r\n lst.append(word)\r\n return lst\r\n\r\n\r\nclass TestSuffixWords(unittest.TestCase):\r\n\r\n def test_1(self):\r\n self.assertEqual(suffix_words(\r\n 'ed', ['called', 'aged', 'land']), ['called', 'aged'])\r\n\r\n def test_2(self):\r\n self.assertEqual(suffix_words(\r\n 'd', ['helped', 'held', 'land', 'mat', 'cat', 'bold']), ['helped', 'held', 'land', 'bold'])\r\n\r\n\r\nif __name__ == '__main__':\r\n unittest.main(verbosity=2)\r\n"
}
] | 2 |
rockiger/recentpages | https://github.com/rockiger/recentpages | 5f63a7eb5b9e0c84f4fa0a38ad3016672bacb1cc | 520059f1d037353af15a6aa49915c1d6c3369e33 | ac41066bf4be497bffe71433a89a698374a51bef | refs/heads/master | 2021-01-22T20:08:13.717130 | 2017-03-17T08:04:34 | 2017-03-17T08:04:34 | 85,284,084 | 5 | 1 | null | 2017-03-17T07:40:11 | 2017-07-28T21:04:31 | 2017-03-17T08:04:42 | Python | [
{
"alpha_fraction": 0.6109765768051147,
"alphanum_fraction": 0.6201237440109253,
"avg_line_length": 28.267717361450195,
"blob_id": "17242e5f97acce6e84405da1de7de06152bc6da3",
"content_id": "1afd3569f320053fde70cff1aa3c5af38916c31a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3717,
"license_type": "no_license",
"max_line_length": 104,
"num_lines": 127,
"path": "/recentpages.py",
"repo_name": "rockiger/recentpages",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Search instantly as you type. Edvard Rejthar\n# https://github.com/e3rd/zim-plugin-instantsearch\n#\nfrom collections import defaultdict, OrderedDict\nimport copy\nimport gobject\nimport gtk\nimport logging\nfrom pprint import pprint\nfrom zim.actions import action\nfrom zim.gui.widgets import Dialog\nfrom zim.gui.widgets import InputEntry\nfrom zim.history import HistoryList\nfrom zim.history import HistoryPath\nfrom zim.notebook import Path\nfrom zim.plugins import PluginClass\nfrom zim.plugins import WindowExtension\nfrom zim.plugins import extends\nfrom zim.search import *\nfrom zim.index import IndexPath\nfrom copy import deepcopy\nimport sys\nimport inspect\n\nlogger = logging.getLogger('zim.plugins.recentpages')\n\nclass RecentPagesPlugin(PluginClass):\n\n plugin_info = {\n 'name': _('Recent Pages'), # T: plugin name\n 'description': _('''\\\nShow the recently viewed pages in a popup window.\n\n(V 0.1.0)\n'''),\n 'author': \"Marco Laspe\"\n }\n\n\n@extends('MainWindow')\nclass RecentPagesMainWindowExtension(WindowExtension):\n\n uimanager_xml = '''\n <ui>\n <menubar name='menubar'>\n <menu action='tools_menu'>\n <placeholder name='plugin_items'>\n <menuitem action='recentpages'/>\n </placeholder>\n </menu>\n </menubar>\n </ui>\n '''\n\n\n gui = \"\";\n\n @action(_('_Recent Pages'), accelerator='<ctrl><shift>r') # T: menu item\n def recentpages(self):\n\n #init\n #TODO: Get Items from pathbar\n self.history = self.window.ui.history.get_recent()\n\n # preferences\n # self.plugin.preferences['keystroke_delay']\n\n\n # Gtk\n self.gui = Dialog(self.window.ui, _('Recent Pages'), buttons=None, defaultwindowsize=(300, -1))\n\n (px, py) = self.window.get_position()\n (pw, ph) = self.window.get_size()\n (x, y) = self.gui.get_position()\n self.gui.resize(300,100)\n self.gui.move(px + (pw / 2) - 150, py + (ph / 2) - 250)\n\n # Maybe add a filter field, like atom dialogs\n #self.inputEntry = InputEntry()\n #self.inputEntry.connect('key_press_event', self.move)\n #self.inputEntry.connect('changed', self.change) # self.change is needed by GObject or something\n #self.gui.vbox.pack_start(self.inputEntry, False)\n\n\n self.listmodel = gtk.ListStore(str)\n\n # My own model for creating dialog labels and later retrieving them\n self.model = OrderedDict()\n for page in self.history:\n ky = str(page)\n ky = ky[1:-1]\n ky = ky.split(\":\")\n ky = ky[-1].strip()\n self.model[ky] = page\n\n # populate the treeview\n for row in self.model.keys():\n self.listmodel.append([row])\n self.treeview = gtk.TreeView(model=self.listmodel)\n self.treeview.set_headers_visible(False)\n # cellrenderer to render the text\n cell = gtk.CellRendererText()\n # the text in the first column should be in boldface\n # the column is created\n col = gtk.TreeViewColumn(\"\", cell, text=0)\n # and it is appended to the treeview\n self.treeview.append_column(col)\n\n self.treeview.connect(\"row-activated\", self.on_row_activated)\n\n self.gui.vbox.pack_start(self.treeview, False)\n\n self.gui.show_all()\n\n\n def on_row_activated(self, path, view_column,user_param):\n #self.gui.move(600, 600)\n #ui.open_page(path)\n (tm, it) = self.treeview.get_selection().get_selected()\n ky = tm[it][0]\n self.window.ui.open_page(self.model[ky])\n self.gui.destroy()\n print \"on_change\"\n print selection\n"
},
{
"alpha_fraction": 0.7725673913955688,
"alphanum_fraction": 0.773739755153656,
"avg_line_length": 49.235294342041016,
"blob_id": "8621b4f995d76315acb78f0ef8b76d1cd791e081",
"content_id": "47ef79e0f33ebf0b438720bdae04349e2cdfebea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 853,
"license_type": "no_license",
"max_line_length": 158,
"num_lines": 17,
"path": "/README.md",
"repo_name": "rockiger/recentpages",
"src_encoding": "UTF-8",
"text": "# recentpages\nA Zim plugin, that schows you the recent visited pages in a popup window - similar to the pathbar.\n\n\n\nThis way you can hide the Path Bar in the View menu and still conveniently access your recent visited pages.\n\n## Installation\n\nSame as for the other plugins.\n\n* [Download recentpages.py](https://raw.githubusercontent.com/rockiger/recentpages/master/recentpages.py)\n* Put the recentpages.py into the plugins folder (%appdata%\\zim\\data\\zim\\plugins on Win, ~/.local/share/zim/plugins/ in Linux or Mac OS).\n* to enable the plugin in Zim/Edit/Preferences/Plugins/ check mark Recent Pages.\n* Type Ctrl+Shift+R and see if it's working.\n\nThis plugin is heavily based on the [Instantsearch plugin](https://github.com/e3rd/zim-plugin-instantsearch/blob/master/instantsearch.py). So go check it out."
}
] | 2 |
BrianG13/RL_DQN_Project | https://github.com/BrianG13/RL_DQN_Project | 957e184c26762dd5dc0a059622b74e644dcf6282 | 7899e8d7e41e932dd1fdec3ad798e55011bf7254 | 4d87fc6e56401f72fd897215f38e92bde20ca70a | refs/heads/master | 2022-10-22T22:06:44.935245 | 2020-06-06T12:21:53 | 2020-06-06T12:21:53 | 269,972,938 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6455445289611816,
"alphanum_fraction": 0.7148514986038208,
"avg_line_length": 35.14285659790039,
"blob_id": "427974a239325fd5f94b8cf253bd3b65b27ddd6c",
"content_id": "36bb016a211aa5fd96f5ca11eec18f1f2f16d03a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 505,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 14,
"path": "/validate.py",
"repo_name": "BrianG13/RL_DQN_Project",
"src_encoding": "UTF-8",
"text": "import glob\nimport pathlib\n#make sure this file runs in the same folder as mnist.py and the answers pdf\n#make sure to title the pdf file name as id1_id2_id3.pdf i.e: 123456789_123456789_123456789.pdf\npdf_list = list(glob.glob(\"*.pdf\"))\nassert len(pdf_list)<2,\"Only submit a single pdf file\"\nassert len(pdf_list)>0,\"Only submit answers in a pdf format\"\n\n\npdf_path = pathlib.Path(pdf_list[0])\n\nfor id_el in pdf_path.name[:-4].split(\"_\"):\n print(\"id:\",id_el)\n assert len(id_el)==9,\"incorrect id number\""
}
] | 1 |
Tugdual-G/phys-num | https://github.com/Tugdual-G/phys-num | 369e928bf114abfebf863448efe8592f84bd0613 | 3a2d89f43ab9d273a73c30482c82b58aa0dfba31 | 0515cfa94aa662d735586556e3b604fa07127940 | refs/heads/main | 2023-03-02T09:29:07.583849 | 2021-02-07T18:03:02 | 2021-02-07T18:03:02 | 331,003,999 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5943223237991333,
"alphanum_fraction": 0.6373626589775085,
"avg_line_length": 19.22222137451172,
"blob_id": "d7df614e9935caabe0c6d2eb1ad219b3dedb0364",
"content_id": "d4e5098c948f33b1e1a43423b87b46b3503a4082",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1105,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 54,
"path": "/chute_1d.py",
"repo_name": "Tugdual-G/phys-num",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 24 19:21:58 2021\n\n@author: tugdual\n\nChute d'un objet avec frottements, shéma le plus simple, Euler en temps <=> RK d'ordre 1.\nChute en 1 dimension.\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ng = 10\n\n# Coefs liés aux frottements de l'air\nm = 1\nrho = 1.22\nC_x = 0.5\nS = 0.1\nC = 1/(2*m)*S*C_x*rho\n\n# temps écoulé entre chaque valeur enregistrée de la vitesse \nDelta_t = 0.1\n\n# Temps total d'intégration:\nt_max =8\n\n# Itervalle de temps pour l'intégration:\n# Le shéma d'Euler est imprécis à l'ordre 1, \n# ça se constate en augmentant la valeur de dt.\ndt = 0.001\n\nt = np.arange(1, t_max+Delta_t, Delta_t)\nv = np.empty((len(t)))\n\n# Condition initiale\nv[0] = 0\n\n# Initialisation \nv_0 = 0\n\nfor i in range(len(t)-1):\n # Intégration de l'équation sur le temps Delta_t:\n for j in range(int(Delta_t/dt)): \n dv = -(g + C*v_0*np.abs(v_0))\n v_0 = v_0 + dv*dt\n # Stockage de la valeur de la vitesse \n v[i+1] = v_0\n \nplt.plot(t,v)\nplt.xlabel('temps en secondes')\nplt.ylabel('vitesse en m/s')\nplt.grid()\nplt.show()\n"
},
{
"alpha_fraction": 0.6326727867126465,
"alphanum_fraction": 0.6723054647445679,
"avg_line_length": 31.328125,
"blob_id": "15b6806324ed5565c92d01b34cb39963533d4f7d",
"content_id": "25027a2a2c5124c703191ec69000d9ced43eacf2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2091,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 64,
"path": "/exemple.py",
"repo_name": "Tugdual-G/phys-num",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 23 12:19:08 2021\n\n@author: tugdual\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\n\n\"\"\"Création de l'ensemble des valeurs de x et de y, représentant l'espace, \nen mètres par exemple\"\"\"\n\nx = np.linspace(-5,5,1000)\ny = np.linspace(-3,3,1000)\n\n# Création des grilles d'espace X et Y:\n\"\"\" Ces grilles permettent d'associer à chaque point (i,j) de \nl'espace discrétisé, son emplacement dans l'espace 'modélisé' où 'réel'. L'emplacement \nen x et en y est donné par X[i,j] et par Y[i,j] (ou plus simplement \npar n'importe quel point de X[i,:] et Y[i,:]).\nx est constant sur les colones de X, et y est constant sur les lignes de Y, c'est un repère\n de l'espace. Les matrices X et Y ont deux dimentions dans notre cas. \nLa matrice 2d X est de la largeur de la matrice ligne x,\n et sa hauteur correspond à la longeur de la matrice ligne y, de même pour la matrice 2d Y \"\"\"\n\n# Création des grilles d'espace X et Y, grace à meshgrid:\nX, Y = np.meshgrid(x,y)\n\n\"\"\"Grace aux grilles X et Y on peut définir une fonction de deux variables.\nLes valeurs de cette fonction sont stockées dans une matrice (2d)\n de même dimensions que X et Y.\"\"\"\nZ = np.cos(3*(X**2 + Y**2)**0.5)\n\n\"\"\"On affiche en couleurs les valeurs de z, - vers + => sombre vers clair\"\"\"\n#graph 1:\nfig = plt.figure(figsize = (13,4))\nax1 = plt.subplot(1,3,1)\n#Colormesh est comme plt.plot() mais en 3 dimensions avec des couleurs pour la 3ème dimensions (Z).\nplt.pcolormesh(X,Y,X, cmap = 'hot', shading ='nearest')\nax1.set_xlabel('x')\nax1.set_ylabel('y')\nax1.set_title('z = x')\n\n#graph 2:\nax2 = plt.subplot(1,3,2)\nax2.set_xlabel('x')\nax2.set_ylabel('y')\nax2.set_title('z = y')\nplt.pcolormesh(X,Y,Y, cmap = 'hot', shading ='nearest')\n\n#graph 3:\nax3 = plt.subplot(1,3,3)\nax3.set_xlabel('x')\nax3.set_ylabel('y')\nax3.set_title('z = cos(3*(X**2 + Y**2)**0.5)')\nplt.pcolormesh(X,Y,Z, cmap = 'hot', shading ='nearest')\n\n#marges\nfig.subplots_adjust(left = 0.05, bottom = 0.15,\n right = 0.95, top = 0.9, wspace = 0.25, hspace = 0)\n\n#Pour Théo\nplt.show()\n"
},
{
"alpha_fraction": 0.5235742926597595,
"alphanum_fraction": 0.5653345584869385,
"avg_line_length": 19.620370864868164,
"blob_id": "562575bca45fb8750d21ae9506505d21df51777a",
"content_id": "9b79d8a0555f5339230c77ed85b994694fa45a90",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2250,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 108,
"path": "/tir.py",
"repo_name": "Tugdual-G/phys-num",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sun Jan 24 20:43:28 2021\n\n@author: tugdual\n\nLancé d'une balle avec du vent\n\"\"\"\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom math import sin, cos, pi\n\n# Gravité\ng = 10\n\n# Constantes liées aux frottements.\nm = 1\nrho = 1.22\nC_x = 0.5\nS = 0.1\nC = 1/(2*m)*S*C_x*rho\n\n# Vent:\nwind = - 10\n\n\n# Temps total d'intégration:\nt_max = 3.5\n\n# Itervalle de temps pour l'intégration:\n# Le shéma d'Euler est imprécis à l'ordre 1, \n# ça se constate en augmentant la valeur de dt.\ndt = 0.001\n\n# Interval d'enregistrement de chaque image.\nDelta_t = dt*10\n\n# Création des listes de vitesses et de temps\nt = np.arange(1, t_max+Delta_t, Delta_t)\nv_x = np.empty((len(t)))\nv_y = np.empty((len(t)))\n\n# Conditions initiales\nv_init = 20.\nalph = pi/4\n\nv_x[0] = v_init*cos(alph) \nv_y[0] = v_init*sin(alph)\n\nv_x0 = v_x[0]\nv_y0 = v_y[0]\n\ndv_y = 0.\ndv_x = 0.\n\nx = np.empty((len(t)))\ny = np.empty((len(t)))\n\n# On lance la balle à partir de (0,0):\nx[0] = 0\ny[0] = 0\n\n# X_Dt : Déplacement de la balle entre chaque itération de la boucle 1\n# initialisation:\nx_Dt = 0\ny_Dt = 0\n\n#Résolution de l'équation diff:\nfor i in range(len(t)-1):\n # Intégration de l'équation sur le temps Delta_t:\n x_Dt = 0\n y_Dt = 0\n for j in range(int(Delta_t/dt)):\n \n #Variation de la vitesse:\n dv_x = -C*(v_x0 - wind)*np.abs(v_x0 - wind) \n dv_y = -(g + C*v_y0*np.abs(v_y0)) \n \n # vitesse après l'écoulement du temps dt:\n v_x0 = v_x0 + dv_x*dt\n v_y0 = v_y0 + dv_y*dt\n \n # Ajout du déplacement après dt:\n y_Dt += dt*v_y0\n x_Dt += dt*v_x0\n \n # Stockage de la valeur de la vitesse \n v_y[i+1] = v_y0\n v_x[i+1] = v_x0\n \n # Stockage des positions\n x[i+1] = x[i] + x_Dt\n y[i+1] = y[i] + y_Dt\n\n\n\nplt.figure(dpi = 200)\nplt.scatter(x, y, s = 2, marker = '.', c = (v_x**2 + v_y**2)**0.5, cmap = 'hot')\n\nplt.annotate('Départ', xy = (x[0],y[0]), xytext=(0,0),\n textcoords = 'offset points', color = 'black')\n\nplt.annotate('Arrivée', xy = (x[len(x)-1],y[len(y)-1]), xytext=(-10,0),\n textcoords = 'offset points', color = 'black')\nplt.xlabel('L (m)')\nplt.ylabel('H (m)')\nplt.grid()\nplt.show()\n"
}
] | 3 |
r06922019/trilateration_numpy_vectorized | https://github.com/r06922019/trilateration_numpy_vectorized | 05742913d269e1d70dbeb732c716cf67c666c929 | 6d8210c078f3a42bc7b5ae65d698932c6eba759b | 2feb1eab3d6077e4ed39325dfe747d07665d5478 | refs/heads/master | 2022-07-06T12:43:37.408595 | 2020-04-20T19:22:29 | 2020-04-20T19:22:29 | 257,380,891 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7847411632537842,
"alphanum_fraction": 0.7983651161193848,
"avg_line_length": 51.57143020629883,
"blob_id": "f621b9b942e0e777358a1417957b31d7a5abf5c2",
"content_id": "aefa5081b5a0044d2a479fecf10e6bda69901b71",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 367,
"license_type": "no_license",
"max_line_length": 202,
"num_lines": 7,
"path": "/README.txt",
"repo_name": "r06922019/trilateration_numpy_vectorized",
"src_encoding": "UTF-8",
"text": "# What's this?\nSpeed up the process of [trilateration](https://www.pathpartnertech.com/triangulation-vs-trilateration-vs-multilateration-for-indoor-positioning-systems/) by performing vectorized calculation with numpy\nthe maximum memory usage shall be len(r1) * len(r2) * len(r3) entries of (x,y)\n\n# Execution\npip3 install -r requirements.txt\npython3 trilateration.py"
},
{
"alpha_fraction": 0.46254926919937134,
"alphanum_fraction": 0.559789776802063,
"avg_line_length": 29.426666259765625,
"blob_id": "95add42615b3ec942cfa4e6269d0cec091dec262",
"content_id": "34fb6f504d96bd907a1bde760c1597c57379ba84",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2283,
"license_type": "no_license",
"max_line_length": 192,
"num_lines": 75,
"path": "/trilateration.py",
"repo_name": "r06922019/trilateration_numpy_vectorized",
"src_encoding": "UTF-8",
"text": "#!/usr/env/python3\nimport time\nimport numpy as np # np 1.17.2\n\n# ref: www.101computing.net/cell-phone-trilateration-algorithm/\ndef trilateration(x1, y1, r1, x2, y2, r2, x3, y3, r3):\n A = 2*x2 - 2*x1\n B = 2*y2 - 2*y1\n C = r1**2 - r2**2 - x1**2 + x2**2 - y1**2 + y2**2\n D = 2*x3 - 2*x2\n E = 2*y3 - 2*y2\n F = r2**2 - r3**2 - x2**2 + x3**2 - y2**2 + y3**2\n x = (C*E - F*B) / (E*A - B*D)\n y = (C*D - A*F) / (B*D - A*E)\n return (x, y)\n\n\ndef generate_lists(n_points=100, n_list=3):\n rand_list = np.random.rand(n_list * n_points)\n return np.split(rand_list * 5, 3, axis=0)\n\n\ndef trilateration_vector(radar1, radar2, radar3):\n x1, y1, r1 = radar1\n r1 = np.square(r1)\n x2, y2, r2 = radar2\n r2 = np.square(r2)\n x3, y3, r3 = radar3\n r3 = np.square(r3)\n\n n_points = r1.size * r2.size * r3.size\n\n A = 2*x2 - 2*x1\n B = 2*y2 - 2*y1\n\n # C = r1**2 - r2**2\n r12 = np.tile(np.tile(r1, r2.size), r3.size)\n r22 = np.tile(np.repeat(r2, r1.size, axis=0), r3.size)\n C = r12 - r22\n C = C - x1**2 + x2**2 - y1**2 + y2**2\n\n D = 2*x3 - 2*x2\n E = 2*y3 - 2*y2\n\n # F = r2**2 - r3**2\n # F = np.repeat( np.repeat(np.expand_dims(r2, axis=1), r1.size, axis=1).reshape([-1, 1]), r3.size, axis=0) - np.repeat(np.expand_dims(r3, axis=1), r1.size*r2.size, axis=1).reshape([-1, 1])\n r32 = np.repeat(r3, r1.size*r2.size, axis=0)\n F = r22 - r32\n F = F - x2**2 + x3**2 - y2**2 + y3**2\n\n x = (C*E - F*B) / (E*A - B*D)\n y = (C*D - A*F) / (B*D - A*E)\n return np.concatenate([x.reshape([-1, 1]), y.reshape([-1, 1])], axis=1)\n\n\n# generate 100 point list * 3\nx1, x2, x3, y1, y2, y3 = (np.random.rand(6) - 0.5) * 5\nr1_list, r2_list, r3_list = generate_lists()\n\n# compute with general method\nstart_time = time.time()\npoint_list_general = [trilateration(x1, y1, r1, x2, y2, r2, x3, y3, r3) for r3 in r3_list for r2 in r2_list for r1 in r1_list]\nprint(\"%.2fs\" % (time.time() - start_time))\n\n# compute with vectorized method\nradar1 = (x1, y1, r1_list)\nradar2 = (x2, y2, r2_list)\nradar3 = (x3, y3, r3_list)\n\nstart_time = time.time()\npoint_list_vector = trilateration_vector(radar1, radar2, radar3)\nprint(\"%.2fs\" % (time.time() - start_time))\n\n# compare error\nprint(\"mse:\", np.mean(np.square(point_list_general - point_list_vector)))\n\n"
}
] | 2 |
shashank1094/machineLearningTutorials | https://github.com/shashank1094/machineLearningTutorials | 9f6358a7ecde6ff509df2c8127eead1c24e5c5eb | 94f20d2c48558d4ee7f53baac1474fc729e886e0 | c2b50d0bcd6d49c238118066144d2c8760789a1d | refs/heads/master | 2020-03-20T04:04:22.231322 | 2018-06-13T06:04:28 | 2018-06-13T06:04:28 | 137,169,560 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6483001112937927,
"alphanum_fraction": 0.6570926308631897,
"avg_line_length": 24.84848403930664,
"blob_id": "6827ebd52247983e676d52772fb3f9d4fb66719c",
"content_id": "9fecba7a191798b2fc4ae6ec6f972a5f5434f551",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1706,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 66,
"path": "/linear_regression_multiple.py",
"repo_name": "shashank1094/machineLearningTutorials",
"src_encoding": "UTF-8",
"text": "import matplotlib.pyplot as plt\nimport numpy as np\nfrom sklearn import datasets, linear_model, metrics\n\n# load the boston dataset\nboston = datasets.load_boston(return_X_y=False)\n\n# defining feature matrix(X) and response vector(y)\nX = boston.data\ny = boston.target\n\n# Printing a graph for \n# print(type(X))\n#\n# plt.scatter(X[:,0], y, color=\"m\",\n# marker=\"o\", s=1)\n#\n# # putting labels\n# plt.xlabel('x')\n# plt.ylabel('y')\n\n#\n# print(X.shape, y.shape)\n#\n# # splitting X and y into training and testing sets\n# from sklearn.model_selection import train_test_split\n#\n# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.4,\n# random_state=1)\n#\n# # create linear regression object\n# reg = linear_model.LinearRegression()\n#\n# # train the model using the training sets\n# reg.fit(X_train, y_train)\n#\n# # regression coefficients\n# print('Coefficients: \\n', reg.coef_)\n#\n# # variance score: 1 means perfect prediction\n# print('Variance score: {}'.format(reg.score(X_test, y_test)))\n#\n# # plot for residual error\n#\n# # setting plot style\n# plt.style.use('fivethirtyeight')\n#\n# # plotting residual errors in training data\n# plt.scatter(reg.predict(X_train), reg.predict(X_train) - y_train,\n# color=\"green\", s=10, label='Train data')\n#\n# # plotting residual errors in test data\n# plt.scatter(reg.predict(X_test), reg.predict(X_test) - y_test,\n# color=\"blue\", s=10, label='Test data')\n#\n# # plotting line for zero residual error\n# plt.hlines(y=0, xmin=0, xmax=50, linewidth=2)\n#\n# # plotting legend\n# plt.legend(loc='upper right')\n#\n# # plot title\n# plt.title(\"Residual errors\")\n\n# function to show plot\nplt.show()\n"
}
] | 1 |
ShashankVBhat/DisplayImage | https://github.com/ShashankVBhat/DisplayImage | 7e66e42a69edd97af6485b91f5cd4eb5cb186fec | 45dc1d7eb20c041964713d6b393f5324de1b06ab | c41413390d399b78fb35dc69972ba55e044147b7 | refs/heads/master | 2023-03-11T17:47:28.387300 | 2021-03-03T09:50:37 | 2021-03-03T09:50:37 | 344,037,226 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7525510191917419,
"alphanum_fraction": 0.7525510191917419,
"avg_line_length": 25.200000762939453,
"blob_id": "cd51a2e7df6081a06d1ded895df68dcb403f2785",
"content_id": "5dd18b51bc31351496a9a17057d8df1536f5927d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 392,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 15,
"path": "/README.md",
"repo_name": "ShashankVBhat/DisplayImage",
"src_encoding": "UTF-8",
"text": "# Image display\n\nImage display package is used to display the image continously.\n\n## Installation\n\nYou can install the image display from [PyPI](https://pypi.org/project/imagedisplay/):\n\n pip install imagedisplay\n\n## How to use\n\nThe imagedisplay is a command line application, named `imagedisplay`. To use simply call the program:\n\n $ python -m imagedisplay --image_path=\"path\\to\\image\""
},
{
"alpha_fraction": 0.5519713163375854,
"alphanum_fraction": 0.5663082599639893,
"avg_line_length": 25.571428298950195,
"blob_id": "ec7462cdf10f4db6ecbcdee8da6a16045b307347",
"content_id": "0397c37086f4354432300c83323bb943ce165b83",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 558,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 21,
"path": "/imagedisplay/__main__.py",
"repo_name": "ShashankVBhat/DisplayImage",
"src_encoding": "UTF-8",
"text": "import cv2\nimport argparse\n\n\ndef main(image_path):\n image = cv2.imread(image_path)\n while True:\n cv2.imshow(\"demo\", image)\n cv2.waitKey(1)\n k = cv2.waitKey(1) & 0xFF\n # press 'q' to exit\n if k == ord('q'):\n break\n\n\nif __name__ == \"__main__\":\n parser = argparse.ArgumentParser(description='Display image.')\n parser.add_argument('--image_path', type=str, default='./image.jpg',\n help='path of the image to be displayed.')\n args = parser.parse_args()\n main(args.image_path)\n"
},
{
"alpha_fraction": 0.6140350699424744,
"alphanum_fraction": 0.6666666865348816,
"avg_line_length": 27,
"blob_id": "909d232f57d6bc8ddb6ba455c319c2955e56cca1",
"content_id": "f302cea7a722770c894506b44a05d9661429149a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 57,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 2,
"path": "/imagedisplay/__init__.py",
"repo_name": "ShashankVBhat/DisplayImage",
"src_encoding": "UTF-8",
"text": "# Version of iamgedisplay package\n__version__ = \"1.0.0\"\n\n"
}
] | 3 |
james20140802/Voc2Voc | https://github.com/james20140802/Voc2Voc | 7d143570946cbe348b083ad31577c87b2cb10c01 | 965319b740e0d6914ec52b8f69b690856361f7eb | acfe8e2fe71a226cffe7b541d3e5930369afeb5c | refs/heads/master | 2021-03-01T20:15:44.807263 | 2020-03-10T14:26:43 | 2020-03-10T14:26:43 | 245,811,398 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6590909361839294,
"alphanum_fraction": 0.6695803999900818,
"avg_line_length": 25,
"blob_id": "e0313c4010952dfd905ba84aa346f5e74ded6f4f",
"content_id": "bc6632fe6db6483c048805d462dc4184ac13577b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 572,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 22,
"path": "/model/model_utils.py",
"repo_name": "james20140802/Voc2Voc",
"src_encoding": "UTF-8",
"text": "\"\"\"Voc2Voc model helper methods.\"\"\"\n\nfrom __future__ import absolute_import\nfrom __future__ import division\nfrom __future__ import print_function\n\nimport tensorflow as tf\n\n\ndef get_padding(x, padding_value=0):\n \"\"\"Return float tensor representing the padding values in x.\n\n Args:\n x: int tensor with any shape\n padding_value: int value that\n\n Returns:\n float tensor with same shape as x containing values 0 or 1.\n 0 -> non-padding, 1 -> padding\n \"\"\"\n with tf.name_scope(\"padding\"):\n return tf.to_float(tf.equal(x, padding_value))\n"
}
] | 1 |
wingsgit/patentSpider | https://github.com/wingsgit/patentSpider | 8a314449ae15e4a75a1108b93ce89c72f924c8ef | 570867ffd657860bb19beedfea47a44ab4954721 | 4068b2a04f8d43c29c3fb77dafa115393f69a131 | refs/heads/master | 2020-12-10T22:30:05.042833 | 2017-08-24T15:06:22 | 2017-08-24T15:06:22 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5094585418701172,
"alphanum_fraction": 0.5747874975204468,
"avg_line_length": 34.88418197631836,
"blob_id": "276b241ead149a9d7724dd6a03e04db01f27193b",
"content_id": "0f5a8e003823a2a6d5b6455a2450bbd38ab44f2c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 13293,
"license_type": "no_license",
"max_line_length": 367,
"num_lines": 354,
"path": "/patent_clawer.py",
"repo_name": "wingsgit/patentSpider",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @Time : 2017/8/8 23:00 \r\n# @Author : chesian\r\n# @Site : \r\n# @File : patent_clawer.py\r\n# @Software: PyCharm\r\nimport csv\r\nimport json\r\nimport random\r\nimport re\r\n\r\nimport sys\r\n\r\nimport time\r\nfrom bs4 import BeautifulSoup\r\n\r\nfrom test_ip_pools import test_useful\r\n\r\nreload(sys)\r\nsys.setdefaultencoding('utf-8')\r\n\r\npros = [\r\n # \"202.119.162.138:80\",\r\n # \"210.29.26.250:80\",\r\n # \"43.240.138.31:8080\",\r\n # \"111.1.3.36:8000\",\r\n # \"121.12.170.233:8998\",\r\n # \"121.232.144.81:9000\",\r\n # \"118.117.139.144:9000\",\r\n # \"43.240.138.31:8080\",\r\n \"119.254.84.90:80\",\r\n # \"114.215.192.135:8118\",\r\n # \"101.4.60.50:80\",\r\n # \"121.232.148.143:9000\",\r\n # \"117.90.7.194:9000\",\r\n \"182.254.246.215:8123\",\r\n # \"101.4.136.34:81\",\r\n \"58.254.132.87:80\",\r\n \"183.62.60.100:80\",\r\n]\r\n\r\nuser_agents = [\r\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 OPR/26.0.1656.60'\r\n 'Mozilla/5.0 (Windows NT 5.1; U; en; rv:1.8.1) Gecko/20061208 Firefox/2.0.0 Opera 9.50'\r\n 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 9.50'\r\n 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0'\r\n 'Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10'\r\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2'\r\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36'\r\n 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'\r\n 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16'\r\n 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'\r\n 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'\r\n 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0'\r\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)'\r\n 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36'\r\n]\r\n\r\ncookies_strs = [\r\n \"WEE_SID=r9UTtXo8y2yXNcf7K8wjgAH-7fUjyMcd91HeSqRUcbdX_ZzJrSo_!-1520733268!2083373865!1503569214012; IS_LOGIN=true; wee_username=cHBwcHAxMjM%3D; wee_password=cHFwNTQ1MjUwNw%3D%3D; JSESSIONID=r9UTtXo8y2yXNcf7K8wjgAH-7fUjyMcd91HeSqRUcbdX_ZzJrSo_!-1520733268!2083373865; _gscu_761734625=03501374f8hl8s15; _gscs_761734625=t03575978x4yu6v91|pv:3; _gscbrs_761734625=1\",\r\n\r\n \"WEE_SID=HUUUG1rxKZlWzLgVf4keAnux2CpW6HFHPAOYcmHixMXxccUKA8O3!879531882!187197179!1503575890673; IS_LOGIN=true; avoid_declare=declare_pass; JSESSIONID=HUUUG1rxKZlWzLgVf4keAnux2CpW6HFHPAOYcmHixMXxccUKA8O3!879531882!187197179; _gscu_761734625=03401759u08w3823; _gscs_761734625=t03576099mxlcjl23|pv:1; _gscbrs_761734625=1\"\r\n]\r\n\r\n\r\ndef get_cookies():\r\n cookies_str = random.choice(cookies_strs)\r\n cookies = {} # 初始化cookies字典变量\r\n for line in cookies_str.split(';'): # 按照字符:进行划分读取\r\n # 其设置为1就会把字符串拆分成2份\r\n name, value = line.strip().split('=', 1)\r\n cookies[name] = value # 为字典cookies添加内容\r\n\r\n return cookies\r\n\r\n\r\ndef extract_data(content):\r\n rows = []\r\n soup = BeautifulSoup(content)\r\n # print soup.prettify()\r\n nodes = soup.find_all(\"li\", class_=\"patent\")\r\n for patent in nodes:\r\n row = {}\r\n vIdHidden = patent.find_all(attrs={\"name\": \"vIdHidden\"})[0]['value']\r\n idHidden = patent.find_all(attrs={\"name\": \"idHidden\"})[0]['value']\r\n titleHidden = patent.find_all(attrs={\"name\": \"titleHidden\"})[0]['value']\r\n nrdAnHidden = patent.find_all(attrs={\"name\": \"nrdAnHidden\"})[0]['value']\r\n nrdAdpHidden = patent.find_all(attrs={\"name\": \"nrdAdpHidden\"})[0]['value']\r\n nrdpdHidden = patent.find_all(attrs={\"name\": \"nrdpdHidden\"})[0]['value']\r\n nrdPnHidden = patent.find_all(attrs={\"name\": \"nrdPnHidden\"})[0]['value']\r\n appSnHidden = patent.find_all(attrs={\"name\": \"appSnHidden\"})[0]['value']\r\n pnSnHidden = patent.find_all(attrs={\"name\": \"pnSnHidden\"})[0]['value']\r\n langHidden = patent.find_all(attrs={\"name\": \"langHidden\"})[0]['value']\r\n docStatusHidden = patent.find_all(attrs={\"name\": \"docStatusHidden\"})[0]['value']\r\n appNameHidden = patent.find_all(attrs={\"name\": \"appNameHidden\"})[0]['value']\r\n appAddrHidden = patent.find_all(attrs={\"name\": \"appAddrHidden\"})[0]['value']\r\n appZipHidden = patent.find_all(attrs={\"name\": \"appZipHidden\"})[0]['value']\r\n appCountryHidden = patent.find_all(attrs={\"name\": \"appCountryHidden\"})[0]['value']\r\n\r\n row[\"文献标识\"] = vIdHidden\r\n row[\"文献唯一标识\"] = idHidden\r\n row[\"发明名称\"] = titleHidden\r\n row[\"nrdAnHidden\"] = nrdAnHidden\r\n # row[\"申请日\"] = nrdAdpHidden\r\n # row[\"公开(公告)日\"] = nrdpdHidden\r\n # row[\"公开(公告)号\"] = nrdPnHidden\r\n row[\"appSnHidden\"] = appSnHidden\r\n row[\"pnSnHidden\"] = pnSnHidden\r\n row[\"国家\"] = langHidden\r\n row[\"文献状态\"] = docStatusHidden\r\n # row[\"申请人/专利权人\"] = appNameHidden\r\n row[\"地址\"] = appAddrHidden\r\n row[\"邮编\"] = appZipHidden\r\n row[\"申请人/专利权人所在国代码\"] = appCountryHidden\r\n\r\n for a in patent.select(\"p\"):\r\n dict_data = \"\".join(a.stripped_strings).split(\":\")\r\n row[dict_data[0].strip()] = dict_data[1].strip()\r\n\r\n rows.append(row)\r\n # for key in row:\r\n # print key, \"-----\", row[key]\r\n # break\r\n form_data = {}\r\n try:\r\n form = soup.find_all(attrs={\"name\": \"resultlistForm\"})[0]\r\n\r\n for input in form.find_all(\"input\"):\r\n form_data[input[\"name\"].strip()] = input[\"value\"].strip()\r\n except IndexError:\r\n # print \"no data!!!\"\r\n pass\r\n return rows, form_data\r\n\r\n\r\ndef parse_index(company):\r\n import requests\r\n url = 'http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/executeSmartSearch1207-executeSmartSearch.shtml'\r\n d = {\r\n \"searchCondition.searchExp\": company,\r\n \"searchCondition.dbId\": \"VDB\",\r\n \"resultPagination.limit\": \"12\",\r\n \"searchCondition.searchType\": \"Sino_foreign\",\r\n \"wee.bizlog.modulelevel\": \"0200101\"\r\n\r\n }\r\n r = requests.post(url, data=d, cookies=get_cookies(),\r\n headers={'User-Agent': random.choice(user_agents)})\r\n time.sleep(5)\r\n # open(\"content.html\", \"w\").write(r.content)\r\n return r.content\r\n\r\n\r\ndef parse_turn_page(form_data):\r\n import requests\r\n\r\n url = 'http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/showSearchResult-startWa.shtml'\r\n\r\n company_name = form_data[\"searchCondition.searchExp\"]\r\n searchKeywords = \"\"\r\n for i in range(0, len(company_name)):\r\n searchKeywords += \"[\" + company_name[i] + \"][ ]{0,}\"\r\n\r\n d = {\r\n \"resultPagination.limit\": \"12\",\r\n \"resultPagination.sumLimit\": \"10\",\r\n \"resultPagination.start\": form_data[\"resultPagination.start\"],\r\n \"resultPagination.totalCount\": form_data[\"resultPagination.totalCount\"],\r\n \"searchCondition.searchType\": \"Sino_foreign\",\r\n \"searchCondition.dbId\": \"\",\r\n \"searchCondition.strategy\": \"\",\r\n \"searchCondition.literatureSF\": \"复合申请人与发明人=(\" + company_name + \")\",\r\n \"search_scope\": \"\",\r\n \"searchCondition.searchKeywords\": searchKeywords,\r\n \"searchCondition.searchExp\": company_name,\r\n \"searchCondition.executableSearchExp\": \"VDB:(IBI=\" + company_name + \")\",\r\n \"wee.bizlog.modulelevel\": \"0200101\",\r\n }\r\n\r\n r = requests.post(url, data=d, cookies=get_cookies(),\r\n headers={'User-Agent': random.choice(user_agents)})\r\n time.sleep(10)\r\n # r = requests.post(url, data=d, cookies=get_cookies(), proxies={'http': random.choice(pros)},\r\n # headers={'User-Agent': random.choice(user_agents)})\r\n return r.content\r\n\r\n\r\ndef file_to_list(path, filename):\r\n with open(path + filename, \"rb\") as f:\r\n lines = f.readlines()\r\n txtList = []\r\n for line in lines:\r\n line = line.replace('\\r', '').replace('\\n', '')\r\n tokens = re.split(\",| \", line)\r\n txtList.append(tokens[0])\r\n return txtList\r\n\r\n\r\ndef file_to_json(filename):\r\n lines = open(filename).readlines()\r\n\r\n colums = set()\r\n rows = []\r\n for i in range(0, len(lines), 2):\r\n row = {}\r\n\r\n print len(lines[i].split(\":\")), len(lines[i + 1].split(\":\"))\r\n for key, value in zip(lines[i].split(\":\"), lines[i + 1].split(\":\")):\r\n row[key.replace('\\n', '')] = value.replace('\\n', '')\r\n colums.add(key.replace('\\n', ''))\r\n rows.append(row)\r\n\r\n f = open(\"patent_all.csv\", \"a\")\r\n f.write(\",\".join(colums) + \"\\n\")\r\n\r\n print len(rows)\r\n for row in rows:\r\n line = []\r\n for key in colums:\r\n if key not in row.keys():\r\n line.append(\"\")\r\n else:\r\n line.append(row[key])\r\n\r\n f.write(\",\".join(line) + \"\\n\")\r\n\r\n\r\ndef check_post_num(post_num, content, f):\r\n post_num += 1\r\n rows, form_data = extract_data(content)\r\n for row in rows:\r\n # print row\r\n f.write(\":\".join(row.keys()) + \"\\n\")\r\n f.write(\":\".join(row.values()) + \"\\n\")\r\n if post_num > 500:\r\n return -1\r\n if len(form_data) == 0:\r\n return 0\r\n else:\r\n return form_data\r\n\r\n\r\ndef get_patent_num(company):\r\n import requests\r\n url = 'http://www.pss-system.gov.cn/sipopublicsearch/patentsearch/executeSmartSearch1207-executeSmartSearch.shtml'\r\n d = {\r\n \"searchCondition.searchExp\": company,\r\n \"searchCondition.dbId\": \"VDB\",\r\n \"resultPagination.limit\": \"12\",\r\n \"searchCondition.searchType\": \"Sino_foreign\",\r\n \"wee.bizlog.modulelevel\": \"0200101\"\r\n }\r\n r = requests.post(url, data=d, cookies=get_cookies(),\r\n headers={'User-Agent': random.choice(user_agents)})\r\n time.sleep(10)\r\n # open(\"content.html\", \"w\").write(r.content)\r\n rows, form_data = extract_data(r.content)\r\n # form_data = {}\r\n if \"resultPagination.totalCount\" not in form_data:\r\n form_data[\"resultPagination.totalCount\"] = 0\r\n return form_data[\"resultPagination.totalCount\"]\r\n\r\n\r\ndef process():\r\n f = open(\"patent_all.txt\", \"a\")\r\n f_log = open(\"log\", \"a\")\r\n\r\n companys = file_to_list(\"\", \"company\")\r\n companys_log = file_to_list(\"\", \"log\")\r\n\r\n post_num = 0\r\n stop_page = 311\r\n\r\n for company in companys:\r\n\r\n if company in companys_log:\r\n print \"skip\"\r\n continue\r\n page = 1\r\n if stop_page != 0:\r\n result = {}\r\n result[\"resultPagination.start\"] = 12 * stop_page\r\n result[\"searchCondition.searchExp\"] = company\r\n result[\"resultPagination.totalCount\"] = 5204\r\n page = stop_page\r\n stop_page = 0\r\n else:\r\n content = parse_index(company)\r\n result = check_post_num(post_num, content, f)\r\n\r\n if not isinstance(result, int):\r\n print result[\"resultPagination.totalCount\"]\r\n print company, \"page \", page\r\n while (int(result[\"resultPagination.start\"]) != int(result[\"resultPagination.totalCount\"]) / 12 * 12):\r\n page += 1\r\n result[\"resultPagination.start\"] = int(result[\"resultPagination.start\"]) + 12\r\n print company, \"page \", page\r\n content = parse_turn_page(result)\r\n\r\n result = check_post_num(post_num, content, f)\r\n if isinstance(result, int):\r\n if result == 0:\r\n break\r\n else:\r\n print company, \"page \", page\r\n print 1 / 0\r\n else:\r\n if result == -1:\r\n print company, \"page 1\"\r\n break\r\n\r\n f_log.write(company + \"\\n\")\r\n\r\n\r\ndef post_test():\r\n result = {}\r\n result[\"resultPagination.start\"] = 12 * 311\r\n result[\"searchCondition.searchExp\"] = \"康佳集团股份有限公司\"\r\n result[\"resultPagination.totalCount\"] = 5204\r\n print parse_turn_page(result)\r\n\r\n\r\ndef fitter_useful_ip():\r\n for pro in pros:\r\n if not test_useful(pro):\r\n print pro\r\n\r\n\r\nif __name__ == \"__main__\":\r\n\r\n # fitter_useful_ip()\r\n\r\n f = open(\"patent_all.txt\", \"a\")\r\n f_log = open(\"patent_num.csv\", \"a\")\r\n\r\n companys = file_to_list(\"\", \"company\")\r\n companys_log = file_to_list(\"\", \"patent_num.csv\")\r\n post_num = 0\r\n for company in companys:\r\n if company not in companys_log:\r\n num = get_patent_num(company)\r\n print company, num\r\n f_log.write(company + \",\" + str(num) + \"\\n\")\r\n post_num += 1\r\n if post_num > 400:\r\n break\r\n else:\r\n print company\r\n f.close()\r\n f_log.close()\r\n\r\n # process()\r\n # file_to_json(\"patent_all.txt\")\r\n"
},
{
"alpha_fraction": 0.49554014205932617,
"alphanum_fraction": 0.5953088998794556,
"avg_line_length": 35.37036895751953,
"blob_id": "03c41abdfacdcaae593d69941752f9183db8527a",
"content_id": "174632ef97810e9379abcbe7233e6269f42fe065",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3027,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 81,
"path": "/test_ip_pools.py",
"repo_name": "wingsgit/patentSpider",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\r\n# -*- coding: utf-8 -*-\r\n# @Time : 2017/8/21 11:43 \r\n# @Author : chesian\r\n# @Site : \r\n# @File : test_ip_pools.py\r\n# @Software: PyCharm\r\nimport random\r\n\r\nimport pandas as pd\r\nimport requests\r\nimport sys\r\nfrom bs4 import BeautifulSoup\r\n\r\n\r\ndef func():\r\n pass\r\n\r\nreload(sys)\r\nsys.setdefaultencoding('utf-8')\r\n\r\nuser_agents = [\r\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36 OPR/26.0.1656.60'\r\n 'Mozilla/5.0 (Windows NT 5.1; U; en; rv:1.8.1) Gecko/20061208 Firefox/2.0.0 Opera 9.50'\r\n 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; en) Opera 9.50'\r\n 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:34.0) Gecko/20100101 Firefox/34.0'\r\n 'Mozilla/5.0 (X11; U; Linux x86_64; zh-CN; rv:1.9.2.10) Gecko/20100922 Ubuntu/10.10 (maverick) Firefox/3.6.10'\r\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/534.57.2 (KHTML, like Gecko) Version/5.1.7 Safari/534.57.2'\r\n 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.71 Safari/537.36'\r\n 'Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.64 Safari/537.11'\r\n 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.16 (KHTML, like Gecko) Chrome/10.0.648.133 Safari/534.16'\r\n 'Mozilla/5.0 (Macintosh; U; Intel Mac OS X 10_6_8; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'\r\n 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-us) AppleWebKit/534.50 (KHTML, like Gecko) Version/5.1 Safari/534.50'\r\n 'Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0'\r\n 'Mozilla/4.0 (compatible; MSIE 8.0; Windows NT 6.0; Trident/4.0)'\r\n 'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/50.0.2661.75 Safari/537.36'\r\n]\r\n\r\n\r\ndef clawer_ips():\r\n base_url = \"http://www.kuaidaili.com/free/inha/\"\r\n f_ips = open(\"ips.csv\", \"a\")\r\n for page in range(1, 1789):\r\n url = base_url + str(page)\r\n r = requests.get(url)\r\n soup = BeautifulSoup(r.content)\r\n nodes = soup.find_all(\"tr\")\r\n for node in nodes:\r\n # print node\r\n for a in node.select(\"td\"):\r\n # print \"\".join(a.stripped_strings)\r\n f_ips.write(\"\".join(a.stripped_strings)+\",\")\r\n f_ips.write(\"\\n\")\r\n # break\r\n\r\n\r\ndef test_useful(proxy):\r\n # print '[INFO] Testing proxy ', proxy, ' now...'\r\n try:\r\n proxies = {'http': proxy}\r\n requests.get('http://www.pss-system.gov.cn', timeout=5, proxies=proxies)\r\n # print '[Congra] Successfully get one'\r\n return True\r\n except Exception, e:\r\n # print e\r\n return False\r\n\r\n\r\nif __name__ == \"__main__\":\r\n # clawer_ips()\r\n ip_pools = set()\r\n ips = pd.read_csv(\"ip.csv\")\r\n\r\n\r\n for ip, port in zip(ips[\"IP\"], ips[\"PORT\"]):\r\n pro = str(ip)+\":\"+str(port)\r\n if test_useful(pro):\r\n ip_pools.add(pro)\r\n\r\n for ip in ip_pools:\r\n print ip\r\n"
},
{
"alpha_fraction": 0.8028169274330139,
"alphanum_fraction": 0.8028169274330139,
"avg_line_length": 21.66666603088379,
"blob_id": "879fff575b7a7e340f19727b305077068bf44b9c",
"content_id": "ee84546e94fb839d889a48cc1fb9c8f64554cdc9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 137,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 3,
"path": "/README.md",
"repo_name": "wingsgit/patentSpider",
"src_encoding": "UTF-8",
"text": "\"# patentSpider\r\n\r\n关于获取免费IP代理, 可以查看 ProxySpider项目:爬取西刺上的代理IP,并验证代理可用性\r\n"
}
] | 3 |
zongjie233/liaoxuefengPython3 | https://github.com/zongjie233/liaoxuefengPython3 | 667fa3b13536c3d10f40af24fa78a0c9d1303461 | 5ddfe03c6aa7b9fe855c87e8fbf75b05b6e8bae2 | feeebe69f628ec42e78de664e4194a3ccadeed26 | refs/heads/master | 2022-11-12T19:52:40.233112 | 2020-07-02T10:05:52 | 2020-07-02T10:05:52 | 262,496,518 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.675608217716217,
"alphanum_fraction": 0.681846559047699,
"avg_line_length": 20.66216278076172,
"blob_id": "a516eecc8f2c5811ee59d643e408c7a024c4a157",
"content_id": "084da65fc551e4c0c82db93c20e4cb27bd514b29",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2731,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 74,
"path": "/面向对象编程/类和实例.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "'''\n面向对象最重要的概念就是类(Class)和实例(Instance),必须牢记类是抽象的模板,比如Student类,而实例是根据类创建出来的一个个具体的“对象”,\n每个对象都拥有相同的方法,但各自的数据可能不同。\n'''\n# class Student(object):\n# pass\n\n#变量指向一个实例,后边为内存地址,每个object的地址都不一样。Student本身则是一个类\n# hs = Student()\n# print(hs)\n# # 可以自由地给一个实例变量绑定属性,比如,给实例bart绑定一个name属性:\n# hs.name = 'huang shang'\n# print(hs.name)\n\n'''\n类可以起到模板的作用,因此,可以在创建实例的时候,把一些我们认为必须绑定的属性强制填写进去。通过定义一个特殊的__init__方法,在创建实例的\n时候,就把name,score等属性绑上去:\n'''\n# class Student(object):\n#\n# def __init__(self, name, score):\n# self.name = name\n# self.score = score\n#\n# hs = Student('hs',100)\n# print(hs.name)\n# print(hs.score)\n\n# 和普通的函数相比,在类中定义的函数只有一点不同,就是第一个参数永远是实例变量self\n\n# 数据封装\n'''\n面向对象编程的一个重要特点就是数据封装。在上面的Student类中,每个实例就拥有各自的name和score这些数据。我们可以通过函数来访问这些数据,比如\n打印一个学生的成绩:\n'''\n# def print_score(std):\n# print(f'{std.name} {std.score}')\n\n# print_score(hs)\n\n'''\n既然Student实例本身就拥有这些数据,要访问这些数据,就没有必要从外面的函数去访问\n可以直接在Student类的内部定义访问数据的函数,这样,就把“数据”给封装起来了\n'''\nclass Student(object):\n\n def __init__(self, name, score):\n self.name = name\n self.score = score\n\n def print_score(self):\n print(f'{self.name} {self.score}')\n\n #可以直接增加新的方法\n def get_grade(self):\n if self.score > 90:\n return 'A'\n elif self.score >= 60:\n return 'B'\n else:\n return \"C\"\n\nhs = Student('huangshang', 100)\nhs.print_score()\nprint(hs.get_grade())\n\n#直接添加自定义属性,不用更改class的格局\nhs.appearance = 'handsome'\nprint(hs.appearance)\n# 这样做的好处我们从外部看Student类,就只需要知道,创建实例需要给出name和score,而如何打印,都是在Student类的内部定义的,这些数据和逻辑被\n# “封装”起来了,调用很容易,但却不用知道内部实现的细节。\n\n\n# 类是创建实例的模板,而实例则是一个一个具体的对象,各个实例拥有的数据都互相独立,互不影响;\n"
},
{
"alpha_fraction": 0.5851631760597229,
"alphanum_fraction": 0.5910979509353638,
"avg_line_length": 25.265625,
"blob_id": "441e91d3f937ace9e979c917b56a00298e2ca5dc",
"content_id": "1bc9850ab9f24d9fd9a52ca4ee48271fce3a2d3c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2231,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 64,
"path": "/错误,调试,测试/mydict_test.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "# 为了编写单元测试,我们需要引入Python自带的unittest模块\nimport unittest\nfrom mydict import Dict\n\nclass TestDict(unittest.TestCase):\n\n def test_init(self):\n d = Dict(a = 1, b = 'test')\n self.assertEqual(d.a, 1)\n self.assertEqual(d.b, 'test')\n self.assertTrue(isinstance(d, dict))\n\n def test_key(self):\n d = Dict()\n d['key'] = 'value'\n self.assertEqual(d.key, 'value')\n\n def test_attr(self):\n d = Dict()\n d.key = 'value'\n self.assertTrue('key' in d)\n self.assertEqual(d['key'], 'value') #断言函数返回的结果与'value'相等\n\n def test_keyerror(self):\n d = Dict()\n #期待抛出指定类型的Error\n with self.assertRaises(KeyError):\n value = d['empty']\n\n def test_attrerror(self):\n d = Dict()\n with self.assertRaises(AttributeError):\n value = d.empty\n\nif __name__ == '__main__':\n unittest.main()\n'''\n编写单元测试时,我们需要编写一个测试类,从unittest.TestCase继承。\n\n以test开头的方法就是测试方法,不以test开头的方法不被认为是测试方法,测试的时候不会被执行。\n\n对每一类测试都需要编写一个test_xxx()方法。由于unittest.TestCase提供了很多内置的条件判断,我们只需要调用这些方法就可以断言输出是否是我们所期望的。\n'''\n\n'''\nsetUp tearDown\n可以在单元测试中编写两个特殊的setUp()和tearDown()方法。这两个方法会分别在每调用一个测试方法的前后分别被执行。\n设想你的测试需要启动一个数据库,这时,就可以在setUp()方法中连接数据库,在tearDown()方法中关闭数据库,这样,不必在每个测试方法中重复相同的代码\n'''\n# class Student(object):\n# def __init__(self, name, score):\n# self.name = name\n# self.score = score\n# def get_grade(self):\n# if self.score > 100:\n# raise ValueError\n# elif self.score >= 80:\n# return 'A'\n# elif self.score >= 60:\n# return 'B'\n# elif self.score >= 0:\n# return 'C'\n# else:\n# raise ValueError\n\n\n\n\n"
},
{
"alpha_fraction": 0.5796309113502502,
"alphanum_fraction": 0.6103895902633667,
"avg_line_length": 22.079364776611328,
"blob_id": "380e95545d4c17797e8c96d2a3f0b77f5c9aa75d",
"content_id": "797ce55125aefdcd9ced565dbfa13e99244aee3f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1681,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 63,
"path": "/面向对象高级编程/使用@property.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "#绑定属性时,如果直接把属性暴露出去,没办法检查参数,可以在类中新建方法来设置成绩\n# class Student():\n# def get_score(self):\n# return self.score\n#\n# def set_score(self, score):\n# if not isinstance(score, int):\n# raise ValueError('score must be an integer!')\n# if score < 0 or score > 100:\n# raise ValueError('score must between 0~100!')\n# self.score = score\n#\n# h = Student()\n# h.set_score(100)\n# print(h.get_score())\n# h.set_score(909090)#这样会抛出异常\n\n#上述调用方式比较复杂。内置的@property可以把一个方法变成属性调用的\nclass Student():\n\n @property\n def score(self):\n return self.score_\n\n#@score.setter 由@property创建\n @score.setter#负责把一个setter方法变成属性赋值\n def score(self, score):\n if not isinstance(score, int):\n raise ValueError('score must be an integer!')\n if score < 0 or score > 100:\n raise ValueError('score must between 0~100!')\n self.score_ = score\n\ns = Student()\ns.score = 30\nprint(s.score)\n# s.score = 9000 #报错\n\nclass Screen():\n\n @property\n def width(self):\n return self._width\n @width.setter\n def width(self,width):\n self._width = width\n\n @property\n def height(self):\n return self._height\n @height.setter\n def height(self,height):\n self._height = height\n\n @property\n def resolution(self):\n return self._width * self._height\n\nA = Screen()\nA.height = 1080\nA.width = 1920\nprint(A.resolution)\nA.resolution = 102020 #不可更改的属性,如果设置值会报错\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.676075279712677,
"alphanum_fraction": 0.6881720423698425,
"avg_line_length": 17.64102554321289,
"blob_id": "3a39b9ee457dc8c5f07442348dbc40d296eb26a8",
"content_id": "234398a5acd8062905b00c095602bc5047f9a5d4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1162,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 39,
"path": "/面向对象高级编程/使用__slots__.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "# 创建了一个class的实例后,我们可以给该实例绑定任何属性和方法,这就是动态语言的灵活性。\nclass Student():\n pass\n\ns = Student()\ns.name = 'hs'#动态给予属性\nprint(s.name)\n\n#还可以给实例绑定一个方法\ndef set_age(self,age):\n self.age = age\n\nfrom types import MethodType\ns.set_age = MethodType(set_age, s) #给实例绑定一个方法\ns.set_age(21)\n\nprint(s.age)\n#给实例绑定的方法,对另一个实例是不起作用的,可以给class绑定方法\n# Student.set_age = set_age #此语句只是调用方法\nStudent.set_age=MethodType(set_age,Student) #将方法绑定到类\nprint(Student.set_age,set_age)\nh = Student()\nh.set_age(20)\nprint(h.age)\n'''\n在动态语言中,上述绑定方法的功能很容易实现,但是在静态语言中难以实现\n'''\n\n#使用__slots__\n#通过slots可以实现限制class添加属性的功能\nclass Stu():\n __slots__ = ('name', 'age')\n\nz = Stu()\nz.name = 'zfy'\nz.age = 21\n# z.score = 100 #不在限制范围内,所以会报错\n\n#!!!!__slots__定义的属性支队当前类的实例起作用,对继承的子类是不起作用的\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.8061325550079346,
"alphanum_fraction": 0.8160237669944763,
"avg_line_length": 31.161291122436523,
"blob_id": "681ec8166cdc9af7364a795bb297ebba6ebb4dac",
"content_id": "c99774dd1d1a83ab3ab3e0640aebe3699bd40c4d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2593,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 31,
"path": "/IO编程/简介.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "'''\nIO在计算机中指Input/Output,也就是输入和输出。由于程序和运行时数据是在内存中驻留,由CPU这个超快的计算核心来执行,涉及到数据交换的地方,通常\n是磁盘、网络等,就需要IO接口。\n通常,程序完成IO操作会有Input和Output两个数据流。\n当然也有只用一个的情况,比如,从磁盘读取文件到内存,就只有Input操作,反过来,把数据写到磁盘文件里,就只是一个Output操作。\n\nIO编程中,Stream(流)是一个很重要的概念,可以把流想象成一个水管,数据就是水管里的水,但是只能单向流动。Input Stream就是数据从外面\n(磁盘、网络)流进内存,Output Stream就是数据从内存流到外面去。对于浏览网页来说,浏览器和新浪服务器之间至少需要建立两根水管,才可以既能发\n数据,又能收数据。\nOutput Stream就是数据从内存流到外面去。对于浏览网页来说,浏览器和新浪服务器之间至少需要建立两根水管,才可以既能发数据,又能收数据。\n\n'''\n\n'''\n在IO编程中,就存在速度严重不匹配的问题,有两种方法:\n1.CPU等着,也就是程序暂停执行后续代码,等100M的数据在10秒后写入磁盘,再接着往下执行,这种模式称为同步IO;\n2.CPU不等待,只是告诉磁盘,“您老慢慢写,不着急,我接着干别的事去了”,于是,后续代码可以立刻接着执行,这种模式称为异步IO。\n好比你去麦当劳点餐,你说“来个汉堡”,服务员告诉你,对不起,汉堡要现做,需要等5分钟,于是你站在收银台前面等了5分钟,拿到汉堡再去逛商场,这是同步IO。\n你说“来个汉堡”,服务员告诉你,汉堡需要等5分钟,你可以先去逛商场,等做好了,我们再通知你,这样你可以立刻去干别的事情(逛商场),这是异步IO。\n‘’‘\n\n’‘’\n使用异步IO来编写程序性能会远远高于同步IO,但是异步IO的缺点是编程模型复杂。想想看,你得知道什么时候通知你“汉堡做好了”,而通知你的方法也各\n不相同。如果是服务员跑过来找到你,这是回调模式,如果服务员发短信通知你,你就得不停地检查手机,这是轮询模式。总之,异步IO的复杂度远远高于同步IO。\n'''\n\n'''\n基本概念:input, output,stream\n存在问题:输入和接收速度不匹配\n解决方法:同步、异步(回调--好了叫我,轮询---好了没...好了没)\n'''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.6341127753257751,
"alphanum_fraction": 0.716643750667572,
"avg_line_length": 21.6875,
"blob_id": "4a44736d5e59e4d52f9d1f2643d2803902090a40",
"content_id": "b3f032fdc4b9d3af439b91e68eea5ca7925494d8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1217,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 32,
"path": "/函数式编程/偏函数.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "import functools\n#functools 模块中的 偏函数功能(Partial function)\n#int()函数可以吧字符串转换为整数,默认按十进制转换\nprint(int('123456'))\n\n#int()函数提供额外的base参数,默认值为10,可以做N进制的转换\nprint(int('123456', base = 8))\nprint(int('123456', base = 16))\n\n#如果要转换大量的二进制字符串,每次都要传入int(x, base = 2)很麻烦,可以定义一个int2()函数\ndef int2(x, base = 2):\n return int(x, base)\nprint(int2('100000'))\n#int2()函数只是吧base的默认值设为2.也可以在函数调用时进行更改\n\n#创建偏函数时,实际上可以接受函数对象,*args,**kw这三个参数\n\n#实际上固定了关键字参数base\nint2 = functools.partial(int, base = 2)\n#相当于kw = {'base' : 2}\n# int('10010', **kw)\n\n# 当传入:\nmax2 = functools.partial(max, 10)\n# 实际上会把10作为*args的一部分自动加到左边,也就是:\nmax2(5, 6, 7)\n# 相当于:\nargs = (10, 5, 6, 7)\nmax(*args)\n# 结果为10。\n\n#当函数的参数个数太多,需要简化时,使用functools.partial可以创建一个新的函数,这个新函数可以固定住原函数的部分参数,从而在调用时更简单。\n\n"
},
{
"alpha_fraction": 0.5929824709892273,
"alphanum_fraction": 0.6153509020805359,
"avg_line_length": 19.25,
"blob_id": "e10fc83d0696fdd6d04e30c120f034e06ef5baa5",
"content_id": "d66938c12b8c74c54b3006401aefeb7fdd7b862c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3548,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 112,
"path": "/错误,调试,测试/错误处理.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "'''\n在程序运行的过程中,如果发生了错误,可以事先约定返回一个错误代码,这样,就可以知道是否有错,以及出错的原因。在操作系统提供的调用中,返回错误码非常\n常见。比如打开文件的函数open(),成功时返回文件描述符(就是一个整数),出错时返回-1。\n用错误码来表示是否出错十分不便,因为函数本身应该返回的正常结果和错误码混在一起,造成调用者必须用大量的代码来判断是否出错\n'''\n\n#try\n'''\n当我们认为某些代码可能会出错时,就可以用try来运行这段代码,如果执行出错,则后续代码不会继续执行,而是直接跳转至错误处理代码,即except语句块,\n执行完except后,如果有finally语句块,则执行finally语句块,至此,执行完毕。\n'''\n# try:\n# print('try...')\n# r = 10 / 0\n# print(f'result: {r}')\n# except ZeroDivisionError as e:\n# print(f'except:{e}')\n# finally:\n# print('finally...')\n# print('END')\n#当错误发生时,后续语句不会被执行,except由于捕获到错误,执行语句,最后执行finally\n\n# 可以有多个except来捕获不同类型的错误:\n# try:\n# print('try...')\n# r = 10 / int('2')\n# print(f'result:{r}')\n# except ValueError as e:\n# print(f'ValueError:{e}')\n# except ZeroDivisionError as e:\n# print(f'ZeroDivisionError:{e}')\n# else:\n# print('no error')\n# finally:\n# print('finally..')\n# print('END')\n\n#try可以跨越多层调用。\n# 函数main()调用bar(),bar()调用foo(),结果foo()出错了,这时,只要main()捕获到了,就可以处理:\n# def foo(s):\n# return 10 / int(s)\n#\n# def bar(s):\n# return foo(s) * 2\n#\n# def main():\n# try:\n# bar('0')\n# except Exception as e:\n# print('Error:', e)\n# finally:\n# print('finally...')\n#\n# main()\n\n#记录错误\n# import logging\n#\n# def foo(s):\n# return 10 / int(s)\n#\n# def bar(s):\n# return foo(s) * 2\n#\n# def main():\n# try:\n# bar('0')\n# except Exception as e:\n# logging.exception(e)\n\n# main()\nprint('END')#即使是出现错误,再打印出错误信息之后,后续代码依然会被执行,\n\n'''\n因为错误是class,捕获一个错误就是捕获到该class的一个实例。\nPython的内置函数会抛出很多类型的错误,我们自己编写的函数也可以抛出错误。\n'''\n#根据需要,可以定义一个错误的class,选择好继承关系,然后,用raise语句抛出一个错误的实例:\n# class FooError(ValueError):\n# pass\n#\n# def fo(s):\n# n = int(s)\n# if n == 0:\n# raise FooError(f'invalid value {s}')\n# return 10 / n\n\n# fo('0')\n'''\n捕获错误目的只是记录一下,便于后续追踪。但是,由于当前函数不知道应该怎么处理该错误,所以,最恰当的方式是继续往上抛,让顶层调用者去处理。好比\n一个员工处理不了一个问题时,就把问题抛给他的老板,如果他的老板也处理不了,就一直往上抛,最终会抛给CEO去处理。\n'''\n\n\n# ex运行下面的代码,根据异常信息进行分析,定位出错误源头,并修复:\nfrom functools import reduce\n\ndef str2num(s):\n return float(s)\n\ndef calc(exp):\n ss = exp.split('+')\n ns = map(str2num, ss)\n return reduce(lambda acc, x: acc + x, ns)\n\ndef main():\n r = calc('100 + 200 + 345')\n print('100 + 200 + 345 =', r)\n r = calc('99 + 88 + 7.6')\n print('99 + 88 + 7.6 =', r)\n\nmain()\n\n\n\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.5628834366798401,
"alphanum_fraction": 0.5828220844268799,
"avg_line_length": 16.31999969482422,
"blob_id": "02c4cccb20f6399d0831f2432a947e5c3e674f8c",
"content_id": "0d9143689017d7380ee59dd24a4946c25de3fe27",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1698,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 75,
"path": "/高级特性/生成器.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "#generator\n#创建方法1\nL = [x * x for x in range(10)]\nprint(L)\n#将[]改为()即可\ng = (x * x for x in range(10))\nprint(g)\n\n#通过next()函数来获取generator的下一个返回值,但正确方法应该是使用for循环\nfor n in g:\n print(n)\n\n#输出斐波拉契数列前n项\ndef fib(max):\n n,a,b = 0,0,1\n while n < max:\n print(b)\n a, b = b, a+b\n n += 1\n return 'done'\n\nfib(10)\n\n#如果一个函数定义中包含yield关键字,那么这个函数就不再是一个普通的函数,而是一个generator\ndef fib_generator(max):\n n,a,b = 0,0,1\n while n < max:\n yield b\n a, b = b, a+b\n n += 1\n return 'done'\nf = fib_generator(10)\nprint(f)\n#变成generator的函数,在每次调用next()的时候执行,遇到yield语句返回,再次执行时从上次返回的yield语句处继续执行。\n\ndef odd():\n print('step1')\n yield\n print('step2')\n yield\n print('step3')\n yield\n\n#调用generator时,首先要生成一个generator对象,然后用next()函数获取下一个返回值\na = odd()\nnext(a)\nnext(a)\nnext(a)\n\n#用for循环调用generator时,拿不到return语句中的返回值,如果想要拿回返回值必须捕获StopIteration\ng = fib_generator(6)\nwhile True:\n try:\n x = next(g)\n print('g:',x)\n except StopIteration as e:\n print('return value:', e.value)\n break\n\n#杨辉三角形\n#使用错位相加的方法\ndef triangles():\n l = [1]\n s =[]\n while True:\n yield l\n l = [1] + s + [1]\n for i in range(len(l)-1):\n s.append(l[i] + l[i+1])\n\nb = triangles()\nprint(next(b))\nprint(next(b))\nprint(next(b))\nprint(next(b))\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.4308681786060333,
"alphanum_fraction": 0.45016077160835266,
"avg_line_length": 24.83333396911621,
"blob_id": "3cf236305ff5a158c6f35f7f429064a6625125c2",
"content_id": "cc5fa7faeb63b39056fff156df9ee0f12f2615e2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 403,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 12,
"path": "/函数/递归函数.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "#汉诺塔图解递归算法\n\ndef move(n, a, b, c):\n if n == 1:\n print(a, '--->', c)\n else:\n move(n-1,a, c, b)#将A柱子上的n-1个盘子放到B柱子上\n # print(\"这是a,c,b排列的abc值:\",a,b,c)\n print(a, '--->', c)\n move(n - 1, b, a, c)#将B柱子上的n-1个放到C柱子上\n # print(\"这是b,a,c排列的abc值\",a,b,c)\nmove(3, 'A', 'B', 'C') "
},
{
"alpha_fraction": 0.7163531184196472,
"alphanum_fraction": 0.7452966570854187,
"avg_line_length": 28.913043975830078,
"blob_id": "a95db21a7a5c07620a8850fa337e9beb5cc70af3",
"content_id": "6580af085711107d19948b80e63a73ab887a1c2a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 879,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 23,
"path": "/高级特性/迭代器.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "#可以直接作用于for循环的对象统称为可迭代对象:Iterable。\nfrom collections.abc import Iterable\nfrom collections.abc import Iterator\n\n#isinstance()判断一个对象是否是Iterable对象\nprint(isinstance([], Iterable))\nprint(isinstance({}, Iterable))\nprint(isinstance('abc', Iterable))\nprint(isinstance((x for x in range(1,10)), Iterable))\nprint(isinstance(100, Iterable))\nprint(\"-------------------\")\n#可以被next()函数调用并不断返回下一个值的对象称为迭代器:Iterator。\nprint(isinstance(100, Iterator))\nprint(isinstance([], Iterator))\nprint(isinstance({}, Iterator))\nprint(isinstance((x for x in range(10)), Iterator))\n\n#生成器都是Iterator对象,但list、dict、str虽然是Iterable,却不是Iterator。\n#iter()函数可以把list dict str 等可迭代对象编程迭代器\n\n\nstr1 = \"123.456\"\nprint(str1.split(\".\",1))\n\n\n\n"
},
{
"alpha_fraction": 0.7454545497894287,
"alphanum_fraction": 0.7545454502105713,
"avg_line_length": 19.935483932495117,
"blob_id": "c63cd33dec8691add8bf0f186a6f38340d23e252",
"content_id": "c82836aa84f696d6a274c49c21008e43db68548c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1154,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 31,
"path": "/面向对象高级编程/使用元类.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "from hello import Hello\n#当解释器载入hello模块时,就会意思执行该模块的代码,执行结果就是动态创建出一个Hello的class对象\n\nh = Hello()\nh.hello()\nprint(type(Hello))\nprint(type(h))\n\n#type()函数既可以返回一个对象的类型,又可以创建出新的类型。\n#eg 用type()函数创建出Hello类。\ndef fn(self, name = 'world'):#先定义函数\n print(f'Hello {name}')\n\nHello = type('Hello',(),dict(hello = fn)) #创建Hello class\n\nh1 = Hello()\nh1.hello()\n'''\n要创建一个class对象,type()函数依次传入3个参数:\n\n1.class的名称;\n2.继承的父类集合,注意Python支持多重继承,如果只有一个父类,别忘了tuple的单元素写法;\n3.class的方法名称与函数绑定,这里我们把函数fn绑定到方法名hello上\n通过type()函数创建的类和直接写class是完全一样的,因为Python解释器遇到class定义时,仅仅是扫描一下class定义的语法,然后调用type()函数创建出class。\n'''\n\n#metaclass 元类\n'''\n可以使用metaclass 控制类的创建行为\n先定义metaclass,就可以创建类,最后创建实例\n'''\n\n\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.6736111044883728,
"alphanum_fraction": 0.6736111044883728,
"avg_line_length": 23.16666603088379,
"blob_id": "477d23083f490d2d118746c71d08c641dd64457d",
"content_id": "bf4dd5e9c7fdcd679425a25423ca394539aa64ef",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 224,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 6,
"path": "/面向对象高级编程/hello.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "#动态语言和静态语言最大的不同,就是函数和类的定义,不是编译时定义,而是动态创建的\nclass Hello():\n def hello(self, name = 'world'):\n print(f'Hello {name}')\n\nprint(type(Hello))"
},
{
"alpha_fraction": 0.6800000071525574,
"alphanum_fraction": 0.696825385093689,
"avg_line_length": 22.840909957885742,
"blob_id": "40f39d0331ff9d2b8c12d30b0c4d88f252a2311d",
"content_id": "506d516bab906e933efd45a1872f54629eb55caa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4994,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 132,
"path": "/进程和线程/多线程.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "'''\nPython的标准库提供了两个模块:_thread和threading,_thread是低级模块,threading是高级模块,对_thread进行了封装。绝大多数情况下,\n我们只需要使用threading这个高级模块。\n'''\n#启动一个线程就是将一个函数传入并创建Thread实例,然后调用start()开始执行\nimport time, threading\n\n#新线程执行的代码\n# def loop():\n# print(f'thread {threading.current_thread().name} is running...')\n# n = 0\n# while n < 5:\n# n += 1\n# print(f'thread {threading.current_thread().name} >>> {n}')\n# time.sleep(1)\n# print(f'thread {threading.current_thread().name} ended.')\n#\n# print(f'thread {threading.current_thread().name}')\n# t = threading.Thread(target=loop, name='LoopThread') #创建Thread实例,传入函数\n# t.start()\n# t.join()\n# print(f'thread {threading.current_thread().name} ended')\n'''\nPython的threading模块有个current_thread()函数,它永远返回当前线程的实例。主线程实例的名字叫MainThread,子线程的名字在创建时指定,\n我们用LoopThread命名子线程。名字仅仅在打印时用来显示,完全没有其他意义,如果不起名字Python就自动给线程命名为Thread-1,Thread-2……\n'''\n\n'''\nLock\n多线程和多进程最大的不同在于,多进程中,同一个变量,各自有一份拷贝存在于每个进程中,互不影响,而多线程中,所有变量都由所有线程共享,\n所以,任何一个变量都可以被任何一个线程修改\n\n下述代码正常运行时 结果balance = 0,但线程是交替运行的,所以交替运行多次可能会出错\n原因是修改balance需要多条语句,而执行这些语句时,线程可能终端,从而导致多个线程把同一个对象的内容改乱了,两个线程同时一存一取,\n就可能导致余额不对。\n'''\n# 假定这是你的银行存款:\nbalance = 0\nlock = threading.Lock() #创建🔒\n\ndef change_it(n):\n # 先存后取,结果应该为0:\n global balance\n balance = balance + n\n balance = balance - n\n\ndef run_thread(n):\n for i in range(1000000):\n #获取锁\n lock.acquire()\n try:\n change_it(n)\n finally:\n #释放锁\n lock.release()\n\nt1 = threading.Thread(target=run_thread, args=(5,))\nt2 = threading.Thread(target=run_thread, args=(8,))\nt1.start()\nt2.start()\nt1.join()\nt2.join()\nprint(balance)\n\n'''\n必须确保一个线程在修改balance的时候,别的线程一定不能改动\n要给change_it()上一把锁,当某个线程开始执行change_it()时,我们说,该线程因为获得了锁,因此其他线程不能同时执行change_it(),只能等\n待,直到锁被释放后,获得该锁以后才能改。由于锁只有一个,无论多少线程,同一时刻最多只有一个线程持有该锁,所以,不会造成修改的冲突。\n创建一个🔒是通过threading.Lock()来实现的\n'''\n'''\n当多个线程同时执行lock.acquire()时,只有一个线程能成功地获取锁,然后继续执行代码,其他线程就继续等待直到获得锁为止。\n\n'''\n\n'''\nPython的线程虽然是真正的线程,但解释器执行代码时,有一个GIL锁:Global Interpreter Lock,任何Python线程执行前,必须先获得GIL锁,\n然后,每执行100条字节码,解释器就自动释放GIL锁,让别的线程有机会执行。这个GIL全局锁实际上把所有线程的执行代码都给上了锁,所以,多线\n程在Python中只能交替执行,即使100个线程跑在100核CPU上,也只能用到1个核。\n'''\n\n#死循环\nimport threading, multiprocessing\n\ndef loop():\n x = 0\n while True:\n x = x ^ 1\n\nfor i in range(multiprocessing.cpu_count()):\n t = threading.Thread(target=loop)\n t.start()\n\n#计算子线程执行的时间\nimport threading\nimport time\n\ndef run(n):\n print('task', n, threading.current_thread()) #输出当前的线程\n time.sleep(1)\n\n#\n# start_time = time.time()\n\nimport threading\nimport time\n\n#由于主线程比子线程快很多,当主线程执行active_count()时,其他子线程都还没执行完毕,因此利用主线程统计的活跃的线程数\n# num = sub_num(子线程数量)+1(主线程本身)\ndef run(n):\n print(\"task\", n)\n time.sleep(1) #此时子线程停1s\n\nfor i in range(3):\n t = threading.Thread(target=run, args=(\"t-%s\" % i,))\n t.start()\n\ntime.sleep(0.5) #主线程停0.5秒\nprint(threading.active_count()) #输出当前活跃的线程数\n\n#由于主线程比子线程慢很多,当主线程执行active_count()时,其他子线程都已经执行完毕,因此利用主线程统计的活跃的线程数num = 1(主线程本身)\ndef run(n):\n print(\"task\", n)\n time.sleep(0.5) #此时子线程停0.5s\n\n\nfor i in range(3):\n t = threading.Thread(target=run, args=(\"t-%s\" % i,))\n t.start()\n\ntime.sleep(1) #主线程停1秒\nprint(threading.active_count()) #输出活跃的线程\n\n\n\n"
},
{
"alpha_fraction": 0.7382297515869141,
"alphanum_fraction": 0.743879497051239,
"avg_line_length": 31.84375,
"blob_id": "c142b8aa6a20b3706f2c2124aba3379b0efb4a2f",
"content_id": "9e20c0a82f4f106359c4dd94db68a0984b600f93",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1568,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 32,
"path": "/IO编程/操作文件和目录.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "import os\nprint(os.name) #如果是posix,说明系统是Linux、Unix或Mac OS X,如果是nt,就是Windows系统。\n\nprint(os.environ) #查看操作系统中定义的环境变量\n\n# 要获取某个变量的值,可以调用os.envision.get('key')\nprint(os.environ.get('PATH'))\n\n#查看当前目录的绝对路径\nprint(os.path.abspath('.'))\n\n#在某个目录下创建一个新目录,在创建之前需要把新目录的完整路径表示出来,使用os.path.join()\n# print(os.path.join('D:\\\\PythonProject\\\\liaoxuefengPython3\\\\IO编程','testdir'))\n# os.mkdir('D:\\\\PythonProject\\\\liaoxuefengPython3\\\\IO编程\\\\testdir')\n# os.rmdir('D:\\\\PythonProject\\\\liaoxuefengPython3\\\\IO编程\\\\testdir')\n\n#要拆分路径时,不要拆字符串,而是通过os.path.split()函数。可以吧一个路径拆分为两部分,后一部分总是最后级别的目录活着文件名:\nprint(os.path.split('D:\\\\PythonProject\\\\liaoxuefengPython3\\\\IO编程\\\\test.txt'))\n\n# os.path.splitext()可以直接得到文件扩展名。这些函数只会对路径进行拆分操作\nprint(os.path.splitext('D:\\\\PythonProject\\\\liaoxuefengPython3\\\\IO编程\\\\test.txt'))\n\n#对文件重命名\n# os.rename('test.txt','test.py')\n#删掉文件:\n# os.remove('test.py')\n\n#os模块中没有copyfile()函数,可以使用shutil模块中找到,可以看作是os模块的补充\n\n#利用Python的特性来过滤文件,eg列出当前目录下的所有目录,或者所有.py\nprint(os.getcwd())\nprint([x for x in os.listdir('.') if os.path.isfile(x) and os.path.splitext(x)[1] == '.py'])\n\n\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.6557161808013916,
"alphanum_fraction": 0.6557161808013916,
"avg_line_length": 17.071428298950195,
"blob_id": "27ed069375a602496610fec4487bb5eeb333eea2",
"content_id": "d5629950b9fb99e32c7c77ca0098ab81d89af453",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1195,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 42,
"path": "/面向对象编程/继承和多态.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "'''\n定义一个class时,可以从某个现有的class继承,新的class称为子类(Subclass),被继承的称为基类,父类\n'''\nclass Animal():\n def run(self):\n print(\"Animal is running...\")\n\n#编写dog,cat类是可以直接继承\nclass Dog(Animal):\n def run(self):\n print('Dog is running...')\n\nclass Cat(Animal):\n def run(self):\n print('Cat is running...')\n\nclass car():\n def run(self):\n print('car is running...')\nclass Stone():\n pass\n\nclass Husky(Dog):\n pass\n\n\n#继承会使的子类获得父类的全部功能。\n\n'''\n当子类和父类都存在相同的run()方法时,子类的run覆盖了父类的run,这样就获得了继承的好处 多态\n'''\n#当定义一个class的时候,实际上就定义了一种数据类型\n\n# def run_twice(animal): #对于此方法,不一定要传入animal类,任何带有run方法的类都可以传入并运行\n# animal.run()\n#\n# run_twice(Cat())\n# run_twice(car())\n# run_twice(Stone())\n'''\n这就是动态语言的“鸭子类型”,它并不要求严格的继承体系,一个对象只要“看起来像鸭子,走起路来像鸭子”,那它就可以被看做是鸭子。\n'''\n\n\n"
},
{
"alpha_fraction": 0.6431593894958496,
"alphanum_fraction": 0.6586741805076599,
"avg_line_length": 16.04878044128418,
"blob_id": "30c154bcc7c6f80e64b4512d67d4b2dbd6d2c258",
"content_id": "c5ec2e7683fecbc956a46dbb524316d2b7bedc9b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1183,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 41,
"path": "/错误,调试,测试/调试.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "#断言, 凡是可以用print()来辅助查看的地方 都可以用断言(assert)来替代\n# def foo(s):\n# n = int(s)\n# # assert意思是,表达式n!=0应该是True,否则根据程序运行的逻辑,后面的代码就会出错,如果断言失败就会抛出AssertionError\n# assert n != 0, 'n is zero'\n# return 10 / n\n#\n# def main():\n# foo('0')\n#\n# main()\n\n#python解释器可以通过-O参数来关闭assert,关闭之后assert语句可以当成pass看待\n\n# logging\n'''\nlogging不会抛出错误,而且可以输出到文件,允许指定记录信息的级别\n通过简单的配置,一条语句可以同时输出到不用的地方,比如console和文件\n'''\n# import logging\n#\n# s = '0'\n# n = int(s)\n# logging.info(f'n = {n}')\n# print(10 / n)\n\n#pdb\n'''\n启动python的调试器,让程序以单步方式运行,可以随时查看运行状态\n'''\n\n# pdb.set_trace()\n'''\n这个方法也是用pdb,但是不需要但不执行,在可能出错的地方放一个pdb.set_trace(),就可以设置一个断电\n'''\nimport pdb\n\ns = '0'\nn = int(s)\npdb.set_trace() #运行到这里就会自动暂停,可以用命令c继续执行\nprint(10 / n)\n\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.5972744226455688,
"alphanum_fraction": 0.6156014800071716,
"avg_line_length": 23.090909957885742,
"blob_id": "9040124230d90d983449d7c89da0596698a86664",
"content_id": "e33d5967b8f6f1808957bdacc5332ceb31a603dc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2944,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 88,
"path": "/函数式编程/装饰器.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "#通过变量也能调用该函数\n# def now():\n# print('2020-06-04')\n\n# f = now\n# f()\n\n# #函数对象有一个__name__属性,可以看到函数的名字\n# print(now.__name__)\n# print(f.__name__)\n\n#这种在代码运行期间动态增加功能的方式,称之为“装饰器”(Decorator)。\n#本质上,decorator就是一个返回函数的高阶函数。所以,我们要定义一个能打印日志的decorator,可以定义如下:\n# def log(func):\n# def wrapper(*args, **kw):\n# print('call %s():' % func.__name__)\n# return func(*args, **kw)\n# #返回的是函数本身,而不是运行的结果\n# return wrapper\n# #借助@语法,将decorator置于函数的定义出\n# @log\n# def now():\n# print('2020-06-05')\n#\n# now()\n#相当于执行了语句 now = long(now)\n'''\n由于log()是一个decorator,返回一个函数,所以,原来的now()函数仍然存在,只是现在同名的now变量指向了新的函数,\n于是调用now()将执行新函数,即在log()函数中返回的wrapper()函数。wrapper()函数的参数定义是(*args, **kw),\n因此,wrapper()函数可以接受任意参数的调用。在wrapper()函数内,首先打印日志,再紧接着调用原始函数。\n'''\n#如果decorator函数本身需要传入参数,就需要编写一个高阶函数,\n#eg:定义log文本\ndef log(text):\n def decorator(func):\n def wrapper(*args, **kw):\n print(f'{text},{func.__name__}')\n return func(*args, **kw)\n return wrapper\n return decorator\n@log('execute')\n#相当于运行了now = long('execute')(now)\ndef now():\n print('2020-06-05')\nnow()\n#经过装饰的函数,__name__变成了’wrapper‘\n# 因为返回的那个wrapper()函数名字就是'wrapper',所以,需要把原始函数的__name__等属性复制到wrapper()函数中,否则,有些依赖函数签名的代码执行就会出错。\nprint(now.__name__)\n\n#完整的decorator的写法如下\n# 住在定义wrapper()的前面加上@functools.wraps(func)\nimport functools\ndef log(func):\n @functools.wraps(func)\n def wrapper(*args, **kw):\n print(f'call {func.__name__}')\n return func(*args, **kw)\n return wrapper\n\n#带参数的装饰器\ndef log(text):\n def decorator(func):\n @functools.wraps(func)\n def wrapper(*args, **kwargs):\n print(f'{text} {func.__name__}')\n return func(*args,**kwargs)\n return wrapper\n return decorator\n\n#ex 设计一个decorator,作用于任何函数,并打印该函数的执行时间\nimport time\ndef metric(fn):\n print('%s executed in %s ms' % (fn.__name__, 10.24))\n\n @functools.wraps(fn)\n def wrapper(*args, **kwargs):\n t1 = time.time()\n op = fn(*args, **kwargs)\n t2 = time.time()\n print(f'{t2-t1}')\n return op\n return wrapper\n\n@metric\ndef fast(x, y):\n time.sleep(0.0012)\n return x + y;\nfast(6,6)\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.6524204015731812,
"alphanum_fraction": 0.6650676131248474,
"avg_line_length": 18.775861740112305,
"blob_id": "234635c0e5f05cd5011301f7ecd409ddd6642121",
"content_id": "6a3911700411dd58a0c75bc0d3d377a98622665e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3177,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 116,
"path": "/面向对象高级编程/使用枚举类.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "#当需要定义常量时,一个办法是用大写变量通过整数定义\n#好处是简单,但是类型为int,并且仍是变量\nJAN = 1\nFEB = 2\nMar = 3\n\n#更好的方法是为这样的枚举类型定义一个class,每个常量都是class的一个唯一实例。Python提供了Enum类\nfrom enum import Enum, unique\n\n#获取Month类型的枚举类,可以直接使用Month.Jan来引用一个常量。或者枚举他的所有成员\nMonth = Enum('Month',('Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', 'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'))\n# 枚举\nfor name, member in Month.__members__.items():\n print(f'{name} => {member}, {member.value}')#value是自动赋给成员的int常量。默认从1开始\n\n#如果需要精确地控制枚举类型,可以从Enum派生出自定义类:\n#枚举类型不可实例化,不可更改\n@unique #unique装饰器可以检查 保证没有重复值\nclass Weekday(Enum):\n Sun = 0\n Mon = 1\n Tue = 2\n Wed = 3\n Thu = 4\n Fri = 5\n Sat = 6\nday1 = Weekday.Mon\nprint(day1)\nprint(Weekday.Tue)\nprint(Weekday['Tue'])\nprint(Weekday.Tue.value)\nprint(day1 == Weekday.Mon)\nprint(Weekday(1))\nfor name, member in Weekday.__members__.items():\n print(f'{name} => {member}')\n\nprint('-----ex-----')\n# ex 把Student的gender属性改造为枚举类型,可以避免使用字符串:\n# @unique\nclass Gender(Enum):\n Male = 0\n Female = 1\n\nclass Student(object):\n def __init__(self, name, gender):\n self.name = name\n\n self.gender = gender\n\nhs = Student('hs',Gender.Male)\nprint(hs.gender)\nprint(type(hs.gender))\n\n\n\n\n\n\nprint('-----------------------------')\n#定义枚举\n\n# @unique # 当用unique装饰后,不能定义相同的成员值\nclass Color(Enum):\n\n red = 1\n green = 2\n # red = 3 #定义枚举时,成员名不允许重复\n blue = 1 #但是成员值允许相同,第二个成员的名称会被视为第一个成员的别名,通过该值获取该成员时,只能获取到第一个成员名\n\nprint(Color.red)\nprint(Color.blue)\nprint(Color.blue is Color.red)\nprint(Color(1))\n\nprint('-----枚举取值-----')\nprint(Color['red'])#通过成员来获取成员\nprint(Color(1))#通过成员值来获取成员\n\nmember = Color.red\n#每个成员都有名称属性和值属性\nprint(member.name)\nprint(member.value)\n\n#如果有值重复的成员,只获取重复的第一个成员\nfor color in Color:\n print(color)\n\n#特殊属性__members__是一个将名称映射到成员的有序字典,也可以通过他完成遍历:\nfor color in Color.__members__.items():\n print(color)\n\nprint('------枚举比较------')\n#枚举的成员可以通过is同一性比较或者通过==等值比较\nprint(Color.red is Color.red)\nprint(Color.red == Color.red)\n\nprint(Color.blue == Color.red)\nprint(Color.red != Color.red)\n\n#不能进行大小比较\n# print(Color.red > Color.red)\n\nprint('-----扩展枚举-----')\nfrom enum import IntEnum\n#IntEnum是Enum的扩展,不同类型的整数枚举也可以互相比较\nclass Shape(IntEnum):\n circle = 1\n square = 2\n\nclass Request(IntEnum):\n post = 1\n get = 2\n\nprint(Shape.circle == 1)\nprint(Shape.circle < 1)\nprint(Shape.circle < Request.post)"
},
{
"alpha_fraction": 0.4895833432674408,
"alphanum_fraction": 0.5034722089767456,
"avg_line_length": 15.29411792755127,
"blob_id": "d2450e4fdd7972d65c6791c9f38ab78398ec9f69",
"content_id": "a739d2bceca3b99410a1729f6e123c55a5866343",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 376,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 17,
"path": "/高级特性/切片操作.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "# 利用切片操作,实现一个trim()函数,去除字符串首尾的空格,注意不要调用str的strip()方法:\ndef trim(s):\n if s[0] == \" \":\n return s[1:]\n\n elif s[-1] == \" \":\n return s[:-1]\n else:\n return s\n print(s)\nprint(trim(' hello'))\n\n#字符串为不可变对象\ns = ' hello world'\n\nprint(s.split(\" \"))\nprint(s)\n \n\n \n"
},
{
"alpha_fraction": 0.6510416865348816,
"alphanum_fraction": 0.6822916865348816,
"avg_line_length": 16.363636016845703,
"blob_id": "34ba209af9ca5e146db49095c64badd77bed1779",
"content_id": "219c5bcd13b8eef5b13f8ac44b85a4fea0b511b2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 316,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 11,
"path": "/函数式编程/高阶函数.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "#变量可以指向函数\nf = abs\nprint(f(-10))\n\n#函数名也是变量,可以通过import builtins; builtins.abs = 10 修改abs对应的值\n\n#传入函数\n#一个函数就可以接收另一个函数作为参数,这种函数就称之为高阶函数。\ndef add(x,y,f):\n return f(x) + f(y)\nprint(add(-5,-6,f))\n\n"
},
{
"alpha_fraction": 0.6856955289840698,
"alphanum_fraction": 0.6975065469741821,
"avg_line_length": 22.090909957885742,
"blob_id": "b066c74566e9b5dd73b8ee9f92124b896633f0e9",
"content_id": "4a3c2307b0aacdd9a08e256330db38b260a6d730",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2136,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 66,
"path": "/进程和线程/ThreadLocal.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "'''\n一个线程使用自己的局部变量比使用全局变量好,因为局部变量只有线程自己能看见,不会影响其他线程,而全局变量的修改必须加锁。\n'''\n#局部变量在函数调用的时候传递起来很麻烦\n'''\ndef process_student(name):\n std = Student(name)\n #std是局部变量,但是每个函数都需要,所以必须传进去\n do_task_1(std)\n do_task_2(std)\n \ndef do_task_1(std):\n do_subtask_1(std)\n do_subtask_2(std)\n\ndef do_task_2(std):\n do_subtask_2(std)\n do_subtask_2(std)\n'''\n\n#用一个全局dict存放所有的student对象,然后以thread自身作为key获得线程对应的student对象\n# global_dict = {}\n#\n# def std_thread(name):\n# std = Student(name)\n# # 将std放到全局变量global_dict中:\n# global_dict[threading.current_thread()] = std\n# do_task_1()\n# do_task_2()\n#\n# def do_task_1():\n# # 不传入std,而是根据当前线程查找\n# std = global_dict[threading.current_thread()]\n#\n#\n# def do_task_2():\n# # 不传入std,而是根据当前线程查找\n# std = global_dict[threading.current_thread()]\n\n#THreadLocal可以不用查找dict,自动完成这个过程\nimport threading\nlocal_school = threading.local()\n\ndef process_student():\n #获取当前线程关联的student\n std = local_school.student\n print(f'hello, {std} (in {threading.current_thread().name})')\n\ndef process_thread(name):\n #绑定ThreadLocal的student\n local_school.student = name\n process_student()\n\nt1 = threading.Thread(target=process_thread, args=('Hs',), name='Thread-A')\nt2 = threading.Thread(target=process_thread, args=('zfy',), name='Thread-B')\nt1.start()\nt2.start()\nt1.join()\nt2.join()\n'''\n全局变量local_school就是一个ThreadLocal对象,每个Thread对它都可以读写student属性,但是互不影响\n\n全局变量local_school是一个dict,可以绑定其他变量。\n\nThreadLocal最常用的地方就是为每个线程绑定一个数据库连接,HTTP请求,用户身份信息等,这样一个线程的所有调用到的处理函数都可以非常方便地访问这些资源\n'''\n"
},
{
"alpha_fraction": 0.7078384757041931,
"alphanum_fraction": 0.724465548992157,
"avg_line_length": 28,
"blob_id": "fe43ac09dcac32264cb2c2c3c05f79f34bae1a2d",
"content_id": "be73334c652a38865653ab95508db7f4c6e4b441",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1544,
"license_type": "no_license",
"max_line_length": 90,
"num_lines": 29,
"path": "/面向对象编程/面向对象编程.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "# 面向对象编程——Object Oriented Programming,简称OOP,是一种程序设计思想。\n# 在Python中,所有数据类型都可以视为对象,当然也可以自定义对象。自定义的对象数据类型就是面向对象中的类(Class)的概念。\n\n#为了表示学生的成绩,面向过程的程序可以用一个dict表示\nstd1 = {'name':'hs','score':100}\nstd1 = {'name':'zyy','score':90}\n\n#处理学生成绩可以通过函数实现,比如打印学生的成绩\ndef print_score(std):\n print(f\"{std['name']} {std['score']}\")\n\n'''\n面向对象的设计思想时,首选思考的不是程序的执行流程,而是student这种数据类型应该被视为一个对象,这个对象拥有name score两个属性,如果打\n印一个学生的成绩,首先必须创建出这个学生对应的对象,然后,给对象发一个print_score消息,让对象自己把自己的数据打印出来。\n\n'''\nclass Student():\n def __init__(self, name, score):\n self.name = name\n self.score = score\n\n def print_score(self):\n print(f'{self.name} {self.score}')\n\n# 面向对象的设计思想是抽象出Class,根据Class创建Instance。\n# # 面向对象的抽象程度又比函数要高,因为一个Class既包含数据,又包含操作数据的方法。\n''' __init__ 方法的主要作用,就是初始化你的属性,这些属性,在上帝初始化你的时候就要赋予给你,比如zhangsan = Person(170,29,50)这时上帝就把你\n# 创造出来了,也就是实例化了你,\n'''\n\n"
},
{
"alpha_fraction": 0.4857351779937744,
"alphanum_fraction": 0.5896123051643372,
"avg_line_length": 18.19718360900879,
"blob_id": "e35da52918fbbaa8079dfbfff960297c0a38a3f6",
"content_id": "ab503a0b2043af2a2db9d3841923849866ab1c12",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2019,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 71,
"path": "/函数式编程/filter.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "#filter()用于过滤序列\n#与map()类似,同样接受一个函数和一个序列。不同的是。在传入的函数依次作用于每个元素之后,会根据返回值的True False来决定保留还是丢弃\n#eg:在一个list中,删除偶数,保留奇数\ndef is_odd(n):\n return n % 2 == 1\nprint(list(filter(is_odd,[1,2,3,4,5])))\n\n#删除空字符串,Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。\n#空字符串的bool值为0\ndef not_empty(s):\n return s and s.strip()\n\nprint(list(filter(not_empty,['a','','b'])))\n\n#用filter求素数,埃氏筛法\n# 首先,列出从2开始的所有自然数,构造一个序列:\n#\n# 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...\n#\n# 取序列的第一个数2,它一定是素数,然后用2把序列的2的倍数筛掉:\n#\n# 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...\n#\n# 取新序列的第一个数3,它一定是素数,然后用3把序列的3的倍数筛掉:\n#\n# 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...\n#\n# 取新序列的第一个数5,然后用5把序列的5的倍数筛掉:\n#\n# 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, ...\n#\n# 不断筛下去,就可以得到所有的素数。\n\n#python实现\n#先构造一个从3开始的奇数数列\ndef _odd_iter():\n n = 1\n while True:\n n += 2\n yield n\n\n\n\n#然后定义一个筛选函数\ndef _not_divisible(n):\n return lambda x : x % n > 0\n\n#最后定义一个生成器,不断返回下一个素数\ndef primes():\n yield 2\n it = _odd_iter()\n while True:\n n = next(it)\n yield n\n it = filter(_not_divisible(n), it)\n\nfor n in primes():\n if n < 100:\n print(n)\n else:\n break\n\n\n\n\n\n\n#回数是指从左向右读和从右向左读都是一样的数.用filter()筛选出回数:\ndef is_palindrome(n):\n return str(n) == str(n)[::-1]\nprint(list(filter(is_palindrome,range(1,100))))\n\n\n\n\n"
},
{
"alpha_fraction": 0.5877862572669983,
"alphanum_fraction": 0.6335877776145935,
"avg_line_length": 26.25,
"blob_id": "aa397761dd3ea4d4746eaf4d491837d882370dd5",
"content_id": "e39542dcfe3a1bac7cec71abd665f11c8f09fe92",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 819,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 24,
"path": "/函数式编程/sorted.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "# Python内置的sorted()函数可以对list进行排序\nprint(sorted([1,4,6,2,6]))\n\n#sorted()函数可以接受一个key函数来实现自定义的排序,eg 按照绝对值大小排序\nprint(sorted([2,5,7,-3,-8,-5], key = abs))\n\n#实现 忽略大小写的排序\nprint(sorted(['boy','apple','Ce'], key=str.lower))\n#反向排序,只需要传入第三个参数\nprint(sorted(['boy','apple','Ce'], key=str.lower,reverse = True))\n\n#ex L = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]\n# 用sorted()对上述列表分别按照名字,成绩排序\nL = [('Bob', 75), ('Adam', 92), ('Bart', 66), ('Lisa', 88)]\nprint(L[1])\n\ndef by_name(t):\n return sorted(t,key = lambda student:student[0])\n\ndef by_score(t):\n return sorted(t,key = lambda student:student[1],reverse=True)\n\nprint(by_name(L))\nprint(by_score(L))\n\n"
},
{
"alpha_fraction": 0.6032934188842773,
"alphanum_fraction": 0.6235029697418213,
"avg_line_length": 17.51388931274414,
"blob_id": "8da90361cce2a9389764074bffd2467bb154d3aa",
"content_id": "a6686e3116f92a822df619e1a2ed6b697002d18e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2270,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 72,
"path": "/函数式编程/返回函数.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "#高阶函数除了可以接受函数作为参数外,还可以把函数作为结果值返回\n\n#可变参数的求和\ndef calc_sum(*args):\n ax = 0\n for n in args:\n ax = ax + n\n return ax\n\n#当不需要立刻求和,而是在后面的代码中根据需要进行计算时,可以不返回求和结果,而是返回求和的函数\ndef lazy_sum(*args):\n def sum():\n ax = 0\n for n in args:\n ax = ax + n\n return ax\n return sum\n\n#调用lazy_sum()时,返回的是秋和函数\n#当调用lazy_sum()时,每次调用都会返回一个新的函数,即使传入相同的参数\na = lazy_sum(1,2,3,4)\nprint(a)\n\n#闭包\n'''\n注意到返回的函数在其定义内部引用了局部变量args,所以,当一个函数返回了一个函数后,\n其内部的局部变量还被新函数引用,所以,闭包用起来简单,实现起来可不容易。\n'''\n#返回的函数没有立刻执行,而是知道调用fn()之后才会执行\n#eg\ndef count():\n fs = []\n for i in range(1,4):\n def f():\n return i*i\n fs.append(f)\n return fs\n\nf1,f2,f3 = count()\n#返回结果都为9\nprint(f1())\nprint(f2())\nprint(f3())\n#原因就在于返回的函数引用了变量i,但它并非立刻执行。等到3个函数都返回时,它们所引用的变量i已经变成了3,因此最终结果为9。\n#返回闭包时牢记一点:返回函数不要引用任何循环变量,或者后续会发生变化的变量\n\n\n#如果一定要引用循环变量,用该函数的参数绑定循环变量当前的值,无论该循环变量后续如何更改,已绑定到函数参数的值不变:\ndef count():\n def f(j):\n def g():\n return j*j\n return g\n fs = []\n for i in range(1, 4):\n fs.append(f(i)) # f(i)立刻被执行,因此i的当前值被传入f()\n return fs\n\n#ex利用闭包返回一个计数器函数,每次调用返回递增整数\ndef createCounter():\n#返回函数不要引用任何循环变量,或者后续会发生变化的变量。这里创建列表,本质上是传递的地址\n l1 = [0]\n def counter():\n l1[0] += 1\n return l1[0]\n return counter\n\nA = createCounter()\nB = createCounter()\nprint(A())\nprint(A())\nprint(A)\n\n\n\n"
},
{
"alpha_fraction": 0.8683953285217285,
"alphanum_fraction": 0.8732876777648926,
"avg_line_length": 30.9375,
"blob_id": "271871b79e7bb1ad6c9dc4cfd5459c0317832506",
"content_id": "9e68919dcd4e0fd77a8421d024d60a38f96225a5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5486,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 64,
"path": "/进程和线程/进程vs线程.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "'''\n要实现多任务,通常我们会设计Master-Worker模式,Master负责分配任务,Worker负责执行任务,因此,多任务环境下,通常是一个Master,多个Worker。\n\n\n如果用多进程实现Master-Worker,主进程就是Master,其他进程就是Worker。\n\n如果用多线程实现Master-Worker,主线程就是Master,其他线程就是Worker。\n\n\n多进程模式最大的优点就是稳定性高,因为一个子进程崩溃了,不会影响主进程和其他子进程。著名的Apache最早就是采用多进程模式。\n多进程模式的缺点是创建进程的代价大。另外,操作系统能同时运行的进程数也是有限的,在内存和CPU的限制下,如果有几千个进程同时运行,操作系统连调度都会成问题。\n\n\n\n多线程模式通常比多进程快一点,但是也快不到哪去,而且,多线程模式致命的缺点就是任何一个线程挂掉都可能直接造成整个进程崩溃,因为所有线程共享进程的内存。\n\n'''\n\n'''\n线程切换\n无论是多进程还是多线程,只要数量一多,效率肯定上不去。\n\n我们打个比方,假设你不幸正在准备中考,每天晚上需要做语文、数学、英语、物理、化学这5科的作业,每项作业耗时1小时。\n\n如果你先花1小时做语文作业,做完了,再花1小时做数学作业,这样,依次全部做完,一共花5小时,这种方式称为单任务模型,或者批处理任务模型。\n\n假设你打算切换到多任务模型,可以先做1分钟语文,再切换到数学作业,做1分钟,再切换到英语,以此类推,只要切换速度足够快,这种方式就和单核CPU执行\n多任务是一样的了,以幼儿园小朋友的眼光来看,你就正在同时写5科作业。\n\n但是,切换作业是有代价的,比如从语文切到数学,要先收拾桌子上的语文书本、钢笔(这叫保存现场),然后,打开数学课本、找出圆规直尺(这叫准备新环境),\n才能开始做数学作业。操作系统在切换进程或者线程时也是一样的,它需要先保存当前执行的现场环境(CPU寄存器状态、内存页等),然后,把新任务的执行环境\n准备好(恢复上次的寄存器状态,切换内存页等),才能开始执行。这个切换过程虽然很快,但是也需要耗费时间。如果有几千个任务同时进行,操作系统可能就主\n要忙着切换任务,根本没有多少时间去执行任务了,这种情况最常见的就是硬盘狂响,点窗口无反应,系统处于假死状态。\n\n多任务一旦多到一个限度,就会消耗掉系统所有的资源,结果效率急剧下降,所有任务都做不好。\n'''\n\n'''\n计算密集型 vs. IO密集型\n是否采用多任务的第二个考虑是任务的类型。我们可以把任务分为计算密集型和IO密集型。\n\n计算密集型任务的特点是要进行大量的计算,消耗CPU资源,比如计算圆周率、对视频进行高清解码等等,全靠CPU的运算能力。这种计算密集型任务虽然也可以用\n多任务完成,但是任务越多,花在任务切换的时间就越多,CPU执行任务的效率就越低,所以,要最高效地利用CPU,计算密集型任务同时进行的数量应当等于CPU\n的核心数\n计算密集型任务由于主要消耗CPU资源,因此,代码运行效率至关重要。Python这样的脚本语言运行效率很低,完全不适合计算密集型任务。对于计算密集\n型任务,最好用C语言编写。\n\n第二种任务的类型是IO密集型,涉及到网络、磁盘IO的任务都是IO密集型任务,这类任务的特点是CPU消耗很少,任务的大部分时间都在等待IO操作完成(因为IO\n的速度远远低于CPU和内存的速度)。对于IO密集型任务,任务越多,CPU效率越高,但也有一个限度。常见的大部分任务都是IO密集型任务,比如Web应用。\nIO密集型任务执行期间,99%的时间都花在IO上,花在CPU上的时间很少,因此,用运行速度极快的C语言替换用Python这样运行速度极低的脚本语言,完全无法提\n升运行效率。对于IO密集型任务,最合适的语言就是开发效率最高(代码量最少)的语言,脚本语言是首选,C语言最差。\n'''\n\n'''\n异步IO\n考虑到CPU和IO之间巨大的速度差异,一个任务在执行的过程中大部分时间都在等待IO操作,单进程单线程模型会导致别的任务无法并行执行,因此,我们才需要\n多进程模型或者多线程模型来支持多任务并发执行。\n\n现代操作系统对IO操作已经做了巨大的改进,最大的特点就是支持异步IO。如果充分利用操作系统提供的异步IO支持,就可以用单进程单线程模型来执行多任务,\n这种全新的模型称为事件驱动模型,Nginx就是支持异步IO的Web服务器,它在单核CPU上采用单进程模型就可以高效地支持多任务。在多核CPU上,可以运行多个\n进程(数量与CPU核心数相同),充分利用多核CPU。由于系统总的进程数量十分有限,因此操作系统调度非常高效。用异步IO编程模型来实现多任务是一个主要的趋势。\n\n对应到Python语言,单线程的异步编程模型称为协程,有了协程的支持,就可以基于事件驱动编写高效的多任务程序。我们会在后面讨论如何编写协程。\n'''\n"
},
{
"alpha_fraction": 0.5669456124305725,
"alphanum_fraction": 0.6066945791244507,
"avg_line_length": 17.153846740722656,
"blob_id": "8e18836b0be0f317a45a4603cf0ca61f26bae1dd",
"content_id": "8afe59dce7efa7619b1de73e279ea90346f919b4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 684,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 26,
"path": "/函数式编程/匿名函数.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "#lambda表示匿名函数。只能有一个表达式,不用写return,返回值便是该表达式的结果\n#eg\nprint(list(map(lambda x: x * x, [1, 2, 3, 4, 5, 6, 7, 8])))\n'''\n这里的lambda实际上就是\ndef f(x):\n return x * x\n \n匿名函数也是一个函数对象,可以吧函数赋值给一个变量,利用变量调用函数\n'''\n# eg\nf = lambda x: x + x\nprint(f(5))\n\n#同样可以吧匿名函数作为返回值返回\ndef build(x, y):\n return lambda: x + x - y + y\n\n# ex 请用匿名函数改造下面的代码\ndef is_odd(n):\n return n % 2 == 1\n\nL = list(filter(is_odd, range(1, 20)))\n\nL_lambda = list(filter(lambda x: x % 2 == 1,range(1, 20)))\nprint(L)\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.4042056202888489,
"alphanum_fraction": 0.4252336323261261,
"avg_line_length": 17.04347801208496,
"blob_id": "db61e866aea6189f2b8b667337ae8e49ccc07080",
"content_id": "aef6fb276168a44237a174295356e80cf0557b44",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 452,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 23,
"path": "/高级特性/迭代.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "#python内置的enumerate函数 \n# for i, value in enumerate(\"abc\"):\n# print(i,value)\n\n#ex\n\ndef findMaxandMin(l):\n if len(l) == 0:\n print(\"请输入一个列表\")\n else:\n min = max = None\n min = max = l[0]\n for i in l:\n if i > max :\n max = i\n if i < min:\n min = i\n t1 = (min,max)\n return t1 \n\n\nl1 = [1,2,3]\nprint(findMaxandMin(l1))\n \n"
},
{
"alpha_fraction": 0.45038166642189026,
"alphanum_fraction": 0.45474374294281006,
"avg_line_length": 30.65517234802246,
"blob_id": "da32a27960d0c77e96fee1fc49c78493efc12f74",
"content_id": "b1a2a5a4796038bb922536ca8660c3e079fcd99f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1155,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 29,
"path": "/IO编程/文件目录ex.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "# 编写一个程序,能在当前目录以及当前目录的所有子目录下查找文件名包含指定字符串的文件,并打印出相对路径。\n# 查找文件名包含s的文件\nimport os\ndef Get_Path(s):\n Q, result = ['.'], [] # Q是目录队列\n while Q: # 队列不为空\n p = Q[0] # 取出队头\n Q = Q[1:] # 弹出队头\n for x in os.listdir(p): # 遍历当前目录下文件\n if os.path.isdir(x): # 如果这个是目录\n Q.append(x) # 加入队列\n elif os.path.isfile(x) and (s in x): # 如果是文件并且文件名包含s\n result.append(os.path.abspath(x)) # 符合要求的文件名\n return result\n\nprint(Get_Path('test'))\nprint(os.listdir('.'))\n\ndef find_file(s):\n Q, result = ['.'], []\n while Q:\n p = Q[0]\n Q = Q[1:]\n for x in os.listdir(p):\n if os.path.isdir():\n Q.append(x)\n elif os.path.isfile(x) and (s in x):\n result.append(os.path.abspath(x))\n return result"
},
{
"alpha_fraction": 0.5732647776603699,
"alphanum_fraction": 0.6066837906837463,
"avg_line_length": 17.5,
"blob_id": "978c28247c24ff6d71fe9834c0fb678e326425ed",
"content_id": "2758682c5cff8ef2a820b85e3212745b44ee4287",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1022,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 42,
"path": "/高级特性/列表生成式.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "#列表生成式即List Comprehensions 是python中内置的 用来创建list生成式\nprint(list(range(1,10)))\n\n\nl1 = [x * x for x in range(1,10)]\nprint(l1)\n\n#仅选出偶数的平方\nl2 = [x * x for x in range(1,5) if x % 2 == 0]\nprint(l2)\n\n#两层循环\nl3 = [m + n for m in 'huang' for n in 'shang']\nprint(l3)\n\nimport os\n#listdir 列出文件和目录\nprint([d for d in os.listdir('.')])\n\n#同时迭代字典中的key和value\nd = {\n 'one' : '1',\n 'two' : '2',\n 'three' : '3'\n }\nfor k, v in d.items():\n print(f'{k} = {v}')\n\n#使用两个变量生成list\nprint([k + '=' + v for k,v in d.items()])\n\n#所有字符串变小写\nL = ['HUANG','SHANG']\nprint([s.lower() for s in L])\n\n#可见,在一个列表生成式中,for前面的if ... else是表达式,而for后面的if是过滤条件,不能带else。\n\n#ex 修改列表生成式,通过添加if语句保证列表生成式正确执行\nL1 = ['Hello', 'World', 18, 'Apple', None]\nL2 = [s.lower() for s in L1 if isinstance(s,str)]\nprint(L1)\nprint(L2)\n\n"
},
{
"alpha_fraction": 0.8582317233085632,
"alphanum_fraction": 0.8597561120986938,
"avg_line_length": 24.269229888916016,
"blob_id": "6f29930259610471daa476cd118cdfbc70115644",
"content_id": "62576602de9762d836d3c97ee0912cac999e56bb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1838,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 26,
"path": "/进程和线程/进程和线程.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "'''\n对于操作系统来说,一个任务就是一个进程(Process),比如打开一个浏览器就是启动一个浏览器进程,打开一个记事本就启动了一个记事本进程,打开两个记\n事本就启动了两个记事本进程,打开一个Word就启动了一个Word进程。\n\n有些进程还不止同时干一件事,比如Word,它可以同时进行打字、拼写检查、打印等事情。在一个进程内部,要同时干多件事,就需要同时运行多个“子任务”,\n我们把进程内的这些“子任务”称为线程(Thread)。\n\n由于每个进程至少要干一件事,所以,一个进程至少有一个线程。当然,像Word这种复杂的进程可以有多个线程,多个线程可以同时执行,多线程的执行方式\n和多进程是一样的,也是由操作系统在多个线程之间快速切换,让每个线程都短暂地交替运行,看起来就像同时执行一样。当然,真正地同时执行多线程需要\n多核CPU才可能实现。\n\n执行多任务的解决方案:\n一种是启动多个进程,每个进程虽然只有一个线程,但多个进程可以一块执行多个任务。\n\n还有一种方法是启动一个进程,在一个进程内启动多个线程,这样,多个线程也可以一块执行多个任务。\n\n当然还有第三种方法,就是启动多个进程,每个进程再启动多个线程,这样同时执行的任务就更多了,当然这种模型更复杂,实际很少采用。\n\n总结一下就是,多任务的实现有3种方式:\n\n多进程模式;\n多线程模式;\n多进程+多线程模式。\n\n线程是最小的执行单元,而进程由至少一个线程组成。如何调度进程和线程,完全由操作系统决定,程序自己不能决定什么时候执行,执行多长时间。\n'''"
},
{
"alpha_fraction": 0.6569269299507141,
"alphanum_fraction": 0.671032726764679,
"avg_line_length": 20.139785766601562,
"blob_id": "8fc881805ca8ae704bb7af7bea602df8e001a0f7",
"content_id": "a8400ac8ac16a31898d73e094222285601cc18fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2769,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 93,
"path": "/面向对象编程/获取对象信息.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "from 继承和多态 import *\n#判断对象类型,使用type()函数\nprint(type(123))\n\n#如果一个变量指向函数或者类,也可用type()判断\nprint(type(max))\n\n#type返回值为type类\nprint(type(type(123)))\n\n#判断一个对象是否为函数时,使用types模块中定义的常量\nimport types\ndef fn():\n pass\n\n\nprint(type(fn))\nprint(type(fn) == types.FunctionType)\nprint(type(abs) == types.BuiltinFunctionType)\nprint(type(lambda x :x) == types.LambdaType)\nprint(type((x for x in range(10))) == types.GeneratorType)\nprint('------------------------')\n\n\n# 对于class的继承关系来说,使用type()就很不方便。我们要判断class的类型,可以使用isinstance()函数。\na = Animal()\nb = Dog()\nc = Husky()\nprint(isinstance(a,Animal))\nprint(isinstance(b,Animal))\nprint(isinstance(c,Animal))\nprint('=*******=')\nprint(isinstance(b,Husky))\n#也可用isinstance()实现type()的功能,总是优先使用isinstance()\nprint(isinstance('a',str))\nprint(isinstance(123,int))\nprint('-----------')\n\n#也可以判断一个变量是否是某些类型中的一种\nprint(isinstance([1, 2, 4],(list, tuple)))\nprint(isinstance((1, 2, 4),(list, tuple)))\n\n#如果要获得一个对象的所有属性和方法,可以使用dir()函数,返回一个包含字符串的list\nprint(dir('abc'))\n\n# 类似__xxx__的属性和方法在Python中都是有特殊用途的\n#下述两种方法实现同样的功能\nprint(len('abc'))\nprint('abc'.__len__())\n\n#在自己编写类的时候,如果想用类似len(obj)的话,可以自己写一个__len__()方法\nclass MyDog():\n def __len__(self):\n return 20\n\ndog = MyDog()\nprint(len(dog))\n\n# 配合getattr()、setattr()以及hasattr(),直接操作一个对象的状态\nclass MyObject():\n def __init__(self):\n self.x = 9\n def power(self):\n return self.x * self.x\n\nobj = MyObject()\n\nprint(hasattr(obj,'x')) #有属性'x'吗\nprint(obj.x)\nprint(hasattr(obj,'y')) #有属性'y'吗\nsetattr(obj,'y',20) #设置一个属性'y'\nprint(hasattr(obj,'y'))\nprint(getattr(obj,'y'))\n\n# 可以传入一个default参数,如果属性不存在,就返回默认值:\nprint(getattr(obj, 'z', 404)) # 获取属性'z',如果不存在,返回默认值404\n\n#也可以获得对象的方法\nprint(hasattr(obj,'power'))\nprint(getattr(obj,'power'))\n\nfn = getattr(obj,'power') #获取属性power 并赋值到变量fn\nprint(fn()) #此时的fn()功能与obj.power()是一样的\n\n\n'''\n假设我们希望从文件流fp中读取图像,我们首先要判断该fp对象是否存在read方法,如果存在,则该对象是一个流,如果不存在,则无法读取。\nhasattr()就派上了用场。\n'''\ndef readImage(fp):\n if hasattr(fp, 'read'):\n return readData(fp)\n return None\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.6725146174430847,
"alphanum_fraction": 0.7037037014961243,
"avg_line_length": 15.896552085876465,
"blob_id": "23388bcbcc551e2c0b814a6e066ce647f9b4f272",
"content_id": "bdecc1b9506c6c27df34a3af231796ded0df7416",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1071,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 29,
"path": "/错误,调试,测试/单元测试.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "#测试驱动开发(TDD:Test-Driven Development)。单元测试是用来对一个模块,一个函数或者一个类来进行正确性检验的测试工作\n'''\n比如对函数abs(),我们可以编写出以下几个测试用例:\n\n输入正数,比如1、1.2、0.99,期待返回值与输入相同;\n\n输入负数,比如-1、-1.2、-0.99,期待返回值与输入相反;\n\n输入0,期待返回0;\n\n输入非数值类型,比如None、[]、{},期待抛出TypeError。\n\n把上面的测试用例放到一个测试模块里,就是一个完整的单元测试。\n'''\n\n'''\n单元测试通过后有什么意义呢?如果我们对abs()函数代码做了修改,只需要再跑一遍单元测试,如果通过,说明我们的修改不会对abs()函数原有的行为造成影\n\n响,如果测试不通过,说明我们的修改与原有行为不一致,要么修改代码,要么修改测试。\n'''\n\n\n\n# d = Dict(a = 1, b = 2)\n# print(d['a'])\n# print(d.a)\n\n#引入自带的unittest模块,编写mydict_test.py\nimport unittest\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.6641883254051208,
"alphanum_fraction": 0.6691449880599976,
"avg_line_length": 24.1875,
"blob_id": "870eff49fb72c954a75bf9dc165e52e6120ee12a",
"content_id": "e058c92f88435140e0c2ccd75f93e5b58fb6537d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1193,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 32,
"path": "/面向对象编程/实例属性和类属性.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "#由于python是动态语言,根据类创建的实例可以任意绑定属性\n# class Student():\n# def __init__(self, name):\n# self.name = name\n#\n# s = Student('hs')\n# s.score = 90\n\n# class Student(object):\n# name = 'Student'\n\n# s = Student() # 创建实例s\n# print(s.name) # 打印name属性,因为实例并没有name属性,所以会继续查找class的name属性\n# print(Student.name) # 打印类的name属性\n# s.name = 'Michael' # 给实例绑定name属性\n# print(s.name) # 由于实例属性优先级比类属性高,因此,它会屏蔽掉类的name属性\n# print(Student.name) # 但是类属性并未消失,用Student.name仍然可以访问\n# del s.name # 如果删除实例的name属性\n# print(s.name) # 再次调用s.name,由于实例的name属性没有找到,类的name属性就显示出来了\n\n#ex为了统计学生人数,可以给Student类增加一个类属性,每创建一个实例,该属性自动增加:\nclass Student(object):\n count = 0\n def __init__(self, name):\n self.name = name\n Student.count += 1 #调用类下的属性\n print('运行了')\n\n\nhs = Student('hs')\nzfy = Student('zfy')\nprint(Student.count)\n\n"
},
{
"alpha_fraction": 0.7054380774497986,
"alphanum_fraction": 0.7160120606422424,
"avg_line_length": 21.689655303955078,
"blob_id": "89ebd4c352173098397f6523354ac5588e7eadc1",
"content_id": "981e7b61ef93f4f11d5ad8fb974720bfab3a0be6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 952,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 29,
"path": "/IO编程/StringIO和BytesIO.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "'''\n数据读写不一定是文件,也可以在内存中读写。stringIo顾名思义就是在内存中读写str\n需要创建一个stringIO,像文件一样写入\n'''\nfrom io import StringIO\nf = StringIO()\nprint(f.write('hello'))\nprint(f.write(' '))\nprint(f.write('world'))\n\nprint(f.getvalue()) #getvalue()方法用于获得写入后的str\n\n#要读取StringIO,可以用一个str初始化StringIO,然后,像读文件一样读取:\nf = StringIO('Hello!\\nHi\\nGoodBye!')\nwhile True:\n s = f.readline()\n if s == '':\n break\n print(s.strip())\n\n#BytesIO,StringIO操作的只能是str,如果要操作二进制数据,就需要使用BytesIO\nfrom io import BytesIO\nf = BytesIO()\nprint(f.write('中文'.encode('utf-8'))) #这里写入的不是str,而是经过UTF-8编码的bytes\nprint(f.getvalue())\n\n#与StringIO类似,可以用一个bytes初始化BytesIO,然后像读文件一样读取:\nf = BytesIO(b'82385')\nprint(f.read())\n\n\n\n\n"
},
{
"alpha_fraction": 0.4598408043384552,
"alphanum_fraction": 0.524240255355835,
"avg_line_length": 21.983333587646484,
"blob_id": "18f2c02789954bcd9903df0fafd383484a27b145",
"content_id": "c8921a8554dccc98a9b66d6e9063a55cb51b2f1b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3432,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 120,
"path": "/函数式编程/mapreduce.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "#map()函数接收两个参数,一个是函数,一个是Iterable,map将传入的函数依次作用到序列的每个元素,并把结果作为新的Iterator返回。\ndef f(x):\n return x * x\n\nr = map(f, [1, 2, 3, 4, 5, 6, 7, 8])\n#查看一个map对象需要list方法\n# 由于结果r是一个Iterator,Iterator是惰性序列,因此通过list()函数让它把整个序列都计算出来并返回一个list。\nprint(list(r))\n\n#map作为高阶函数,将运算规则进行抽象。\n\n\n#将list中的数字全部转化为字符串\nprint(list(map(str,[1, 2, 3, 4])))\n\n#reduce把一个函数作用在一个序列[x1, x2, x3, ...]上,这个函数必须接收两个参数,reduce把结果继续和序列的下一个元素做累积计算。\n\n#将序列变成整数\nfrom functools import reduce\ndef fn(x,y):\n return x * 10 + y\n\nprint(reduce(fn,[1, 2, 4, 5]))\n\n#将str转化为int\ndef strtoint(s):\n def fn(x,y):\n return x * 10 + y\n\n def chartonum(s):\n num = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9\n\n }\n return num[s]\n\n return reduce(fn,map(chartonum,s))\n\nprint(strtoint('12345'))\n\n#lambda函数简化\nDIGITS = {'0':0,'1':1,'2':2,'3':3,'4':4,'5':5,'6':6,'7':7,'8':8,'9':9\n\n }\ndef char2num(s):\n return DIGITS[s]\ndef str2int(s):\n return reduce(lambda x, y: x * 10 + y, map(char2num(), s))\n\n#ex:利用map()函数,把用户输入的不规范的英文名字,变为首字母大写,其他小写的规范名字。输入:['adam', 'LISA', 'barT'],输出:['Adam', 'Lisa', 'Bart']:\ndef normalize(name):\n namelow = name[1:].lower()\n nameupp = name[0].upper()\n return nameupp + namelow\nprint(\"-测试结果-\")\nL1 = ['adam', 'LISA', 'barT']\nL2 = list(map(normalize, L1))\nprint(L2)\n\n#ex:Python提供的sum()函数可以接受一个list并求和,请编写一个prod()函数,可以接受一个list并利用reduce()求积:\ndef prod(L):\n\n def mutiply(x, y):\n return x * y\n\n return reduce(mutiply,L)\n\nprint(\"--测试结果--\")\nprint('3 * 5 * 7 * 9 =', prod([3, 5, 7, 9]))\n\n#ex:利用map和reduce编写一个str2float函数,把字符串'123.456'转换成浮点数123.456:\n# 标答\n# CHAR_TO_FLOAT = {\n# '0': 0,\n# '1': 1,\n# '2': 2,\n# '3': 3,\n# '4': 4,\n# '5': 5,\n# '6': 6,\n# '7': 7,\n# '8': 8,\n# '9': 9,\n# '.': -1\n# }\n# # def str2float(s):\n# # nums = map(lambda ch: CHAR_TO_FLOAT[ch], s)\n# # point = 0\n# # def to_float(f, n):\n# # nonlocal point\n# # if n == -1:\n# # point = 1\n# # return f\n# # if point == 0:\n# # return f * 10 + n\n# # else:\n# # point = point * 10\n# # return f + n / point\n# # return reduce(to_float, nums, 0.0)\n\n# 网答\ndef str2float(s):\n#去除引号\n def k(s):\n digits = {'.': '.', '0': 0, '1': 1, '2': 2, '3': 3, '4': 4, '5': 5, '6': 6, '7': 7, '8': 8, '9': 9}\n return digits[s]\n s = list(s)\n result = list(map(k, s))\n#确定小数点的位置\n n = result.index('.')\n#确定小数点前的整数\n def add1(x, y):\n return x * 10 + y\n float_int = reduce(add1, result[:n])\n m = n +1\n#确定小数点后的值\n def add2(q, p):\n return q * 10 + p\n float_flo = 0.1 ** len(result[m:]) * reduce(add2, result[m:])\n return (float_int + float_flo)\nprint('str2float(\\'123.456\\') =', str2float('123.456'))\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.7146610617637634,
"alphanum_fraction": 0.7178139686584473,
"avg_line_length": 23.855262756347656,
"blob_id": "188035a695dc4ed8141ac20f425cbd1b53a8ed91",
"content_id": "8a48f4f9e4b68e4a6794dcd30ff24a456cfb35b8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3523,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 76,
"path": "/IO编程/文件读写.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "#使用open()函数,传入文件名和标示符\n# f = open('test.txt', 'r')\n#文件打开成功后可以调用read()方法 一次读取文件的全部内容。Python把内容读到内存,用一个str对象表示\n# print(f.read())\n\n#文件使用完毕后必须关闭,因为文件对象会占用操作系统的资源。操作系统同一时间能打开的文件数量也是有限的\n# f.close()\n\n#文件读写时可能产生IOError,出错后后面的f.close()就不会调用。所以为了无论是否出错,都能正确地关闭文件,我们可以使用try...finally来实现\n# try:\n# f = open('test.txt', 'r')\n# print(f.read())\n# finally:\n# if f:\n# f.close()\n\n\n#为了简便,python引入with语句,自动调用close()方法:\nwith open('test.txt', 'r') as f:\n print(f.read())\n\n'''\n调用read()会一次性读取文件的全部内容,如果文件有10G,内存就爆了,所以,要保险起见,可以反复调用read(size)方法,每次最多读取size个字节的内容。\n另外,调用readline()可以每次读取一行内容,调用readlines()一次读取所有内容并按行返回list。因此,要根据需要决定怎么调用。\n如果文件很小,read()一次性读取最方便;如果不能确定文件大小,反复调用read(size)比较保险;如果是配置文件,调用readlines()最方便:\n'''\nfor line in f.readlines():\n print(line.strip()) #将末尾地\\n删掉\n\n#file-like Object\n'''\n像open()函数返回的这种有个read()方法的对象,在Python中统称为file-like Object。除了file外,还可以是内存的字节流,网络流,自定义流等等。\nfile-like Object不要求从特定类继承,只要写个read()方法就行。\n\nStringIO就是在内存中创建的file-like Object,常用作临时缓冲。\n'''\n\n\n'''\n#二进制文件\n# 要读取二进制文件,用'rb'模式打开即可\n# eg:f1 = open('test1.jpg', 'rb')\n# f1.read()\n'''\n\n\n\n'''\n字符编码\n要读取非UTF-8编码的文本文件,需要给open()函数传入encoding参数,例如,读取GBK编码的文件:\nf = open('/Users/michael/gbk.txt', 'r', encoding='gbk')\nf.read()\n \n遇到有些编码不规范的文件,你可能会遇到UnicodeDecodeError,因为在文本文件中可能夹杂了一些非法编码的字符。遇到这种情况,open()函数还接收一\n个errors参数,表示如果遇到编码错误后如何处理。最简单的方式是直接忽略:\nf = open('/Users/michael/gbk.txt', 'r', encoding='gbk', errors='ignore')\n '''\n\n\n\n'''\n写文件\n写文件和读文件是一样的,唯一区别是调用open()函数时,传入标识符'w'或者'wb'表示写文本文件或写二进制文件:\n>>> f = open('/Users/michael/test.txt', 'w')\n>>> f.write('Hello, world!')\n>>> f.close()\n\n可以反复调用write()来写入文件,但是务必要调用f.close()来关闭文件\n当我们写文件时,操作系统往往不会立刻把数据写入磁盘,而是放到内存缓存起来,空闲的时候再慢慢写入。只有调用close()方法时,操作系统才保证把没有写入\n的数据全部写入磁盘。忘记调用close()的后果是数据可能只写了一部分到磁盘,剩下的丢失了。所以,还是用with语句来得保险:\nwith open('/Users/michael/test.txt', 'w') as f:\n f.write('Hello, world!')\n \n \n以'w'模式写入文件时,如果文件已存在,会直接覆盖(相当于删掉后新写入一个文件)。可以传入'a'以追加(append)模式写入。\n'''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.7144522070884705,
"alphanum_fraction": 0.7156177163124084,
"avg_line_length": 14.867924690246582,
"blob_id": "b5e6232eeaa66ac60b2aa2455ccb1bd0f42932b8",
"content_id": "0d362992075889af83bb7cdc066784323172aafc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1402,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 53,
"path": "/面向对象高级编程/多重继承.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "'''\n继承是面向对象编程的一个重要的方式,因为通过继承,子类就可以扩展父类的功能。\n\n回忆一下Animal类层次的设计,假设我们要实现以下4种动物:\n\nDog - 狗狗;\nBat - 蝙蝠;\nParrot - 鹦鹉;\nOstrich - 鸵鸟。\n'''\n#采用多重继承,主要类层次按照哺乳类和鸟类设计\nclass Animal():\n pass\n\n#大类\nclass Mammal(Animal): #哺乳类\n pass\n\nclass Bird(Animal): #鸟类\n pass\n\n#各种动物\nclass Dog(Mammal, RunnableMixIn):\n\n pass\n\nclass Bat(Mammal, FlyableMinIn):\n pass\n\nclass Parrot(Bird, FlyableMinIn):\n pass\n\nclass Ostrich(Bird, FlyableMinIn):\n pass\n\n#给动物加上Runnable Flyable功能\nclass RunnableMixIn():\n def run(self):\n print('running...')\n\nclass FlyableMixIn():\n def fly(self):\n print('flying...')\n\n#通过多重继承,一个子类就可以同时获得多个父类的所有功能\n\n#Mixln\n'''\n通常,主线都是单一继承下来的,需要额外功能,通过多重继承可以实现。这种设计称为MixIn\n为了更好的看出继承关系,可以把Runnable和Flyable改为RunnableMixIn和FlyableMixIn\nMixIn的目的就是给一个类增加多个功能,在设计类的时候,优先考虑通过多重继承来组合多个MixIn的功能。\nMixIn只是相当于一个标记,区分出继承的主次,目的是提高代码的可读性\n'''\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.7173637747764587,
"alphanum_fraction": 0.7279256582260132,
"avg_line_length": 25,
"blob_id": "50434b101d16ebdfe8a27cead1b9f1f7a2148a01",
"content_id": "50ef542a4c57bbadd584c07752cd22202d354861",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3933,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 91,
"path": "/IO编程/序列化.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "#在程序运行的过程中,所有的变量都是在内存中,比如定义一个dict:\n\n\n'''\n变量从内存中变成可存储或传输的过程称之为序列化,在Python中叫pickling,在其他语言中也被称之为serialization,marshalling,flattening等等,都是一个意思。\n\n序列化之后,就可以把序列化后的内容写入磁盘,或者通过网络传输到别的机器上。\n\n反过来,把变量内容从序列化的对象重新读到内存里称之为反序列化,即unpickling。\n\nPython提供了pickle模块来实现序列化。\n'''\n# import pickle\n# d = dict(name = 'hs', age = 20, score = 100)\n# print(pickle.dumps(d))\n\n#pickle.dumps()可以把任意对象序列化称为一个bytes,然后就可以把这个bytes写入文件。或者用另一个方法pickle.dump()直接把对象序列化后写入一个\n# file-like object\n# f = open('test.txt','wb') #此时的文件内容为乱码。这些就是python保存的对象内部信息\n# pickle.dump(d,f)\n# f.close()\n\n'''\n当我们要把对象从磁盘读到内存时,可以先把内容读到一个bytes,然后用pickle.loads()方法反序列化出对象,也可以直接用pickle.load()方法从一个\nfile-like Object中直接反序列化出对象。我们打开另一个Python命令行来反序列化刚才保存的对象:\n'''\n# f = open('test.txt','rb') #此时的文件内容为乱码。这些就是python保存的对象内部信息\n# d = pickle.load(f)\n# f.close()\n# print(d)\n\n#json\n'''\n如果我们要在不同的编程语言之间传递对象,就必须把对象序列化为标准格式,比如XML,但更好的方法是序列化为JSON,因为JSON表示出来就是一个字符串,\n可以被所有语言读取,也可以方便地存储到磁盘或者通过网络传输。JSON不仅是标准格式,并且比XML更快,而且可以直接在Web页面中读取,非常方便。\nJSON表示的对象就是标准的JavaScript语言的对象,JSON和Python内置的数据类型对应如下:\n'''\n\n'''\nJSON类型\t Python类型\n{}\t dict\n[]\t list\n\"string\"\t str\n1234.56\t int或float\ntrue/false\tTrue/False`\nnull\t None\n'''\nimport json\nd = dict(name = 'Bob', age = 20)\nprint(json.dumps(d)) #dumps()方法返回一个str。dump()方法可以直接把json写入一个file-like Object\n\n#json反序列化为python对象\njson_str = '{\"name\": \"Bob\", \"age\": 20}'\nprint(json.loads(json_str))\n\n'''\nJSON进阶\nPython的dict对象可以直接序列化为JSON的{},不过,很多时候,我们更喜欢用class表示对象,比如定义Student类,然后序列化:\n'''\nclass Student():\n def __init__(self, name, age, score):\n self.name = name\n self.age = age\n self.score = score\n\n\n\n# 改变可选参数,定制json序列化。为Student写一个转换函数,再将函数传进去即可\ndef student2dict(s):\n return {\n 'name': s.name,\n 'age' : s.age,\n 'score' : s.score\n }\n\n\na = Student('hs', 20, 100)\nprint(json.dumps(a, default=student2dict)) #程序运行报错,因为Student对象不是一个可序列化为json的对象\n\n#上述方法不通用,如果换为其他实例便不会起作用。可以进行如下操作\n# print(json.dumps(s, default=lambda obj: obj.__dict__)) #将任意class的实例变为dict\n\n\n# JSON反序列化为一个Student对象实例,loads()方法首先转换出一个dict对象,然后,我们传入的object_hook函数负责把dict转换为Student实例:\ndef dict2student(d):\n return Student(d['name'], d['age'], d['score'])\n\n# ex对中文进行JSON序列化时,json.dumps()提供了一个ensure_ascii参数,观察该参数对结果的影响:\nobj = dict(name='小明', age=20)\n# 如果ensure_ascii为True(默认值),则输出保证将所有输入的非ASCII字符转义。如果确保ensure_ascii为False,这些字符将原样输出。\nprint(json.dumps(obj, ensure_ascii=False))\n\n"
},
{
"alpha_fraction": 0.6785714030265808,
"alphanum_fraction": 0.6889401078224182,
"avg_line_length": 20.725000381469727,
"blob_id": "0c067a40dbe16d95ad846d915a94b98b1f9fbd3e",
"content_id": "8fc10d72eefb7a8fe11d436bcf22d7830b855c38",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1568,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 40,
"path": "/面向对象编程/hello.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\n#前两行为标准注释。第一行注释可以让这个文件直接在unix、linux、mac上运行,第二个注释表示py文件\n# 本身使用标准utf-8编码;\n\n#hello 模块\n#文档注释,任何模块代码的第一个字符串都被视为模块的文档注释;\n\n'a test module'\n\n#使用__author__变量将作者写进去\n__author__ = 'Coach huang'\n\n\nimport sys\n\n#argv至少有一个元素,因为第一个参数永远是该.py文件的名称\ndef test():\n args = sys.argv\n if len(args) == 1:\n print('hello world')\n elif len(args) == 2:\n print(f\"hello {args[1]}\")\n else:\n print(\"Too many arguments!\")\n\nif __name__=='__main__':\n test()\n# 当我们在命令行运行hello模块文件时,Python解释器把一个特殊变量__name__置为__main__,而如果在其他地方导入该hello模块时,if判断将失败,\n# 因此,这种if测试可以让一个模块通过命令行运行时执行一些额外的代码,最常见的就是运行测试。\n'''\n正常的函数和变量名是公开的(public),可以被直接引用,比如:abc,x123,PI等;\n\n似__xxx__这样的变量是特殊变量,可以被直接引用,但是有特殊用途,比如上面的__author__,__name__就是特殊变量,hello模块定义的文档注释也\n可以用特殊变量__doc__访问,我们自己的变量一般不要用这种变量名;\n\n类似_xxx和__xxx这样的函数或变量就是非公开的(private),不应该被直接引用,比如_abc,__abc等;\n\n'''"
},
{
"alpha_fraction": 0.6711195707321167,
"alphanum_fraction": 0.6733460426330566,
"avg_line_length": 26.09482765197754,
"blob_id": "8d568013fed9fc0f5feadee272e1e74e831f8023",
"content_id": "abc225912b1441ba852348cca04b62c3d81d81ef",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4714,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 116,
"path": "/进程和线程/多进程.py",
"repo_name": "zongjie233/liaoxuefengPython3",
"src_encoding": "UTF-8",
"text": "'''\nUnix/Linux操作系统提供了一个fork()系统调用,它非常特殊。普通的函数调用,调用一次,返回一次,但是fork()调用一次,返回两次,因为操作系统自动\n把当前进程(称为父进程)复制了一份(称为子进程),然后,分别在父进程和子进程内返回。\n\n子进程永远返回0,而父进程返回子进程的ID。这样做的理由是,一个父进程可以fork出很多子进程,所以,父进程要记下每个子进程的ID,而子进程只需要调用\ngetppid()就可以拿到父进程的ID。\n'''\n\nimport os\n# print(f'Process {os.getpid()} start')\n\n# pid = os.fork() #只有Unix Linux Mac可运行\n\n#multiprocessing\n#multiprocessing模块提供了一个Process类来代表一个进程对象。\n# from multiprocessing import Process\n# import os\n#\n# #子进程要执行的代码\n# def run_proc(name):\n# print(f'Run child process {name} ({os.getpid()})')\n#\n# if __name__ == '__main__':\n# print(f'Parent process {os.getpid()}')\n# p = Process(target=run_proc, args = ('test',)) #创建实例\n# print('Child process will start.')\n# p.start()\n# p.join() #join方法可以等待子进程结束后再继续往下运行,通常用于进程间的同步\n# print('Child process end.')\n\n#启动大量的子进程时,可以用进程池的方式批量创建子进程\nfrom multiprocessing import Pool\nimport os, time, random\n\n'''\napply是阻塞式的。\n\n首先主进程开始运行,碰到子进程,操作系统切换到子进程,等待子进程运行结束后,在切换到另外一个子进程,直到所有子进程运行完毕。然后在切换到主进程,运行剩余的部分。\n\napply_async是异步非阻塞式的。\n\n首先主进程开始运行,碰到子进程后,主进程说:让我先运行个够,等到操作系统进行进程切换的时候,在交给子进程运行。以为我们的程序太短,然而还没等到操作系统进行进程切换,主进程就运行完毕了。\n\n想要子进程执行,就告诉主进程:你等着所有子进程执行完毕后,在运行剩余部分。\n\n'''\n# def long_time_task(name):\n# print(f'Run task {name} ({os.getpid()})')\n# start = time.time()\n# time.sleep(random.random() * 3)\n# end = time.time()\n# print(f'Task {name} runs {(end - start)}')\n#\n# if __name__ == '__main__':\n# print(f'Parent process {os.getpid()}')\n# p = Pool(15)\n# for i in range(15):\n# p.apply_async(long_time_task, args=(i,)) #apply_async为异步非阻塞式的\n# print('Waiting for all subprocesses done...')\n# #对Pool对象调用join()方法会等待所有子进程执行完毕,调用join()之前必须先调用close(),调用close()之后就不能继续添加新的Process了。\n# p.close()\n# p.join()\n# print('All subprocesses done.')\n\n\n'''\n很多时候,子进程并不是自身,而是一个外部进程。我们创建了子进程后,还需要控制子进程的输入和输出。\n\nsubprocess模块可以让我们非常方便地启动一个子进程,然后控制其输入和输出。\n'''\n# import subprocess\n# print('$ nslookup www.baidu.com')\n# r = subprocess.call(['nslookup', 'www.baidu.com'])\n# print(f'Exit code: {r}')\n\n#如果子进程还需要输入,则可以通过communicate()方法输入:\n# print('$ nslookup')\n# p = subprocess.Popen(['nslookup'], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE)\n# output, err = p.communicate(b'set q=mx\\npython.org\\nexit\\n')\n# print(output.decode('utf-8'))\n# print('Exit code:', p.returncode)\n\n'''\nProcess之间肯定是需要通信的,操作系统提供了很多机制来实现进程间的通信。Python的multiprocessing模块包装了底层的机制,提供了Queue、Pipes等多种方式来交换数据。\n\n我们以Queue为例,在父进程中创建两个子进程,一个往Queue里写数据,一个从Queue里读数据:\n'''\nfrom multiprocessing import Process, Queue\nimport os, time, random\n\ndef write(q):\n print(f'Process to write: {os.getpid()}')\n for value in ['A', 'B', 'C']:\n print(f'Put {value} to queue...')\n q.put(value)\n time.sleep(random.random())\n\ndef read(q):\n print(f'Process to read: {os.getpid()}')\n while True:\n value = q.get(True)\n print(f'Get {value} from quene.')\n\nif __name__ == '__main__':\n #父进程创建Queue,并传给各个子进程\n q = Queue()\n pw = Process(target=write, args=(q,))\n pr = Process(target=read, args=(q,))\n #启动子进程pw,写入:\n pw.start()\n #启动子进程pr, 读取:\n pr.start()\n #等待pw结束\n pw.join()\n #pr为死循环,只能强行停止\n pr.terminate()\n\n"
}
] | 41 |
rhiggins2308/MultiParadigm-Programming | https://github.com/rhiggins2308/MultiParadigm-Programming | cd8bea0178117f19893d71fd3b5648f56f7bdbe5 | b24e088cfcff5d0b4a88eb9993e7e3a4897bc1b4 | 15a352cebe7b377577ed83b7813d6f5bd2c34f0d | refs/heads/master | 2020-09-05T08:23:18.704110 | 2019-12-11T10:28:27 | 2019-12-11T10:28:27 | 220,039,991 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5419977903366089,
"alphanum_fraction": 0.5497896075248718,
"avg_line_length": 28.918415069580078,
"blob_id": "4ff132b373bf79f2554fab958666f393b3010403",
"content_id": "4e2dd9593d2da6218f7465055ad3d0b7f155a983",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 12856,
"license_type": "permissive",
"max_line_length": 203,
"num_lines": 429,
"path": "/Assignment 1/C/shop.c",
"repo_name": "rhiggins2308/MultiParadigm-Programming",
"src_encoding": "UTF-8",
"text": "// |----------------------------|\n// |---- 1. Import Packages ----|\n// |----------------------------|\n#include <stdio.h>\n#include <string.h>\n#include <stdlib.h>\n\n// |-----------------------------|\n// |----- 2. Model Entities -----|\n// |-----------------------------|\n\n// 2a - Product Entity\nstruct Product{\n char* name;\n double price;\n};\n\n// 2b - ProductStock Entity\nstruct ProductStock{\n struct Product product;\n int quantity;\n};\n\n// 2c - Customer Entity\nstruct Customer{\n char* name;\n double budget;\n struct ProductStock shoppingList[10];\n int index;\n};\n\n// 2d - Shop Entity\nstruct Shop{\n double cash;\n struct ProductStock stock[20];\n int index;\n};\n\n// |-----------------------------|\n// |----- 3. Define Methods -----|\n// |-----------------------------|\n\n// 3a. Create the Shop entity from shop.csv file\n// - Contains opening cash balance\n// - Contains stocked products\n// - Contains price for each product\n// - Contains stock level for each product\nstruct Shop createAndStockShop()\n{\n FILE * fp;\n char * line = NULL;\n size_t len = 0;\n ssize_t read;\n\n // open stock.csv file to read values\n fp = fopen(\"stock.csv\", \"r\");\n if (fp == NULL ){\n exit(EXIT_FAILURE);\n }\n \n // parse first line of stock.csv, to import opening cash value\n getline(&line, &len, fp);\n double cashInShop = atof(line);\n struct Shop shop = {cashInShop};\n\n // parse remaining line items in stock.csv file\n // store in Shop struct as Productstock items\n // - Description (Product)\n // - Cost (Product)\n // - Stock (ProductStock)\n while ((read = getline(&line, &len, fp)) != -1){\n char *n = strtok(line, \",\");\n char *p = strtok(NULL, \",\");\n char *q = strtok(NULL, \",\");\n\n int quantity = atoi(q);\n double price = atof(p);\n char *name = malloc(sizeof(char) * 50);\n strcpy(name, n);\n\n struct Product product = {name, price};\n struct ProductStock stockItem = {product, quantity};\n shop.stock[shop.index++] = stockItem;\n }\n \n fclose(fp);\n return shop;\n}\n\n// 3b. Generate Menu Options for User to choose from\nint menuOptions(){\n /*\n Offer Customer 2 options:\n - read in shopping list\n - search for and purchase single item\n - suggest giving customer a default budget of €20\n */\n int choice;\n\n printf(\"\\nPlease Choose and Option:\");\n printf(\"\\nProcess an Order (Enter 1)\");\n printf(\"\\nPurchase a Single Item (Enter 2)\\n\");\n printf(\"\\nExit (Enter 0)\\n\");\n scanf(\"%d\", &choice);\n\n return choice;\n}\n\n// 3c. Create a Customer entity from customer.csv file\nstruct Customer createCustomer(){\n FILE * fp;\n char * line = NULL;\n size_t len = 0;\n ssize_t read;\n\n struct Customer custEntity = {};\n\n // open iostream for customer.csv file\n fp = fopen(\"customer.csv\", \"r\");\n if (fp == NULL ){\n exit(EXIT_FAILURE);\n }\n\n // parse first line of customer.csv, to import customer's name\n getline(&line, &len, fp);\n char* custName = line;\n custEntity.name = custName;\n \n // parse second line of customer.csv, to import customer's budget\n getline(&line, &len, fp);\n double custBudget = atof(line);\n custEntity.budget = custBudget;\n \n // parse remaining line items in customer.csv file\n while ((read = getline(&line, &len, fp)) != -1){\n char *i = strtok(line, \",\");\n char *q = strtok(NULL, \",\");\n \n // store in Customer struct as shoppingList items\n // - Description\n // - Amount Required\n char *item = malloc(sizeof(char) * 50);\n strcpy(item, i);\n \n int quantity = atoi(q);\n \n //create ProductStock struct to hold each item for purchase\n struct ProductStock buyItem = {item, 0.0, quantity};\n // add each purchase item to Customers shoppingList array\n custEntity.shoppingList[custEntity.index++] = buyItem;\n }\n \n fclose(fp);\n return custEntity;\n}\n\n\n// 3a - Print Product Details\nvoid printProduct(struct Product p)\n{\n printf(\"----------------------\\n\");\n printf(\"PRODUCT NAME: %s \\nPRODUCT PRICE: %.2f\\n\", p.name, p.price);\n printf(\"----------------------\\n\");\n}\n\n// 3b - Print Customer Details\nvoid printCustomer(struct Customer c)\n{\n printf(\"\\nCUSTOMER NAME: %s \\nCUSTOMER BUDGET: %.2f\\n\", c.name, c.budget);\n printf(\"----------------------\\n\");\n \n for (int i = 0; i < c.index; i++){\n printProduct(c.shoppingList[i].product);\n printf(\"%s HAS ORDERED %d OF THE ABOVE PRODUCT.\\n\", c.name, c.shoppingList[i].quantity);\n\n double cost = c.shoppingList[i].quantity * c.shoppingList[i].product.price;\n printf(\"The cost to %s will be €%.2f\\n\\n\", c.name, cost);\n }\n}\n\nvoid printShop(struct Shop s){\n printf(\"Shop has %.2f in cash\\n\", s.cash);\n\n for (int i = 0; i < s.index; i++){\n printProduct(s.stock[i].product);\n printf(\"Shop has %d of the above.\\n\", s.stock[i].quantity);\n }\n}\n\nchar findProductName(struct Shop s, char *n)\n{\n int exists = 0;\n\n while (exists == 0){\n for (int i = 0; i < s.index; i++)\n {\n char *name = s.stock[i].product.name;\n if (strcmp(name, n) == 0){\n exists = 1;\n return exists;\n }\n }\n }\n return exists;\n}\n\ndouble findProductPrice(struct Shop s, char *n)\n{\n int exists = 0;\n\n while (exists == 0){\n for (int i = 0; i < s.index; i++)\n {\n struct Product product = s.stock[i].product;\n char *name = product.name;\n if (strcmp(name, n) == 0)\n {\n return product.price;\n }\n }\n }\n return exists;\n}\n\nint findProductQty(struct Shop s, char *n)\n{\n for (int i = 0; i < s.index; i++)\n {\n struct Product product = s.stock[i].product;\n char *name = product.name;\n if (strcmp(name, n) == 0)\n {\n return product.price;\n }\n }\n return -1;\n}\n\nint checkStockAmount(char *n, int q, struct Shop s){\n int stockCheck = -1;\n\n for(int j = 0; j < s.index; j++){\n char *name = s.stock[j].product.name;\n\n if (strcmp(name, n) == 0){\n if (q >= s.stock[j].quantity){\n stockCheck = 1;\n return stockCheck;\n }\n else{\n stockCheck = 0;\n return stockCheck;\n }\n }\n }\n\n return stockCheck;\n} \n\nvoid updateShop (struct Shop shop) { \n // complete purchase and write stock and cash updates to stock.csv\n FILE *fp = fopen (\"stock.csv\", \"w\");\n if (fp != NULL) {\n fprintf(fp, \"%.2f\\n\", shop.cash);\n for (int i = 0; i <shop.index; i++){\n fprintf(fp, \"%s, %.2f, %d\\n\", shop.stock[i].product.name, shop.stock[i].product.price, shop.stock[i].quantity);\n }\n\n fclose(fp);\n }\n}\n\nvoid orderSuccess(struct Shop s, struct Customer c, double tot){\n printf(\"\\n----------\\nThank you, your budget of €%.2f is sufficient to cover your order cost of €%.2f.\", c.budget, tot); \n printf(\"\\nThank you for your custom today.\\nHave a lovely day and see you again soon :-)\");\n // commit stock and cash changes to shop.csv\n updateShop(s);\n}\n\nvoid orderFail(struct Customer c, double tot){\n printf(\"\\n----------\\nI'm sorry, unfortunately your budget of €%.2f in not sufficient to cover your total order cost of €%.2f.\\nPlease reduce your shopping list and come back later.\", c.budget, tot);\n // do not commit stock and cash changes to shop.csv\n // continue to exit without saving\n}\n\n\nvoid processOrder(struct Shop shop, struct Customer cust){\n double orderTotal = 0;\n // - for each line item, check that product exists in Shop stock\n // - for each line item, check that product stock in shop is sufficient\n int shopStock;\n\n for (int i = 0; i < cust.index; i++){\n char *name = cust.shoppingList[i].product.name;\n int qty = cust.shoppingList[i].quantity;\n double itemPrice = 0;\n double lineTotal = 0; \n \n shopStock = checkStockAmount(name, qty, shop);\n \n if (shopStock == -1){\n printf(\"\\n----------\\nSorry, we do not stock %s here.\", name);\n } else if (shopStock == 0){\n printf(\"\\n----------\\nYes, we have enough of %s in stock for your order.\", name);\n // - for each in-stock line item calculate total cost and store in array\n itemPrice = findProductPrice(shop, name);\n lineTotal = qty*itemPrice;\n printf(\"\\nCost of %d %s at €%.2f each is €%.2f\", qty, name, itemPrice, lineTotal);\n\n // - calculate total purchase cost and confirm customer budget is sufficient to cover\n orderTotal += lineTotal;\n\n // - reduce customer budget by orderTotal amount\n cust.budget -= lineTotal;\n \n // increase shop cash by totalOrder amount\n shop.cash += lineTotal;\n \n // deduct purchased items from shop stock\n shop.stock[i].quantity -= qty;\n \n } else if (shopStock == 1){\n printf(\"\\n----------\\nSorry, we don't have enough of %s in stock at the moment.\", name);\n }\n }\n\n if (cust.budget >= orderTotal){ orderSuccess(shop, cust, orderTotal); } \n else{ orderFail(cust, orderTotal); }\n}\n\nvoid reduceStock(struct Shop s, char *n, int q){\n for (int i = 0; i <s.index; i++){\n if (strcmp(n, s.stock[i].product.name) == 0){\n s.stock[i].quantity -= q;\n break;\n }\n }\n\n updateShop(s);\n}\nvoid processGuestOrder(struct Shop shop, struct Customer cust){\n double orderTotal = 0;\n // - for each line item, check that product exists in Shop stock\n // - for each line item, check that product stock in shop is sufficient\n int shopStock;\n\n char *name = cust.shoppingList[0].product.name;\n int qty = cust.shoppingList[0].quantity;\n double itemPrice = 0;\n double lineTotal = 0; \n \n shopStock = checkStockAmount(name, qty, shop);\n \n if (shopStock == -1){\n printf(\"\\n----------\\nSorry, we do not stock %s here.\", name);\n } else if (shopStock == 0){\n printf(\"\\n----------\\nYes, we have enough of %s in stock for your order.\", name);\n // - for each in-stock line item calculate total cost and store in array\n itemPrice = findProductPrice(shop, name);\n lineTotal = qty*itemPrice;\n printf(\"\\nCost of %d %s at €%.2f each is €%.2f\", qty, name, itemPrice, lineTotal);\n\n // - reduce customer budget by orderTotal amount\n cust.budget -= lineTotal;\n \n // increase shop cash by totalOrder amount\n shop.cash += lineTotal;\n \n // deduct purchased items from shop stock\n reduceStock(shop, name, qty);\n \n } else if (shopStock == 1){\n printf(\"\\n----------\\nSorry, we don't have enough of %s in stock at the moment.\", name);\n }\n\n if (cust.budget >= lineTotal){ orderSuccess(shop, cust, lineTotal); } \n else{ orderFail(cust, lineTotal); }\n}\n\nint main(void)\n{\n // 1. Create and stock the Shop\n struct Shop shop = createAndStockShop();\n \n // 2. Offer User Options:\n int choice = menuOptions();\n\n // 3. Actions based on User Choice \n if (choice == 0){\n exit;\n }\n else if (choice == 1){\n /*\n 2. Create Customer from file\n - read in Customer's budget\n - read in each item in Customers order\n - Description\n - Quantity\n */\n struct Customer cust = createCustomer();\n processOrder(shop, cust); \n }\n else if (choice == 2){\n // Set budget to €20, since user does not have an account\n struct Customer cust = {\"Guest Shopper\", 20.0};\n char *liveItem = malloc(30);\n int qty;\n cust.index = 0;\n\n printf(\"\\nPlease type the product you wish to purchase (type 'X' to finish): \");\n // scanf(\"%s\", liveItem);\n char temp;\n scanf(\"%c\", &temp); \n scanf(\"%[^\\n]s\", liveItem);\n\n if (strcmp(liveItem, \"X\") != 0){\n printf(\"\\nHow many of %s would you like? \", liveItem);\n scanf(\"%d\", &qty);\n\n cust.shoppingList[cust.index].product.name = liveItem;\n cust.shoppingList[cust.index].quantity = qty;\n printf(\"\\n----------\\nItem: %s\\nQuantity: %d\", cust.shoppingList[cust.index].product.name, cust.shoppingList[cust.index].quantity);\n processGuestOrder(shop, cust);\n }\n } else { printf(\"\\nYou have entered an invalid menu option. Please try again.\\n\"); }\n\n printf(\"\\n\");\n return 0;\n}"
},
{
"alpha_fraction": 0.5826154947280884,
"alphanum_fraction": 0.6084573268890381,
"avg_line_length": 28.045454025268555,
"blob_id": "290b64ae27830f805563492172a043d129c0b29c",
"content_id": "760312aeef22c27e6652214730dfb9f779a0ac75",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1279,
"license_type": "permissive",
"max_line_length": 131,
"num_lines": 44,
"path": "/Assignment 2/2_prodArray.py",
"repo_name": "rhiggins2308/MultiParadigm-Programming",
"src_encoding": "UTF-8",
"text": "# Assignment 2 - Challenge 2\n# Product of an array\n# Given an array of numbers return it’s product (all the numbers multiplied together)\n# ------------------------------------------------------------------------------------\n\ndef prodArr(arr):\n # Base Case 1: check array length. If empty, return 0\n if (len(arr) == 0):\n return 0\n # Base Case 2: if first element in array argument is zero, then product will be zero irrespective of any further multiplication\n elif (arr[0] == 0):\n return 0\n # Base Case 3: check array length. If only 1 element, return it\n elif (len(arr) == 1):\n return arr[0]\n # If more than 1 element, multiply 1st elemwent by result of recursive call to prodArr()\n # with modified array from index 1 to end\n # this recursively reduces the length of the passed array by 1 each time\n # continue until a base case applies\n # return nested results back up the chain of recursove calls\n else: \n return arr[0] * prodArr(arr[1:])\n\n# ----\n# test\n# ----\n\nnums = []\nprint(str(prodArr(nums)))\n\nnums = [0]\nprint(str(prodArr(nums)))\n\nnums = [1]\nprint(str(prodArr(nums)))\n\nnums = [1, 2, 3]\nprint(str(prodArr(nums)))\n\nnums = [1, 2, 3, 0]\nprint(str(prodArr(nums)))\n\nnums = [1, 2, 0, 3]\nprint(str(prodArr(nums)))"
},
{
"alpha_fraction": 0.6616840958595276,
"alphanum_fraction": 0.6661683917045593,
"avg_line_length": 21.550561904907227,
"blob_id": "33e3ef9387d138647d13a823f6b9b207ee338d72",
"content_id": "0ba5424b0400e22cbe6fec30541e7995077e3283",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 2007,
"license_type": "permissive",
"max_line_length": 75,
"num_lines": 89,
"path": "/Assignment 1/Java/src/javaShop/Shop.java",
"repo_name": "rhiggins2308/MultiParadigm-Programming",
"src_encoding": "UTF-8",
"text": "package javaShop;\n\nimport java.io.IOException;\nimport java.nio.charset.StandardCharsets;\nimport java.nio.file.Files;\nimport java.nio.file.Paths;\nimport java.util.ArrayList;\nimport java.util.Collections;\nimport java.util.Iterator;\nimport java.util.List;\n\npublic class Shop {\n\n\tprivate double cash;\n\tprivate ArrayList<ProductStock> stock;\n\n\tpublic Shop(String fileName) {\n\t\tstock = new ArrayList<>();\n\t\tList<String> lines = Collections.emptyList();\n\t\ttry {\n\t\t\tlines = Files.readAllLines(Paths.get(fileName), StandardCharsets.UTF_8);\n\t\t\tSystem.out.println(lines.get(0));\n\t\t\tcash = Double.parseDouble(lines.get(0));\n\t\t\t// i am removing at index 0 as it is the only one treated differently\n\t\t\tlines.remove(0);\n\t\t\tfor (String line : lines) {\n\t\t\t\tString[] arr = line.split(\",\");\n\t\t\t\tString name = arr[0];\n\t\t\t\tdouble price = Double.parseDouble(arr[1]);\n\t\t\t\tint quantity = Integer.parseInt(arr[2].trim());\n\t\t\t\tProduct p = new Product(name, price);\n\t\t\t\tProductStock s = new ProductStock(p, quantity);\n\t\t\t\tstock.add(s);\n\t\t\t}\n\t\t\t\n\t\t}\n\n\t\tcatch (IOException e) {\n\n\t\t\t// do something\n\t\t\te.printStackTrace();\n\t\t}\n\t}\n\n\tpublic double getCash() {\n\t\treturn cash;\n\t}\n\n\tpublic void increaseCash(double amt){\n\t\tthis.cash += amt;\n\t}\n\n\tpublic ArrayList<ProductStock> getStock() {\n\t\treturn stock;\n\t}\n\n\t@Override\n\tpublic String toString() {\n\t\treturn \"Shop [cash=\" + cash + \", stock=\" + stock + \"]\";\n\t}\n\n\t// public static void main(String[] args) {\n\t// \tShop shop = new Shop(\"src/javaShop/stock.csv\");\n\t// }\n\t\n\tprivate double findPrice(String name) {\n\t\t\n\t\tfor (ProductStock productStock : stock) {\n\t\t\tProduct p =productStock.getProduct();\n\t\t\tif (p.getName().equals(name)) {\n\t\t\t\treturn p.getPrice();\n\t\t\t}\n\t\t}\n\t\t\n\t\treturn -1;\n\t}\n\t\n\tpublic void processOrder(Customer c) {\n\t\tfor (ProductStock productStock : stock) {\n\t\t\tProduct p = productStock.getProduct();\n\t\t\tint quantity = productStock.getQuantity();\n\t\t\tdouble price = findPrice(p.getName());\n\t\t\tSystem.out.println(p.getName() + \" costs \" + price);\n\t\t\t\n\t\t\tp.setPrice(price);\n\t\t}\n\t}\n\n}\n"
},
{
"alpha_fraction": 0.5770642161369324,
"alphanum_fraction": 0.5981651544570923,
"avg_line_length": 40.96154022216797,
"blob_id": "f84a53e5206c35057c38321e1e25d0126b3991e8",
"content_id": "2009e7b0168969a9dfd62e94a5753f8017fad0d4",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1090,
"license_type": "permissive",
"max_line_length": 88,
"num_lines": 26,
"path": "/Assignment 2/3_oddNos.py",
"repo_name": "rhiggins2308/MultiParadigm-Programming",
"src_encoding": "UTF-8",
"text": "# Assignment 2 - Challenge 3\n# Remove all odd numbers\n# Given an array of numbers return an array with all the odd numbers removed\n# ------------------------------------------------------------------------------------\n\ndef findOdd(arr):\n # Base case 1: if an empty array is passed, return an empty array\n if not arr:\n return []\n # if array contains data, check the first element using modulus 2\n if arr[0] % 2 == 1:\n # add element to array also containing results of recursive call to findOdd()\n # pass array with 1st element removed\n # continue until base case reached\n # return nested results back up the chain of recursive calls\n return [arr[0]] + findOdd(arr[1:])\n else:\n # if mod 2 == 0\n # do not add element to array and continue by making recursive call to findOdd()\n # pass array with 1st element removed\n # continue until base case reached\n # return nested results back up the chain of recursive calls\n return findOdd(arr[1:])\n\nlst = [1, 2, 3, 4, 5, 6, 7, 8, 9] \nprint(findOdd(lst))"
},
{
"alpha_fraction": 0.6544061303138733,
"alphanum_fraction": 0.6605364084243774,
"avg_line_length": 22.727272033691406,
"blob_id": "f64c455c8ce12d662fa14c87d15542c3d22b9215",
"content_id": "9d6bce15bbb1b78d6aa0c31f64554eaceacd6a5a",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1305,
"license_type": "permissive",
"max_line_length": 109,
"num_lines": 55,
"path": "/Assignment 1/Java/src/javaShop/Runner.java",
"repo_name": "rhiggins2308/MultiParadigm-Programming",
"src_encoding": "UTF-8",
"text": "package javaShop;\n\nimport java.util.*;\n\npublic class Runner {\n\n\tpublic static int menuOptions(){\n\t\t\n\t\t// ask the user how they want to proceed\n\t\tSystem.out.println(\"\\nPlease Choose and Option:\");\n\t\tSystem.out.println(\"\\nProcess an Order (Enter 1)\");\n\t\tSystem.out.println(\"Purchase a Single Item (Enter 2)\");\n\t\tSystem.out.println(\"Exit (Enter 0)\\n\");\n\n\t\t// create the scanner to take in user input\n\t\tScanner scan = new Scanner(System.in);\n\n\t\tint c = scan.nextInt();\n\t\tscan.close();\n\n\t\treturn c;\n\t}\n\n\tpublic static void main(String[] args) {\n\t\tShop shop = new Shop(\"javaShop/stock.csv\");\n\t\t\n\t\tint choice = menuOptions();\n\t\tSystem.out.println(choice);\n\t\t\n\t\tswitch(choice){\n\t\t\tcase 0:\n\t\t\t\tSystem.out.println(\"Thank you. Goodbye.\");\n\t\t\t\tbreak;\n\t\t\tcase 1: \n\t\t\t\tSystem.out.println(\"You Selected 1\");\n\t\t\t\tCustomer custAcc = new Customer(\"javaShop/customer.csv\");\n\t\t\t\tSystem.out.println(custAcc);\n\t\t\t\tSystem.out.println();\n\t\t\n\t\t\t\t//process order\n\t\t\t\tSystem.out.println(\"Thank you.\\nYour order has not been processed today.\\nPlease come back again soon.\");\n\t\t\t\t\n\t\t\t\tbreak;\n\t\t\tcase 2: \n\t\t\t\tSystem.out.println(\"You Selected 2\");\n\t\t\t\tbreak;\n\t\t\tdefault:\n\t\t\t\tSystem.out.println(\"\\nYou have entered an invalid menu option. Please try again.\\n\");\n\t\t}\n\n\t\t\t\n//\t\tSystem.out.println(james);\n//\t\tshop.processOrder(james);\n\t}\n}\n"
},
{
"alpha_fraction": 0.7979797720909119,
"alphanum_fraction": 0.8484848737716675,
"avg_line_length": 48.5,
"blob_id": "e5e79e36b0a283d19e11857fa88fb7676e792c02",
"content_id": "a14668dfce8023c7def33290428e6525b9df0193",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 99,
"license_type": "permissive",
"max_line_length": 70,
"num_lines": 2,
"path": "/README.md",
"repo_name": "rhiggins2308/MultiParadigm-Programming",
"src_encoding": "UTF-8",
"text": "# MultiParadigm-Programming\nAssessment Material for HDip Module 52960 - Multi-Paradigm Programming\n"
},
{
"alpha_fraction": 0.6555132865905762,
"alphanum_fraction": 0.6608365178108215,
"avg_line_length": 49.61538314819336,
"blob_id": "3e43799c363bb525b42757b61bb8aee116208069",
"content_id": "0c7b1221005f557ef35a70815401c9e261975854",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1315,
"license_type": "permissive",
"max_line_length": 144,
"num_lines": 26,
"path": "/Assignment 2/5_replaceChar.py",
"repo_name": "rhiggins2308/MultiParadigm-Programming",
"src_encoding": "UTF-8",
"text": "# Assignment 2 - Challenge 5\n# Replace a given character with '*' Given a string, and a character to replace,\n# return a string where each occurance of the character is replaced with '*'\n# ------------------------------------------------------------------------------------\n\ndef replaceChar(str, tok):\n # Base Case: when string argument is empty, return same\n if str == '':\n return ''\n # if first element of string argument matches the character specified to be altered\n # return '*' in place of that character concatenated with the result of recursive call, passing string argument with first character removed\n # continue until base case reached\n # return nested results back up the chain of recursive calls\n if str[0] == tok:\n return '*' + replaceChar(str[1:], tok)\n # if first element of string argument does not match the character specified to be altered\n # return str[0] unaltered, concatenated with the result of recursive call, passing string argument with first character removed\n # continue until base case reached\n # return nested results back up the chain of recursive calls\n else:\n return str[0] + replaceChar(str[1:], tok)\n\n# -----\n# test\n# -----\nprint(replaceChar(input('Enter a string to modify: '), input('Enter a character to replace: ')))"
},
{
"alpha_fraction": 0.6267516016960144,
"alphanum_fraction": 0.6433120965957642,
"avg_line_length": 28.11111068725586,
"blob_id": "8c64f60e67f36618f0b4d9e26b773120534bef39",
"content_id": "15cd91708a6d1c9163939cf8d59f9dd63756270f",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 785,
"license_type": "permissive",
"max_line_length": 104,
"num_lines": 27,
"path": "/Assignment 2/8_printArr.py",
"repo_name": "rhiggins2308/MultiParadigm-Programming",
"src_encoding": "UTF-8",
"text": "# Assignment 2 - Challenge 8\n# Print an array\n# Given an array of integers print all the elements one per line.\n# This is a little bit different as there is no need for a 'return' statement just to print and recurse.\n\ndef printStr(nums):\n # Base case: if nums is empty, print blank line to terminate\n if(len(nums) == 0):\n print()\n # if nums contains integers, print the first digit to screen and make recursive call\n # pass int array, with first element removed\n # continue until base case reached\n # return nested results back up the chain of recursive calls\n else:\n print(nums[0])\n printStr(nums[1:])\n\n# -----\n# test\n# -----\n\nprint(\"Test 1:\\n\")\nprint(\"----------\")\nprintStr([])\nprint(\"Test 2:\\n\")\nprint(\"----------\")\nprintStr([0,1,2,3,4,5])"
},
{
"alpha_fraction": 0.5693950057029724,
"alphanum_fraction": 0.5860023498535156,
"avg_line_length": 27.133333206176758,
"blob_id": "360ddb1da72fefc9d54e63fb2115ad7c1112803a",
"content_id": "83ab173701ab895ce5aeafeca14c2926ddb9d094",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 845,
"license_type": "permissive",
"max_line_length": 96,
"num_lines": 30,
"path": "/Assignment 2/1_sumArray.py",
"repo_name": "rhiggins2308/MultiParadigm-Programming",
"src_encoding": "UTF-8",
"text": "# Assignment 2 - Challenge 1\n# Sum of an array\n# Given an array of numbers return it’s sum (all the numbers added together)\n# ----------------------------------------------------------------------------\n\ndef sumArr(arr):\n # check array length. \n \n # Base case: If empty, return 0\n if (len(arr) == 0):\n return 0\n # If 1 or more elements, add the first element to the return of a recursive call to sumArr()\n # with modified array from index 1 to end\n # this recursively reduces the length of the passed array by 1 each time\n # continue until a base case applies\n # return nested results back up the chain of recursive calls\n else: \n return arr[0] + sumArr(arr[1:])\n# ----\n# test\n# ----\n\nnums = []\nprint(str(sumArr(nums)))\n\nnums = [1]\nprint(str(sumArr(nums)))\n\nnums = [1, 2, 3]\nprint(str(sumArr(nums)))"
},
{
"alpha_fraction": 0.6017382144927979,
"alphanum_fraction": 0.6104294657707214,
"avg_line_length": 29.578125,
"blob_id": "1c6489559ee0a33dc7565d07e200c28c147865b3",
"content_id": "6bc53acbbec432e9bb60166a2edfeb08e9e3ba39",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1956,
"license_type": "permissive",
"max_line_length": 64,
"num_lines": 64,
"path": "/Assignment 2/10_brackets_rev2.py",
"repo_name": "rhiggins2308/MultiParadigm-Programming",
"src_encoding": "UTF-8",
"text": "def check(string, bracks):\n # Base Case: where no elements/chars left in string\n if not string:\n # if no. open brackets matches no. close brackets\n # string is balanced\n if (bracks == 0):\n return True\n # if no. open brackets does not match no. close brackets\n # string is not balanced\n else:\n return False \n # if first string element is (\n elif (string[0] == \"(\"):\n # increment bracks and pass to recursive call\n # with string minus first element\n # continue recursion until Base Case reached\n # i.e. empty string passed to recursive call\n return check(string[1:], bracks+1)\n # if first string element is )\n elif (string[0] == \")\"):\n # decrement bracks and pass to recursive call\n # with string minus first element\n # continue recursion until Base Case reached\n # i.e. empty string passed to recursive call\n return check(string[1:], bracks-1)\n # caters for any other char in the first string element\n else:\n # do not modify bracks and pass to recursive call\n # with string minus first element\n # continue recursion until Base Case reached\n # i.e. empty string passed to recursive call\n return check(string[1:], bracks)\n\n# -----\n# test\n# -----\n\nbracks = 0\nstring =\"\"\nprint(\"Test 1:\", string, check(string, bracks))\n\nstring =\"))\"\nprint(\"Test 2:\", string, check(string, bracks))\n\nstring =\"(\"\nprint(\"Test 3:\", string, check(string, bracks))\n\nstring =\"()\"\nprint(\"Test 4:\", string, check(string, bracks))\n\nstring =\"())\"\nprint(\"Test 5:\", string, check(string, bracks))\n\nstring =\")()(((())()))\"\nprint(\"Test 6:\", string, check(string, bracks))\n\nstring =\"((((((((()))()))))))\"\nprint(\"Test 7:\", string, check(string, bracks))\n\nstring =\")\"\nprint(\"Test 8:\", string, check(string, bracks))\nprint()\nprint(\"Done ...\")\nprint(\"Noice! Merry Christmas ....Time to GET SCHWIFTY!!\")"
},
{
"alpha_fraction": 0.6577181220054626,
"alphanum_fraction": 0.6724832057952881,
"avg_line_length": 31.434782028198242,
"blob_id": "4842780e0317b60234b345ecd9f36de023c0966e",
"content_id": "3e12b1e073a6c46cd462d8aadc366224e86a1ff0",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 745,
"license_type": "permissive",
"max_line_length": 93,
"num_lines": 23,
"path": "/Assignment 2/7_sumDigits.py",
"repo_name": "rhiggins2308/MultiParadigm-Programming",
"src_encoding": "UTF-8",
"text": "# Assignment 2 - Challenge 7\n# Sum of Digits\n# Given a whole number such as 23, return the sum of the digits in the number\n# i.e. 2 + 3 = 5.\n# For this would be useful to convert the number to a string then break it apart into digits.\n\ndef sumDigits(n):\n # base case: when no more digits left, return zero with no recursive call\n if (len(n) == 0):\n return 0\n # if n contains digits, add the first digit to the result of make recursive call\n # pass specified number, with first digit removed\n # continue until base case reached\n # return nested results back up the chain of recursive calls\n else:\n return int(n[0]) + sumDigits(n[1:])\n\n\n# -----\n# test\n# -----\n\nprint(sumDigits(input('Enter an integer value: ')))"
},
{
"alpha_fraction": 0.6462035775184631,
"alphanum_fraction": 0.6785137057304382,
"avg_line_length": 28.5,
"blob_id": "5a38943224e26b5f5d5766c4233d3b943d1ff448",
"content_id": "58f1ba3d8cf2a2253e155a8f25fbf50c5e9d1743",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1238,
"license_type": "permissive",
"max_line_length": 96,
"num_lines": 42,
"path": "/Assignment 2/6_findIndex.py",
"repo_name": "rhiggins2308/MultiParadigm-Programming",
"src_encoding": "UTF-8",
"text": "# Assignment 2 - Challenge 6\n# Find index in array for item.\n# Given an array, and an element to search for\n# return the index of the element in the array or -1 if the element is not present in the array.\n\ndef findIndex(s, tok):\n # base case: where array argument is empty, return -1\n if (len(s) == 0):\n return -1\n # if last element in array matches search token, return element index\n elif (s[len(s)-1] == tok):\n return len(s)-1\n # if last element in array does not match search token\n # make recursive call, passing search token and array with last element removed\n # continue until base case reached\n # return nested results back up the chain of recursive calls\n else:\n return findIndex(s[:-1], tok)\n\n# -----\n# test\n# -----\n\nstrNums = []\nprint(findIndex(strNums, 4))\nstrNums = [0]\nprint(findIndex(strNums, 4))\nstrNums = [4]\nprint(findIndex(strNums, 4))\nstrNums = [0, 1, 4]\nprint(findIndex(strNums, 4))\nstrNums = [0, 1, 5]\nprint(findIndex(strNums, 4))\n\nstrNums = [0, 1, 4, 9, 16, 25]\nprint(findIndex(strNums, 0))\nprint(findIndex(strNums, 1))\nprint(findIndex(strNums, 4))\nprint(findIndex(strNums, 9))\nprint(findIndex(strNums, 16))\nprint(findIndex(strNums, 25))\nprint(findIndex(strNums, 40))"
},
{
"alpha_fraction": 0.6278538703918457,
"alphanum_fraction": 0.663241982460022,
"avg_line_length": 28.233333587646484,
"blob_id": "9da3c3ed16e8e99b16050887118f341c94d4f79c",
"content_id": "56402b2b05fa5b1052b676166c2c71578fc06750",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 876,
"license_type": "permissive",
"max_line_length": 123,
"num_lines": 30,
"path": "/Assignment 2/9_findMin.py",
"repo_name": "rhiggins2308/MultiParadigm-Programming",
"src_encoding": "UTF-8",
"text": "# Assignment 2 - Challenge 9\n# Find the minimum element in an array of integers.\n# You can carry some extra information through method arguments such as minimum value.\n\ndef findMin(n):\n # Base case: if nums is empty, return string and terminate\n if (len(n) == 0):\n return \"Empty\"\n # Base case: if nums has only one element, return it and terminate\n elif len(n) == 1:\n return n[0]\n # if n contains more than 1 integer,\n # retirn the minimum of n[0] and the reult of a recursive call that takes na as a parameter, with first element removed\n # continue until base case reached\n # return nested results back up the chain of recursive calls\n else:\n return min(n[0], findMin(n[1:]))\n\n# -----\n# test\n# -----\n\nnums = []\nprint(findMin(nums))\n\nnums = [9]\nprint(findMin(nums))\n\nnums = [9,-3333333333333, -2,6,1,80,9,-2]\nprint(findMin(nums))"
}
] | 13 |
IshraqBhuiyan/line_drawer | https://github.com/IshraqBhuiyan/line_drawer | 489365163d72495f2f017294a35d3d00002b0485 | 4c1e79cf8910d005590bdc6cb8dbd208686fa92e | 3b25ebb4c1492aafcb43863b5fcf81cb71958a1f | refs/heads/master | 2021-01-10T17:54:39.089664 | 2016-02-25T12:53:31 | 2016-02-25T12:53:31 | 51,597,355 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6571428775787354,
"alphanum_fraction": 0.6571428775787354,
"avg_line_length": 13,
"blob_id": "c81d19d70288b1bfbc9c62718c3017d15ec83411",
"content_id": "d5d401054aa5bce99b42a5b96eda062656c4eec5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 70,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 5,
"path": "/makefile",
"repo_name": "IshraqBhuiyan/line_drawer",
"src_encoding": "UTF-8",
"text": "run: main.py display.py draw.py\n\t\t\tpython main.py\n\nclean:\n\t\t\trm *.pyc\n"
},
{
"alpha_fraction": 0.2872968912124634,
"alphanum_fraction": 0.32348597049713135,
"avg_line_length": 20.838708877563477,
"blob_id": "3f867d2f55dd0cfd04bf1a6ad8b9bcf8a61fa816",
"content_id": "2f0ab2d22df16433a38ddac73727acb7df668158",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1354,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 62,
"path": "/draw.py",
"repo_name": "IshraqBhuiyan/line_drawer",
"src_encoding": "UTF-8",
"text": "from display import *\n\ndef draw_line( screen, x0, y0, x1, y1, color ):\n if x1 < x0:\n startx = x1\n starty = y1\n x = x0\n y = y0\n else:\n startx = x0\n starty = y0\n x = x1\n y = y1\n A = y - starty\n B = -(x - startx)\n ## Octant 1\n if A >= 0 and A <= -B:\n print \"Octant1\\n\"\n d = 2*A + B\n z =0\n while startx <= x:\n #print \"Making octant1 Line\\n\"\n #print z\n plot(screen, color, x, y)\n if d>0:\n y += 1\n d += 2 * B\n x += 1\n d += 2 * A\n #z+= 1\n ## Octant 8\n elif A < 0 and -A >= B:\n #print \"Octant 8\\n\"\n d = 2*A - B\n while startx <= x:\n plot(screen, color, x, y)\n if d<0:\n y-=1\n d-=2*B\n x+=1\n d+=2*A\n elif A > -B:\n #print \"Octant 2\\n\"\n d = A + 2*B\n while starty <= y:\n plot(screen, color, x, y)\n if d<0:\n x+=1\n d+=2*A\n y+=1\n d+=2*B\n else:\n #print \"Octant 7\\n\"\n d= A-2*B\n while starty>=y:\n plot(screen, color, x, y)\n if d>0:\n x+=1\n d+=2*A\n y-=1\n d-=2*B\n pass\n"
},
{
"alpha_fraction": 0.6296296119689941,
"alphanum_fraction": 0.7407407164573669,
"avg_line_length": 12.5,
"blob_id": "8d5e7d52f27cc4ec50779a1fb5003ab99969cef4",
"content_id": "98d82623492fe3878949ee344eee66f601eee3bc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 27,
"license_type": "no_license",
"max_line_length": 13,
"num_lines": 2,
"path": "/README.md",
"repo_name": "IshraqBhuiyan/line_drawer",
"src_encoding": "UTF-8",
"text": "# line_drawer\nMKS66 Work 1\n"
}
] | 3 |
Siddiqui-code/Lab-Assignment-8 | https://github.com/Siddiqui-code/Lab-Assignment-8 | c5c51abb64057355b2f12a7b1b3b7ca89ddb9b2a | b41ac7afc438e47dd2c3776489f19e840f583e39 | 51afd348d85eb9f4a72e061dcbe82cd7cfc12345 | refs/heads/main | 2023-03-13T18:51:51.052344 | 2021-03-07T05:25:08 | 2021-03-07T05:25:08 | 345,265,653 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.568561851978302,
"alphanum_fraction": 0.5953177213668823,
"avg_line_length": 21.153846740722656,
"blob_id": "48d296eb68a33accdcc4b300f2917ebfea5e8f16",
"content_id": "442f19fb6f4c2a9de392294d5ac1c27b9f4d8002",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 299,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 13,
"path": "/Question1.py",
"repo_name": "Siddiqui-code/Lab-Assignment-8",
"src_encoding": "UTF-8",
"text": "# Nousheen Siddiqui\r\n# Edited on 03/03/2021\r\n# Write a function that takes two inputs from a user and prints whether they are equal or not.\r\n\r\ndef numbers():\r\n x = input(\"Mention an input\")\r\n y = input(\"Mention an input\")\r\n if x == y:\r\n print(True)\r\n else:\r\n print(False)\r\n\r\nnumbers()"
},
{
"alpha_fraction": 0.38910505175590515,
"alphanum_fraction": 0.4747081696987152,
"avg_line_length": 14.733333587646484,
"blob_id": "8563c67e8462a87449293d7bd1c4fd85fc70ed4e",
"content_id": "daae78c8cfac7973f9830937876b19d34dd9972b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 257,
"license_type": "no_license",
"max_line_length": 25,
"num_lines": 15,
"path": "/Question4.py",
"repo_name": "Siddiqui-code/Lab-Assignment-8",
"src_encoding": "UTF-8",
"text": "# Nousheen Siddiqui\r\n# Edited on 03/03/2021\r\n#\r\n\r\ndef year(year):\r\n if year % 400 == 0:\r\n return True\r\n elif year % 100 == 0:\r\n return False\r\n elif year % 4 == 0:\r\n return True\r\n else:\r\n return False\r\n\r\nprint(year(1984))\r\n\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.5396226644515991,
"alphanum_fraction": 0.5962263941764832,
"avg_line_length": 20.25,
"blob_id": "3a3a9b85eb9d2bc0455b9c7386b326135315c76d",
"content_id": "8f2d24a921ac66b94a693e5017f2b61d0be7a3cf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 265,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 12,
"path": "/Question3.py",
"repo_name": "Siddiqui-code/Lab-Assignment-8",
"src_encoding": "UTF-8",
"text": "# Nousheen Siddiqui\r\n# 03/03/2021\r\n# Write a function that takes a list and prints if the value 5 is in that list.\r\n\r\ndef list_values(n):\r\n if 5 in n:\r\n print(\"Number is in list\")\r\n else:\r\n print(\"Number not in list\")\r\nlist=[6,8,3,7,9]\r\n\r\nlist_values(list)"
},
{
"alpha_fraction": 0.6537102460861206,
"alphanum_fraction": 0.6631330847740173,
"avg_line_length": 38.238094329833984,
"blob_id": "e66e25a6ce537e1ce2a738c48b765c466abfaf6e",
"content_id": "ec5434ab14704a9b1d5b6b49d581042345237dca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 849,
"license_type": "no_license",
"max_line_length": 146,
"num_lines": 21,
"path": "/Question5.py",
"repo_name": "Siddiqui-code/Lab-Assignment-8",
"src_encoding": "UTF-8",
"text": "# Nousheen Siddiqui\r\n# Edited on 03/05/2021\r\n# A function checks whether your game character has picked up all the items needed to perform certain tasks and checks against any status debuffs.\r\n# Confirm checks with print statements.\r\n\r\n\r\n\r\ndef character(status_debufs,item_list):\r\n if \"rope\" in item_list and \"coat\" in item_list and \"first_aid kit\" in item_list and \"slow\" not in status_debufs:\r\n print(\"You can climb mountain\")\r\n elif \"pan\" in item_list and \"groceries\" in item_list and \"small\" not in status_debufs:\r\n print(\"Can cook a meal\")\r\n elif \"pen\" in item_list and \"paper\" in item_list and \"idea\" in item_list and \"confusion\" not in status_debufs:\r\n print(\"Write a book\")\r\n else:\r\n print(\"No action\")\r\n\r\nitems = [\"pan\", \"paper\", \"idea\", \"rope\", \"groceries\"]\r\nstatus = [\"slow\"]\r\n\r\ncharacter(status, items)\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.7222222089767456,
"alphanum_fraction": 0.7777777910232544,
"avg_line_length": 18,
"blob_id": "b2aa5a81775ff46b80aa7955ea4b8562ae0a02de",
"content_id": "0d5ab44a99c30ceceb1effd6f9204fb6a8033ec6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 18,
"license_type": "no_license",
"max_line_length": 18,
"num_lines": 1,
"path": "/README.md",
"repo_name": "Siddiqui-code/Lab-Assignment-8",
"src_encoding": "UTF-8",
"text": "# Lab-Assignment-8"
},
{
"alpha_fraction": 0.5349397659301758,
"alphanum_fraction": 0.5927711129188538,
"avg_line_length": 22.52941131591797,
"blob_id": "0bb6776b3354a563073a05664c493c0416072ff5",
"content_id": "d9125d91a576d129bfba077325c3b4079545caf7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 415,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 17,
"path": "/Question2.py",
"repo_name": "Siddiqui-code/Lab-Assignment-8",
"src_encoding": "UTF-8",
"text": "# Nousheen Siddiqui\r\n# 03/03/2021\r\n# Write a function that takes two inputs from a user and prints whether the sum is greater than 10,\r\n# less than 10, or equal to 10\r\n\r\ndef numbers():\r\n x=int(input(\"Mention an input\"))\r\n y=int(input(\"Mention an input\"))\r\n sum=x+y\r\n if sum>10:\r\n print(\"Greater than 10\")\r\n elif sum<10:\r\n print(\"Less than 10\")\r\n else:\r\n print(\"Equal to 10\")\r\n\r\nnumbers()"
}
] | 6 |
jeelpatel007/Profanity_Checker | https://github.com/jeelpatel007/Profanity_Checker | d0ca45e4d664dcb1ca8c9a737c6ecbe44412bbd8 | 75470435963179ec0667446f5948f7273461c6ab | 99cb3ad8317d2e653f9399fb8f2465620b1ce60f | refs/heads/master | 2016-09-06T14:47:17.817244 | 2015-08-12T23:40:40 | 2015-08-12T23:40:40 | 40,518,579 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.711614191532135,
"alphanum_fraction": 0.711614191532135,
"avg_line_length": 29.787878036499023,
"blob_id": "2c59c32741ca7d74cd4e46daa999824e601a8408",
"content_id": "c0fda8be9309785a67d86388d6a61ca95be5e6f3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1016,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 33,
"path": "/profanity_chk.py",
"repo_name": "jeelpatel007/Profanity_Checker",
"src_encoding": "UTF-8",
"text": "#import urllib\nimport requests\n\n# read_text parse the text file to be used for profanity check.\n\ndef read_text():\n# Replace below location with the location of text file on your machine\n\tfile_reader = open(\"C:\\Users\\Jeel\\Desktop\\Python\\adventure.txt\")\n\tcontents_of_file = file_reader.read()\n\tprint (contents_of_file)\n\tfile_reader.close()\n\tcheck_profanity(contents_of_file)\n\n# check_profanity sends the text to wdyl and returns the profanity results\n\ndef check_profanity(text_to_check):\n\t\t#connection = urllib.urlopen(\"http://www.wdyl.com/profanity?q=\"+text_to_check)\n\t\t#output = connection.read()\n\t\t#print (output)\n\t\t#connection.close()\n\t\tr = requests.get('http://www.wdyl.com/profanity', params={'q': text_to_check})\n\n# display the result of our test and print a warning message if foul words are found\n\n\t\tif \"true\" in r.text:\n\t\t\tprint(\"Profanity Alert!!\")\n\t\telif \"false\" in r.text:\n\t\t\tprint (\"No Profanity Found\")\n\t\telse:\n\t\t\tprint(\"Could not scan the document properly\")\n\t\t\nif __name__ == \"__main__\":\n\tread_text()\n"
},
{
"alpha_fraction": 0.7677724957466125,
"alphanum_fraction": 0.7677724957466125,
"avg_line_length": 51.75,
"blob_id": "ebe78decc417d21a80ad0754d6fcb85d6bdaaf1d",
"content_id": "ffc453c1fa91a3ef6f00787b9297c3d6451708c0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 211,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 4,
"path": "/README.md",
"repo_name": "jeelpatel007/Profanity_Checker",
"src_encoding": "UTF-8",
"text": "# Profanity_Checker\nProfanity Checker is a simple script used to check \"foul\" words in a given file.\n\nYou can use the text file which I used to test (adventure.txt) or feel free to test with your own text file.\n"
}
] | 2 |
greenmonn/coding-kata | https://github.com/greenmonn/coding-kata | c3d4018e848606b60b452c987cf7a8cc8345dbc3 | ea66a4eabbf1d7a626407237f24003640520ebac | 9a89345dff866d2e234b9b9466f502923f203705 | refs/heads/master | 2020-03-23T08:14:22.928573 | 2018-08-16T07:27:20 | 2018-08-17T03:23:56 | 141,315,732 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.46736598014831543,
"alphanum_fraction": 0.5477855205535889,
"avg_line_length": 21.0256404876709,
"blob_id": "50e890391bff4b15df6b7ac2bf1ff4caa9430338",
"content_id": "ba9c1aa651579d09182c9529e5008c26bafaff6f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 858,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 39,
"path": "/selfnumber_py/selfnumber_with_wanjae_test.py",
"repo_name": "greenmonn/coding-kata",
"src_encoding": "UTF-8",
"text": "import pytest\n\ndef findSelfNumbers(to):\n selfNumberMap = {i:True for i in range(to)}\n\n for i in range(to):\n selfNumberMap[d(i)] = False\n\n selfnumbers = set({})\n\n return { i for i in range(to) if selfNumberMap[i] is True }\n \n return selfnumbers\n\ndef d(n):\n return n + sum(digits(n))\n\ndef digits(n):\n x = 1\n while True:\n if n < 10 ** x:\n return [n // 10 ** (x - i - 1) % 10 for i in range(x)]\n x += 1\n\ndef test_selfnumber():\n assert {1, 3, 5, 7, 9} == findSelfNumbers(10)\n assert 1227365 == sum(findSelfNumbers(5000))\n \n\ndef test_generate():\n assert 101 == d(91)\n assert 175+1+7+5 == d(175)\n\ndef test_digits():\n assert digits(80) == [8, 0]\n assert digits(91) == [9, 1]\n assert digits(101) == [1, 0, 1]\n assert digits(201) == [2, 0, 1]\n assert digits(2011) == [2, 0, 1, 1]"
},
{
"alpha_fraction": 0.6004296541213989,
"alphanum_fraction": 0.6100966930389404,
"avg_line_length": 15.051724433898926,
"blob_id": "32306434fe43e69158a73de94312354e1316bf4e",
"content_id": "975ab41ed4f834fe68903bbe6f4bca7af754a44a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 931,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 58,
"path": "/jollyjumper/jolly.go",
"repo_name": "greenmonn/coding-kata",
"src_encoding": "UTF-8",
"text": "package jollyjumper\n\ntype IntSequence []int\n\nfunc IsJolly(sequence IntSequence) bool {\n\tlength := len(sequence)-1\n\n\tdiffs := sequence.diffs()\n\n\tsort(diffs)\n\n\treturn diffs.isContinuousSequence(1, length)\n}\n\nfunc (sequence IntSequence) diffs() (diffs IntSequence){\n\tlength := len(sequence) - 1\n\tdiffs = make([]int, length)\n\n\tfor i := 0; i<length; i++ {\n\t\tdiffs[i] = abs(sequence[i] - sequence[i+1])\n\t}\n\n\treturn\n}\n\nfunc (sequence IntSequence) isContinuousSequence(from int, to int) bool {\n\tfor i := from; i <= to; i++ {\n\t\tindex := i-from\n\t\tif sequence[index] != i {\n\t\t\treturn false\n\t\t}\n\t}\n\treturn true\n}\n\nfunc abs(number int) int {\n\tif number < 0 {\n\t\treturn -1 * number\n\t}\n\n\treturn number\n}\n\nfunc sort(list []int) {\n\tfor i := 0; i<len(list); i++ {\n\t\tfor j := i+1; j<len(list); j++ {\n\t\t\tif list[i] > list[j] {\n\t\t\t\tswap(&list[i], &list[j])\n\t\t\t}\n\t\t}\n\t}\n}\n\nfunc swap(left *int, right *int) {\n\ttmp := *left\n\t*left = *right\n\t*right = tmp\n}\n"
},
{
"alpha_fraction": 0.6256517171859741,
"alphanum_fraction": 0.6350364685058594,
"avg_line_length": 15.80701732635498,
"blob_id": "d7e3afdd6f7b9a38941004dfa237ddde988e970b",
"content_id": "e64b97d05a5c4cc75e97f8065ecdc460b84f6d1b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 959,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 57,
"path": "/selfnumber/sequence.go",
"repo_name": "greenmonn/coding-kata",
"src_encoding": "UTF-8",
"text": "package selfnumber\n\ntype Sequence []int\n\nfunc NewSequence(from int, to int) (sequence Sequence) {\n\tsequence = make([]int, to-from)\n\n\tfor number := from; number < to; number++ {\n\t\tindex := number - from\n\t\tsequence[index] = number\n\t}\n\n\treturn\n}\n\nfunc (sequence Sequence) FilterSelfNumber(from int, to int) Sequence {\n\tfor i := 1; i < to; i++ {\n\t\tnumber := generate(i)\n\t\tif from <= number && number < to {\n\t\t\tindex := number - from\n\t\t\tsequence[index] = 0\n\t\t}\n\t}\n\n\treturn sequence\n}\n\nfunc (sequence Sequence) Sum() (sum int) {\n\tfor _, value := range sequence {\n\t\tsum += value\n\t}\n\treturn\n}\n\nfunc generate(number int) int {\n\treturn number + sumOfElements(digits(number))\n}\n\nfunc sumOfElements(list []int) (sum int) {\n\tfor _, value := range list {\n\t\tsum += value\n\t}\n\treturn\n}\n\nfunc digits(number int) (result []int) {\n\tresult = make([]int, 0)\n\n\tfor number >= 10 {\n\t\tresult = append(result, number%10)\n\t\tnumber /= 10\n\t}\n\n\tresult = append(result, number)\n\n\treturn\n}\n\n"
},
{
"alpha_fraction": 0.44114241003990173,
"alphanum_fraction": 0.5252798199653625,
"avg_line_length": 30.59756088256836,
"blob_id": "b63f1368115fb4a1a33e50de598955a5cce4d23a",
"content_id": "9242a80b5634f0fdbbfbeb4a7bb6bb2ad54abd63",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2605,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 82,
"path": "/potterkata/potter_test.py",
"repo_name": "greenmonn/coding-kata",
"src_encoding": "UTF-8",
"text": "import unittest\n\n# 최저가를 구하자\n\ndef price(list):\n list.sort()\n list.reverse()\n\n seriesCount = getSeriesCount(list)\n\n if seriesCount == 5:\n sum1 = 8 * 5 * 0.75 + price(retrieveSeries(list, 5))\n sum2 = 8 * 4 * 0.8 + price(retrieveSeries(list, 4))\n return min(sum1, sum2)\n\n if seriesCount == 4:\n remain_list = retrieveSeries(list, 4)\n return 8 * 4 * 0.8 + price(remain_list)\n\n if seriesCount == 3:\n remain_list = retrieveSeries(list, 3)\n return 8 * 3 * 0.9 + price(remain_list)\n\n if seriesCount == 2:\n remain_list = retrieveSeries(list, 2)\n return 8 * 2 * 0.95 + price(remain_list)\n\n return sum(list) * 8\n\ndef retrieveSeries(list, limit):\n count = 0\n \n remain_list = [0, 0, 0, 0, 0]\n\n for i in range(len(list)):\n remain_list[i] = list[i]\n if list[i] != 0:\n count += 1\n if count > limit:\n return remain_list\n remain_list[i] -= 1\n return remain_list\n\ndef getSeriesCount(list):\n count = 0\n for i in list:\n if i != 0:\n count += 1\n return count\n\n\nclass PotterKataTest(unittest.TestCase):\n def test_retrieve_series(self):\n self.assertEqual([0, 0, 0, 0, 1], retrieveSeries([1, 1, 1, 1, 1], 4))\n\n def test_get_series_count(self):\n self.assertEqual(0, getSeriesCount([0, 0, 0, 0, 0]))\n self.assertEqual(2, getSeriesCount([1, 1, 0, 0, 0]))\n\n def test_simple(self):\n self.assertEqual(0, price([0, 0, 0, 0, 0]))\n self.assertEqual(8, price([1, 0, 0, 0, 0]))\n self.assertEqual(8, price([0, 1, 0, 0, 0]))\n self.assertEqual(8, price([0, 0, 1, 0, 0]))\n self.assertEqual(8, price([0, 0, 0, 1, 0]))\n self.assertEqual(8, price([0, 0, 0, 0, 1]))\n\n def test_simple_with_discounts(self):\n self.assertEqual(8 * 2 * 0.95, price([1, 1, 0, 0, 0]))\n self.assertEqual(8 * 3 * 0.9, price([1, 1, 1, 0, 0]))\n self.assertEqual(8 * 4 * 0.8, price([1, 1, 1, 1, 0]))\n self.assertEqual(8 * 5 * 0.75, price([1, 1, 1, 1, 1]))\n\n def test_several_discounts(self):\n self.assertEqual(8 + (8 * 2 * 0.95), price([2, 1, 0, 0, 0]))\n self.assertEqual(2 * (8 * 2 * 0.95), price([2, 2, 0, 0, 0]))\n self.assertEqual((8 * 4 * 0.8) + (8 * 2 * 0.95), price([2, 1, 2, 1, 0]))\n self.assertEqual(8 + (8 * 5 * 0.75), price([1, 2, 1, 1, 1]))\n\n def test_edge_cases(self):\n self.assertEqual(2 * (8 * 4 * 0.8), price([2, 2, 2, 1, 1]))\n self.assertEqual(3 * (8 * 5 * 0.75) + 2 * (8 * 4 * 0.8), price([5, 5, 4, 5, 4]))\n"
},
{
"alpha_fraction": 0.5428937077522278,
"alphanum_fraction": 0.6184378862380981,
"avg_line_length": 14.313725471496582,
"blob_id": "f116d7fd5682938efc8fde2ade9acf437cff255d",
"content_id": "ccadbc770ee1eb9e82a57baf7c113173cd587d9d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 781,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 51,
"path": "/jollyjumper/jolly_test.go",
"repo_name": "greenmonn/coding-kata",
"src_encoding": "UTF-8",
"text": "package jollyjumper\n\nimport \"fmt\"\n\n// 1 4 2 3 => Jolly\n// 1 4 2 -1 6 => Not Jolly\n// 11 7 4 2 1 6 => Jolly\n\nfunc ExampleIsJolly() {\n\tsequence1 := []int{1, 4, 2, 3}\n\tsequence2 := []int{1, 4, 2, -1, 6}\n\n\tfmt.Println(IsJolly(sequence1))\n\tfmt.Println(IsJolly(sequence2))\n\n\t// Output:\n\t// true\n\t// false\n}\n\nfunc ExampleIsContinuousSequence() {\n\tsequence1 := IntSequence{1, 2, 3, 4}\n\tsequence2 := IntSequence{1, 4, 2, -1, 6}\n\n\tfmt.Println(sequence1.isContinuousSequence(1, 4))\n\tfmt.Println(sequence2.isContinuousSequence(1, 4))\n\n\t// Output:\n\t// true\n\t// false\n}\n\nfunc ExampleDiffs() {\n\tsequence := IntSequence{1, 4, 2, 3}\n\n\tfmt.Println(sequence.diffs())\n\n\t// Output:\n\t// [3 2 1]\n}\n\nfunc ExampleSort() {\n\tlist := []int{2, 1, 3}\n\n\tsort(list)\n\n\tfmt.Println(list)\n\n\t// Output:\n\t// [1 2 3]\n}\n"
},
{
"alpha_fraction": 0.4936886429786682,
"alphanum_fraction": 0.6016830205917358,
"avg_line_length": 10.68852424621582,
"blob_id": "fcf4e8fd1dbbcbb8d9a7508f9837ecb06db842f6",
"content_id": "83e4dd7bf107dd80dcee8152ea9f88e634d4385b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 713,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 61,
"path": "/selfnumber/selfnumber_test.go",
"repo_name": "greenmonn/coding-kata",
"src_encoding": "UTF-8",
"text": "package selfnumber\n\nimport \"fmt\"\n\nfunc ExampleNewSequence() {\n\tfmt.Println(NewSequence(1, 5))\n\n\t// Output:\n\t// [1 2 3 4]\n}\n\nfunc ExampleDigits() {\n\tfmt.Println(digits(123))\n\n\t// Output:\n\t// [3 2 1]\n}\n\nfunc ExampleSumOfElements() {\n\tlist := []int{1, 2, 3}\n\tfmt.Println(sumOfElements(list))\n\n\t// Output:\n\t// 6\n}\n\nfunc ExampleGenerate() {\n\tfmt.Println(generate(91))\n\n\t// Output:\n\t// 101\n}\n\nfunc ExampleSum() {\n\tsum := Sum(1, 32)\n\n\tref := 1 + 3 + 5 + 7 + 9 + 20 + 31\n\n\tfmt.Println(sum == ref)\n\n\t// Output:\n\t// true\n}\n\nfunc ExampleSumTo5000() {\n\tsum := Sum(1, 5000)\n\n\tfmt.Println(sum)\n\n\t// Output:\n\t// 1227365\n}\n\nfunc ExampleSumTo5000000() {\n\tsum := Sum(1, 5000000)\n\n\tfmt.Println(sum)\n\n\t// Output:\n\t// 1222233933479\n}\n"
},
{
"alpha_fraction": 0.604236364364624,
"alphanum_fraction": 0.6622073650360107,
"avg_line_length": 13.03125,
"blob_id": "037b9509b28d5278de0036e3b22d5ede45cacf33",
"content_id": "ee0e876c1035765c9ec4ad0261b1680cb971a718",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 897,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 64,
"path": "/roman_numerals/roman_numerals_test.go",
"repo_name": "greenmonn/coding-kata",
"src_encoding": "UTF-8",
"text": "package roman_numerals\n\nimport \"fmt\"\n\nfunc ExampleRomanNumerals() {\n\tfmt.Println(Roman(1))\n\tfmt.Println(Roman(2))\n\tfmt.Println(Roman(3))\n\tfmt.Println(Roman(4))\n\tfmt.Println(Roman(5))\n\tfmt.Println(Roman(7))\n\n\t// Output:\n\t// I\n\t// II\n\t// III\n\t// IV\n\t// V\n\t// VII\n}\n\nfunc ExampleRomanNumeralsTwoDigits() {\n\tfmt.Println(Roman(10))\n\tfmt.Println(Roman(39))\n\tfmt.Println(Roman(67))\n\n\t// Output:\n\t// X\n\t// XXXIX\n\t// LXVII\n}\n\nfunc ExampleRomanNumeralsThreeDigits() {\n\tfmt.Println(Roman(246))\n\tfmt.Println(Roman(207))\n\n\t// Output:\n\t// CCXLVI\n\t// CCVII\n}\n\nfunc ExampleRomanNumeralsFourDigits() {\n\tfmt.Println(Roman(1066))\n\tfmt.Println(Roman(1776))\n\tfmt.Println(Roman(1954))\n\n\t// Output:\n\t// MLXVI\n\t// MDCCLXXVI\n\t// MCMLIV\n}\n\nfunc ExampleUpperBound() {\n\tfmt.Println(boundary(1))\n\tfmt.Println(boundary(30))\n\tfmt.Println(boundary(103))\n\tfmt.Println(boundary(899))\n\n\t// Output:\n\t// 10\n\t// 100\n\t// 1000\n\t// 1000\n}"
},
{
"alpha_fraction": 0.5654761791229248,
"alphanum_fraction": 0.6547619104385376,
"avg_line_length": 24.884614944458008,
"blob_id": "535b42132313e3dda91fbd0b9f588767234a3891",
"content_id": "e7d6f6d094ffd16380fb056864f64fd78022dbf3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 672,
"license_type": "no_license",
"max_line_length": 71,
"num_lines": 26,
"path": "/selfnumber_py/selfnumber_test.py",
"repo_name": "greenmonn/coding-kata",
"src_encoding": "UTF-8",
"text": "import unittest\n\ndef sumOfSelfNumbers(_from, _to):\n notSelfNumbers = {d(i) for i in range(_to)}\n\n return sum(set(range(_from, _to)) - notSelfNumbers)\n\ndef d(n):\n return n + sumOfDigits(n)\n\ndef sumOfDigits(n):\n if n < 10:\n return n\n\n return sumOfDigits(n//10) + n % 10\n\n\nclass SelfNumberTest(unittest.TestCase):\n def test_sum_of_selfnumbers(self):\n self.assertEqual(1+3+5+7+9, sumOfSelfNumbers(1, 10))\n self.assertEqual(1227365, sumOfSelfNumbers(1, 5000))\n self.assertEqual(1222233933479, sumOfSelfNumbers(1, 5_000_000))\n\n def testGenerator(self):\n self.assertEqual(101, d(91))\n self.assertEqual(1003, d(1001))"
},
{
"alpha_fraction": 0.725806474685669,
"alphanum_fraction": 0.725806474685669,
"avg_line_length": 23.799999237060547,
"blob_id": "bb21fca186368fb47e348c65513af0f6873b571b",
"content_id": "6379ad18397d5dc3dd076ac95658c0b353192d42",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 124,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 5,
"path": "/selfnumber/selfnumber.go",
"repo_name": "greenmonn/coding-kata",
"src_encoding": "UTF-8",
"text": "package selfnumber\n\nfunc Sum(from int, to int) (sum int) {\n\treturn NewSequence(from, to).FilterSelfNumber(from, to).Sum()\n}\n"
},
{
"alpha_fraction": 0.7941176295280457,
"alphanum_fraction": 0.7941176295280457,
"avg_line_length": 16,
"blob_id": "53497e859a8e3f7b9bd04e01d13166b60643d580",
"content_id": "e8d83eeb0bee282ae8865a5b056646754b38177d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 42,
"license_type": "no_license",
"max_line_length": 19,
"num_lines": 2,
"path": "/README.md",
"repo_name": "greenmonn/coding-kata",
"src_encoding": "UTF-8",
"text": "# coding-kata\n코딩도장 in Artifriends\n"
},
{
"alpha_fraction": 0.5172753930091858,
"alphanum_fraction": 0.5686081051826477,
"avg_line_length": 14.119402885437012,
"blob_id": "028c7d798ca1a02ca246bd53c361d8ce64905601",
"content_id": "706ca4cbe55121a533079a8c85f20d20e93c46ec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Go",
"length_bytes": 1013,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 67,
"path": "/roman_numerals/roman_numerals.go",
"repo_name": "greenmonn/coding-kata",
"src_encoding": "UTF-8",
"text": "package roman_numerals\n\n// list := [I, V, X, L, C, D, M]\n\nvar (\n\tm = map[int]string{\n\t\t0: \"\",\n\t\t1: \"I\",\n\t\t5: \"V\",\n\t\t10: \"X\",\n\t\t50: \"L\",\n\t\t100: \"C\",\n\t\t500: \"D\",\n\t\t1000: \"M\",\n\t}\n)\n\nfunc boundary(number int) int {\n\tbounds := []int{10, 100, 1000}\n\n\tfor _, bound := range bounds {\n\t\tif number < bound {\n\t\t\treturn bound\n\t\t}\n\t}\n\n\treturn 100000\n}\n\nfunc Roman(number int) (romanNumeral string) {\n\tbound := boundary(number)\n\thalf := bound/2\n\tbase := bound/10\n\n\tif bound > 1000 {\n\t\treturn m[1000] + Roman(number-1000)\n\t}\n\n\tif number < half - base {\n\t\tfor i := 0; i < number/base; i++ {\n\t\t\tromanNumeral += m[base]\n\t\t}\n\n\t\tremains := number % base\n\n\t\tif remains == 0 {\n\t\t\treturn romanNumeral\n\t\t} else {\n\t\t\treturn romanNumeral + Roman(number % base)\n\t\t}\n\n\t} else if number < bound/2 {\n\n\t\treturn m[base] + m[half] + Roman(number - half + base)\n\n\t} else if number < bound - bound/10 {\n\n\t\treturn m[half] + Roman(number - half)\n\n\t} else if number < bound {\n\n\t\treturn m[base] + m[bound] + Roman(number - bound + base)\n\n\t}\n\n\treturn\n}\n"
}
] | 11 |
juliafox8/cm-codes | https://github.com/juliafox8/cm-codes | 4440cd75cfa143c35edcafd87330c0940b0d2532 | 7386eb7359a881dc8c9d8a275f7f53d2c4c5ce33 | 9f798471407af5567c9daf3ffc64922142808404 | refs/heads/main | 2023-07-13T22:22:09.959756 | 2021-08-30T15:42:38 | 2021-08-30T15:42:38 | 401,397,109 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5449735522270203,
"alphanum_fraction": 0.5608465671539307,
"avg_line_length": 28.83333396911621,
"blob_id": "e53a15e191c443132387a09dc2547961bd1116d6",
"content_id": "42fa0affef04a02672f1de358695259b83ba42e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 189,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 6,
"path": "/Lab_2/q4.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def digitSum(number):\r\n num_string = str(number) \r\n if len(num_string) == 1:\r\n return number\r\n else:\r\n return int(num_string[0]) + int(digitSum(num_string[1:]))\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.4883720874786377,
"alphanum_fraction": 0.5348837375640869,
"avg_line_length": 20.5,
"blob_id": "82f9ef401a7342e21e10b29052c7386a38e7b5aa",
"content_id": "d9c8ee1b492d0357c0a4d8504a6094046f525f9a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 43,
"license_type": "no_license",
"max_line_length": 22,
"num_lines": 2,
"path": "/Programming_a6/right_index.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def right_index(i):\r\n return (i * 2) + 2"
},
{
"alpha_fraction": 0.5592330098152161,
"alphanum_fraction": 0.5933806300163269,
"avg_line_length": 33.61818313598633,
"blob_id": "72b58d01675f52a808193a01d22c3573920d87d5",
"content_id": "708640fac30c3fbcd81b82890a6dd2cdd8ee12f7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3807,
"license_type": "no_license",
"max_line_length": 143,
"num_lines": 110,
"path": "/Programming_a6/test_pa6.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "from triplets import triplets\nfrom left_index import left_index\nfrom right_index import right_index\nfrom parent_index import parent_index\nfrom leaf import is_leaf\nfrom missing_child import missing_child\nfrom bst_search import bst_search\n\ndef test_all():\n print(\"Testing all functions... \\n\")\n test_triplets()\n test_left_index()\n test_right_index()\n test_parent_index()\n test_is_leaf()\n test_missing_child()\n test_bst_search()\n print(\"All tests completed! \\n\")\n\ndef test_triplets():\n print(\"Testing triplets...\")\n assert(triplets({}) == 0)\n assert(triplets({1: \"a\", 2: \"a\", 3:\"a\"}) == 1)\n assert(triplets({1: 'a', 2: 'b', 3: 'a'}) == 0)\n assert(triplets({1: 'a', 2: 'b', 3: 'c', 4: 'c', 5: 'b'}) == 0)\n letters = {1: \"z\", 2: \"z\", 3: \"z\", 4: \"z\"}\n assert(triplets(letters) == 0)\n letters[4] = \"a\"\n letters[5] = \"a\"\n letters[6] = \"a\"\n assert(triplets(letters) == 2)\n print(\"Finished testing triplets!\")\n\ndef test_left_index():\n print(\"Testing left_index...\")\n assert(left_index(0) == 1)\n assert(left_index(1) == 3)\n assert(left_index(2) == 5)\n assert(left_index(3) == 7)\n assert(left_index(4) == 9)\n assert(left_index(5) == 11)\n print(\"Finished testing left_index!\")\n\ndef test_right_index():\n print(\"Testing right_index...\")\n assert(right_index(0) == 2)\n assert(right_index(1) == 4)\n assert(right_index(2) == 6)\n assert(right_index(3) == 8)\n assert(right_index(4) == 10)\n assert(right_index(5) == 12)\n print(\"Finished testing right_index!\")\n\ndef test_parent_index():\n print(\"Testing parent_index...\")\n assert(parent_index(1) == 0)\n assert(parent_index(2) == 0)\n assert(parent_index(6) == 2)\n assert(parent_index(7) == 3)\n assert(parent_index(12) == 5)\n assert(parent_index(11) == 5)\n assert(parent_index(13) == 6)\n print(\"Finished testing parent_index!\")\n\ndef test_is_leaf():\n print(\"Testing is_leaf...\")\n tree = [\"alpha\"]\n assert(is_leaf(tree, 0) == True)\n a = [\"alpha\", \"bravo\", \"charlie\", \"delta\", \"echo\", \"foxtrot\", \"golf\", \"hotel\", \"india\", \"juliett\", \"kilo\", \"lima\", \"mike\", \"nova\", \"oscar\"]\n assert(is_leaf(a, 0) == False)\n assert(is_leaf(a, 13) == True)\n assert(is_leaf(a, 10) == True)\n assert(is_leaf(a, 7) == True)\n assert(is_leaf(a, 6) == False)\n assert(is_leaf(a, 2) == False)\n print(\"Finished testing is_leaf!\")\n\n\ndef test_missing_child():\n print(\"Testing missing_child...\")\n a = [\"alpha\", \"bravo\", \"charlie\", \"delta\", \"echo\", \"foxtrot\", None, \"hotel\", \"india\", \"juliet\", None, \"lima\", \"mike\", None, None]\n assert(missing_child(a, 0) == [\"echo\", \"charlie\"])\n assert(missing_child(a, 1) == [\"echo\"])\n assert(missing_child(a, 2) == [\"charlie\"])\n assert(missing_child(a, 5) == [])\n assert(missing_child(a, 9) == [])\n b = [\"apple\", \"banana\", \"cherry\", None, \"date\", None, None]\n assert(missing_child(b, 0) == [\"banana\"])\n c = [\"aardvark\", \"bear\", None, \"cat\", \"dog\", None, None, \"eel\", None, None, None, None, None, None, None]\n assert(missing_child(c, 0) == [\"aardvark\", \"cat\"])\n print(\"Finished testing missing_child!\")\n\ndef test_bst_search():\n print(\"Testing bst_search...\")\n bstree = [84,41,96,24,52,91,98,10,26,43,None,85,94,None,None]\n assert(bst_search(bstree, 52) == True)\n assert(bst_search(bstree, 51) == False)\n assert(bst_search(bstree, 97) == False)\n assert(bst_search(bstree, 84) == True)\n assert(bst_search(bstree, 98) == True)\n assert(bst_search(bstree, 94) == True)\n assert(bst_search(bstree, 41) == True)\n assert(bst_search(bstree, 42) == False)\n assert(bst_search(bstree, 122) == False)\n bstree = [1]\n assert(bst_search(bstree, 1) == True)\n assert(bst_search(bstree, 2) == False)\n print(\"Finished testing bst_search!\")\n\ntest_all()"
},
{
"alpha_fraction": 0.39293140172958374,
"alphanum_fraction": 0.4261954128742218,
"avg_line_length": 13.933333396911621,
"blob_id": "6af34fed2b3c72f59833ac212ae6399c2f085847",
"content_id": "2b44302d62de730ae0cc7e1178ac47a01d3941a1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 481,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 30,
"path": "/Programming_a4/sum.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def sum(n):\r\n sum = 0 \r\n for i in range(1, n +1):\r\n sum = sum + i\r\n return sum\r\n\r\nprint(sum(6))\r\n\r\ndef sum2(lst):\r\n sum = 0 \r\n for i in range (len(lst)):\r\n sum = sum + lst[i]\r\n return sum \r\n\r\nprint(sum2([2,4, 6]))\r\n\r\ndef sum3(lst):\r\n sum = 0 \r\n for num in lst:\r\n sum = sum + num\r\n return sum \r\n\r\n\r\ndef sum4(lst):\r\n sum = 0\r\n i = 0 \r\n while i < (len(lst)):\r\n sum = sum + lst[i]\r\n i = i + 1\r\n return sum \r\n\r\n"
},
{
"alpha_fraction": 0.4962962865829468,
"alphanum_fraction": 0.5111111402511597,
"avg_line_length": 24.600000381469727,
"blob_id": "f5fc4cbcb6df7d25466e7a764868820839a590e3",
"content_id": "901a5cbd5f40fd23f5843076fe8015b61591002e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 135,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 5,
"path": "/Programming_activity4/first_even.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def first_even(numbers):\r\n for i in range(len(numbers)):\r\n if numbers[i] % 2 == 0:\r\n return i\r\n return None\r\n\r\n"
},
{
"alpha_fraction": 0.4177215099334717,
"alphanum_fraction": 0.44936707615852356,
"avg_line_length": 28.799999237060547,
"blob_id": "c1d128662f5da1387d9905af776dd09c5f5523b5",
"content_id": "36c801c5412036c01cb293452ddbfaae2d22fdb1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 158,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 5,
"path": "/Programming_a2/list_cubic.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "import math\r\n\r\ndef list_cubic(a, b, c, d):\r\n for x in range (0, 21):\r\n print(int((a * math.pow(x, 3)) + (b * (math.pow(x, 2))) + (c * x) + d))\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.49197861552238464,
"alphanum_fraction": 0.5080214142799377,
"avg_line_length": 30.81818199157715,
"blob_id": "bc2e0cdadba32b68575e34376c673110b5984919",
"content_id": "80b6bb5df2a08e180cf78565ba70f67ec6d579fe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 374,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 11,
"path": "/Programming_a3/wages.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def pay(wage, hours):\r\n extra_hours = hours - 40\r\n if extra_hours <= 0:\r\n return wage * hours\r\n else:\r\n return ((1.5 * wage) * extra_hours) + (wage * (hours - extra_hours))\r\n\r\ndef pay_table(wage, hours_list):\r\n for i in range (len(hours_list)):\r\n hours = hours_list[i]\r\n print(\"Week \", (i + 1), \" : \", pay(wage, hours)) \r\n\r\n\r\n\r\n\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.5341615080833435,
"alphanum_fraction": 0.5714285969734192,
"avg_line_length": 18.375,
"blob_id": "831ed6f593805ec59ada084f336242617a8df22b",
"content_id": "f94ad682c701f30cbc08415a468f1d1e19f417f7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 161,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 8,
"path": "/ages.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "ages = {\"julia\" : 17, \"monica\" : 15, \"sylvia\": 7}\r\n\r\n# print(ages[\"monica\"])\r\n\r\ndef birthday(name):\r\n ages[name] = ages[name] + 1\r\n\r\nprint(birthday(\"monica\"))"
},
{
"alpha_fraction": 0.40188172459602356,
"alphanum_fraction": 0.426075279712677,
"avg_line_length": 24.64285659790039,
"blob_id": "895f0d9bb03fadb540d0603c673b75d9ab545ff4",
"content_id": "a8399d8c38f71f483056e8b975dcd87e44eb175e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 744,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 28,
"path": "/Programming_a4/sieven.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def sift(lst,k): \r\n i = 0 \r\n while i < len(lst): \r\n if lst[i] != None and lst[i] % k == 0: \r\n lst[i] = None \r\n i = i + 1 \r\n return lst \r\n\r\ndef sift_wrong(lst,k):\r\n # eliminates multiples of k \r\n for i in range(0,len(lst)):\r\n if lst[i] % k == 0:\r\n lst.remove(lst[i])\r\n return lst\r\n\r\nprint(sift([1, 2, 3], 2))\r\nprint(sift_wrong([1, 2, 3], 2))\r\n\r\ndef sieve(n): \r\n numlist = list(range(2, n+1)) \r\n primes = [] \r\n for i in range(0, len(numlist)): \r\n if numlist[i] != None: \r\n primes.append(numlist[i]) \r\n sift(numlist, numlist[i]) \r\n return primes.pop()\r\n\r\nprint(sieve(20))"
},
{
"alpha_fraction": 0.4189189076423645,
"alphanum_fraction": 0.5180180072784424,
"avg_line_length": 22.88888931274414,
"blob_id": "039fd2c5573ae6414a85f63e17d06018565b931b",
"content_id": "ff7f6095d47232cb0c9c000cc310b9a4ed0b54c3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 222,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 9,
"path": "/Programming_a5/shuffle.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def shuffle(list1, list2):\r\n if list1 == [] or list2 == []:\r\n return []\r\n \r\n return [list1[0], list2[0]] + shuffle(list1[1:], list2[1:])\r\n\r\nlist1 = [1, 3, 5]\r\nlist2 = [2, 4, 6]\r\nprint(shuffle(list1, list2))"
},
{
"alpha_fraction": 0.3807574212551117,
"alphanum_fraction": 0.45240533351898193,
"avg_line_length": 24.45945930480957,
"blob_id": "5905eb448f6de50a1401cdb8de1c662f9fbf640a",
"content_id": "72ec781ee6c52eb2d036c343584ddb199ce87045",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 977,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 37,
"path": "/Lab6/sum_odds2.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def sum_odds2(x):\r\n #base case\r\n if x == []:\r\n return 0\r\n\r\n #recursive\r\n if isinstance(x[0], int) == True:\r\n #isinstance checks if the number is an integer\r\n if (x[0] % 2 == 0):\r\n return sum_odds2(x[1:])\r\n elif (x[0] % 2 == 1):\r\n return x[0] + sum_odds2(x[1:])\r\n \r\n #isinstance checks if the number is a list\r\n if isinstance(x[0], list) == True:\r\n return sum_odds2(x[0]) + sum_odds2(x[1:])\r\n\r\n\r\ndef test_sum_odds2(): \r\n print(\"Testing sum_odds2()...\", end=\"\")\r\n x0 = [[1, 2], 3]\r\n assert(sum_odds2(x0) == 4)\r\n x1 = [1, [2, 3]]\r\n assert(sum_odds2(x1) == 4)\r\n x2 = []\r\n assert(sum_odds2(x2) == 0)\r\n x3 = [2, [3], 1, [4]]\r\n assert(sum_odds2(x3) == 4)\r\n x4 = [2, [4, 6], 8]\r\n assert(sum_odds2(x4) == 0)\r\n x5 = [1, [2, [3, 4], 5], 6]\r\n assert(sum_odds2(x5) == 9)\r\n x6 = [[[], []], [[[]]]]\r\n assert(sum_odds2(x6) == 0)\r\n print(\"Passed!\")\r\n\r\ntest_sum_odds2()"
},
{
"alpha_fraction": 0.40909090638160706,
"alphanum_fraction": 0.4220779240131378,
"avg_line_length": 19.428571701049805,
"blob_id": "1eeeec931a12ddfd88df2b69faf2c93cd1b0afe4",
"content_id": "0832a407db2bf7191ee3d139f58aeca6ae0c702a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 154,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 7,
"path": "/Lab6/blast_off.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def blast_off(n):\r\n if (n == 0):\r\n print(\"blast_off\")\r\n return None \r\n else: \r\n print(n)\r\n return (blast_off(n-1))\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.5023696422576904,
"alphanum_fraction": 0.5308057069778442,
"avg_line_length": 32.33333206176758,
"blob_id": "b4df7c1763cfec343c5b21aa787585d20b880f3c",
"content_id": "027fcaa624d249d8460f82c829fc2676d0a15758",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 211,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 6,
"path": "/Programming_activity4/num_even.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def num_even(numbers):\r\n count = 0 \r\n for i in range (len(numbers)):\r\n if numbers[i] % 2 == 0:\r\n count += 1 #increment by 1 (facy shmacy adding count = count + 1)\r\n return count \r\n\r\n\r\n"
},
{
"alpha_fraction": 0.5555555820465088,
"alphanum_fraction": 0.5634920597076416,
"avg_line_length": 27.714284896850586,
"blob_id": "e26cff4aa05e2a397de5ccd7daad05c84e4285f2",
"content_id": "388d50adf50f59a06046fc2030099df6ed158b7b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 630,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 21,
"path": "/Programming_a3/vacation.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def vacation(places, temps, costs, temp_min):\r\n indexs_with_high_enough_temps = []\r\n\r\n for i in range (len(temps)):\r\n temp = temps[i]\r\n #looking up temp and setting it to the 1,2,3 i value (ith)\r\n if temp >= temp_min: \r\n indexs_with_high_enough_temps.append(i)\r\n \r\n if len(indexs_with_high_enough_temps) == 0:\r\n return \"Home\"\r\n\r\n\r\n min_cost_index = indexs_with_high_enough_temps[0] \r\n\r\n for i in indexs_with_high_enough_temps:\r\n cost= costs[i]\r\n if cost <= costs[min_cost_index]:\r\n min_cost_index = i \r\n\r\n return(places[min_cost_index])\r\n\r\n "
},
{
"alpha_fraction": 0.5865853428840637,
"alphanum_fraction": 0.5865853428840637,
"avg_line_length": 30.719999313354492,
"blob_id": "2f172a371d7a01b53996db8377e456d26a6f76dc",
"content_id": "b83001a5e54c593ee2ddbf3eabae9c5f5fcd6915",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 820,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 25,
"path": "/Programming_a6/missing_child.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "from left_index import left_index\r\nfrom right_index import right_index\r\n\r\ndef is_leaf(tree, i):\r\n l = left_index(i)\r\n r = right_index(i)\r\n if l < len(tree) and tree[l] != None:\r\n return False\r\n if r < len(tree) and tree[r] != None:\r\n return False\r\n else:\r\n return True\r\n\r\n\r\ndef missing_child(tree, i):\r\n if is_leaf(tree, i):# base case\r\n return []\r\n l = left_index(i)\r\n r = right_index(i)\r\n has_left_kid = l < len(tree) and tree[l] != None\r\n has_right_kid = r < len(tree) and tree[r] != None\r\n if has_left_kid and has_right_kid: #recursive check if has missing child\r\n return missing_child(tree, l) + missing_child(tree, r)\r\n # oh no has missing child add below to list \r\n return [tree[i]] + (missing_child(tree, l) + missing_child(tree, r))\r\n\r\n"
},
{
"alpha_fraction": 0.44078946113586426,
"alphanum_fraction": 0.47236841917037964,
"avg_line_length": 21.8125,
"blob_id": "2707d881dbaa019700dbdc458b5dd6cbbdd25d43",
"content_id": "9bd12d47b4ce058464c71deca087b5cedb3b113c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 760,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 32,
"path": "/written_exam.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "# def search_pair(items):\r\n# for i in range (0, ):\r\n# assert i + 1 < len(items)\r\n# if items[i] > items [i + 1]:\r\n# return i \r\n# return None\r\n\r\n# items = [1, 3, 4, 6, 4, 7, 6]\r\n# print(search_pair(items))\r\n\r\n# def mystery1(m, n):\r\n# i = 0 \r\n# while i < n:\r\n# i = i + 1\r\n# print(i ** m, end = \" \")\r\n# return None\r\n\r\n# mystery_val = mystery1(2, 3)\r\n# if mystery_val == 9:\r\n# print (\"here is nine: \", mystery_val)\r\n# else:\r\n# print(\"here im: value\", mystery_val)\r\n\r\ndef is_sorted(my_list):\r\n index = 0 \r\n while index < (len(my_list) - 1) :\r\n if my_list[index] > my_list[index + 1]:\r\n return False\r\n index = index + 1\r\n return True \r\n\r\nprint(is_sorted([1, 2, 3]))"
},
{
"alpha_fraction": 0.5471698045730591,
"alphanum_fraction": 0.5606468915939331,
"avg_line_length": 25.33333396911621,
"blob_id": "18e6cdacb606b4a764155f1a608324fa0894b465",
"content_id": "879b3b24ec3536fa15979d1a96c108ec5fa4ef22",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 742,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 27,
"path": "/Programming_a5/select_strings.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def select_strings(names, letter):\r\n #base case \r\n if names == []:\r\n return []\r\n first_name = names[0]\r\n\r\n if first_name == '':\r\n return select_strings(names[1:], letter)\r\n\r\n if first_name[-1] == letter:\r\n return [first_name] + select_strings(names[1:], letter) \r\n return select_strings(names[1:], letter)\r\n\r\n\r\ndef select_strings_backward(names, letter):\r\n #base case \r\n if names == []:\r\n return []\r\n last_name = names[-1]\r\n\r\n if last_name == '':\r\n return select_strings_backward(names[:-1], letter)\r\n\r\n if last_name[-1] == letter:\r\n return [last_name] + select_strings_backward(names[:-1], letter) \r\n \r\n return select_strings_backward(names[:-1], letter)\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.5054545402526855,
"alphanum_fraction": 0.5236363410949707,
"avg_line_length": 27,
"blob_id": "92c9450afa7699d2d92024fb560d0d8fb5737de2",
"content_id": "9ffa03bf1ae0cb8384e80ddb343e84d56f4eac60",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 275,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 9,
"path": "/Programming_a6/triplets.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def triplets(d):\r\n unique= {}\r\n tripletsnum = 0\r\n for value in d.values():\r\n unique[value] = unique.get(value, 0) + 1\r\n for count in unique.values():\r\n if count == 3:\r\n tripletsnum = tripletsnum + 1\r\n return tripletsnum\r\n \r\n\r\n\r\n"
},
{
"alpha_fraction": 0.4232558012008667,
"alphanum_fraction": 0.45116278529167175,
"avg_line_length": 19.700000762939453,
"blob_id": "b53f95da2c6cab332110f3fd054bc0d3b270a251",
"content_id": "d400ad3aa836e9c8f5a5633b09d4d04a9427f6d0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 215,
"license_type": "no_license",
"max_line_length": 29,
"num_lines": 10,
"path": "/Programming_a4/test9.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def findmin(lst):\r\n min_num = lst[0]\r\n i = 1\r\n while i < len(lst): \r\n if lst[i] < min_num:\r\n min_num = lst[i]\r\n i = i + 1\r\n return lst.index(min_num)\r\n\r\nprint(findmin([1, 2, 3]))"
},
{
"alpha_fraction": 0.27272728085517883,
"alphanum_fraction": 0.3014354109764099,
"avg_line_length": 21.44444465637207,
"blob_id": "c14938f731ffef0aae331d85a5cfb980b3aa07e4",
"content_id": "a518e1ce9cb9693add9ecba49f48afdf2ccba799",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 209,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 9,
"path": "/written_exam2/sec1.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def bad(n): \r\n if n <= 1: \r\n return True \r\n elif n % 2 == 0: \r\n return bad(n/2) \r\n else: \r\n return bad(n/1) \r\n\r\nprint(bad(6))"
},
{
"alpha_fraction": 0.47826087474823,
"alphanum_fraction": 0.52173912525177,
"avg_line_length": 22,
"blob_id": "6138542c9fb85352c3aea9c0c16d7728abfa50d6",
"content_id": "1de15b9aeb784f4e46dcf5949b3ff7500483e667",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 46,
"license_type": "no_license",
"max_line_length": 23,
"num_lines": 2,
"path": "/Programming_a6/parent_index.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def parent_index(i):\r\n return (i - 1) // 2"
},
{
"alpha_fraction": 0.5380434989929199,
"alphanum_fraction": 0.570652186870575,
"avg_line_length": 20.875,
"blob_id": "3a470b060a5ef7b07551548b0736d251e8dfdfa6",
"content_id": "a841d8626d5cfed32bc90e361dcd1404cb25d41d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 184,
"license_type": "no_license",
"max_line_length": 29,
"num_lines": 8,
"path": "/Lab_2/q3.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "from random import randint\r\n\r\ndef roll_20_sided(number):\r\n value = 0 \r\n for i in range(number): \r\n roll = randint(1, 20)\r\n value = value + roll\r\n return value \r\n"
},
{
"alpha_fraction": 0.41860464215278625,
"alphanum_fraction": 0.447674423456192,
"avg_line_length": 21.066667556762695,
"blob_id": "ef912175ba12aa23652f361c713f6d5c0d44b8cc",
"content_id": "728f587f439680dbcd4a7a396aeb653b0777b6e2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 344,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 15,
"path": "/hi.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def bsearch(items, key):\r\n low = 0\r\n high = len(items) - 1\r\n while low <= high:\r\n mid = (low + high) // 2\r\n if items[mid] == key:\r\n return mid\r\n if key > items[mid]:\r\n low = mid + 1\r\n else:\r\n high = mid - 1\r\n return None\r\n\r\nitems = range(0, 16)\r\nprint(bsearch(items, 19))"
},
{
"alpha_fraction": 0.5766738653182983,
"alphanum_fraction": 0.5788336992263794,
"avg_line_length": 28.733333587646484,
"blob_id": "4cbd17836db7ee1e5edd4ef3d1e3ec20a6c000eb",
"content_id": "561efeba75672e94e928074f766a4c39edda2100",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 463,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 15,
"path": "/Programming_a6/bst_search.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "from right_index import right_index\r\nfrom left_index import left_index\r\n\r\n\r\ndef bst_search(tree, key):\r\n curr_index = 0 \r\n while curr_index < len(tree) and tree[curr_index] != None:\r\n curr_value = tree[curr_index]\r\n if curr_value == key:\r\n return True\r\n if key < curr_value:\r\n curr_index = left_index(curr_index)\r\n if key > curr_value:\r\n curr_index = right_index(curr_index)\r\n return False\r\n\r\n"
},
{
"alpha_fraction": 0.531862735748291,
"alphanum_fraction": 0.5392156839370728,
"avg_line_length": 27.285715103149414,
"blob_id": "5406bedf48b5f0c039686141a79b291313b89993",
"content_id": "86f4d9927dba8225b5fa41f0076c02b263331268",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 408,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 14,
"path": "/Programming_activity4/second_largest.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def second_largest(values):\r\n max_start = None\r\n max_yay = None \r\n for num in range (len(values)):\r\n if max_start == None or values[num] > max_start:\r\n max_yay = max_start\r\n max_start = values[num]\r\n elif max_yay == None or values[num] > max_yay:\r\n max_yay = values[num]\r\n # if values[num] \r\n\r\n return max_yay\r\n\r\nprint(second_largest([10, 1]))"
},
{
"alpha_fraction": 0.4935622215270996,
"alphanum_fraction": 0.5214592218399048,
"avg_line_length": 21.100000381469727,
"blob_id": "2f63ce586237af0d2f2c40421c5571e43eed73bf",
"content_id": "2cd6c046d52c19bcb8ca8827c733b968cd004b74",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 466,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 20,
"path": "/Programming_activity4/counting_sort.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def counting_sort(keys, max_key):\r\n counts = [0] * (max_key + 1) \r\n for k in keys:\r\n counts[k] += 1 \r\n result = []\r\n for k in range(0, max_key + 1):\r\n count = counts[k]\r\n for n in range(count):\r\n result.append(k)\r\n return result \r\n\r\nfrom time import time \r\n\r\ndef time_sort(n):\r\n stuff = list(range(n))\r\n start = time()\r\n counting_sort(stuff, n)\r\n return time() - start \r\n\r\n# print(time_sort(10000000))\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.31475409865379333,
"alphanum_fraction": 0.33114755153656006,
"avg_line_length": 22.66666603088379,
"blob_id": "16fddd39ecab689e138253095b2b20cc04c731f8",
"content_id": "678862fd460eb7d31fb05f730cc237fe48d57975",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 305,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 12,
"path": "/Programming_a3/make_triangle.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def make_triangle(n):\r\n for i in range(0, n):\r\n for j in range(0, i+1):\r\n if j == i:\r\n print('* ', end='')\r\n elif j == 0:\r\n print ('* ', end= '')\r\n elif i == (n - 1):\r\n print ('* ', end= '')\r\n else:\r\n print (\" \", end='')\r\n print()\r\n \r\n\t\r\n"
},
{
"alpha_fraction": 0.47986191511154175,
"alphanum_fraction": 0.5143843293190002,
"avg_line_length": 28.964284896850586,
"blob_id": "d92f507b0a8ff4013dd84647ec2ea0641b37e126",
"content_id": "79637a640a0e988727165b3bcb260d4e43065055",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 869,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 28,
"path": "/Lab6/count_a_words.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def count_a_words(lst):\r\n if lst == []:\r\n return 0\r\n if isinstance(lst[0], str) == True:\r\n if (lst[0] != \"\") and (lst[0][0] == 'a'):\r\n return 1 + count_a_words(lst[1:])\r\n\r\n return count_a_words(lst[1:])\r\n\r\ndef test_count_a_words(): \r\n print(\"Testing count_a_words()...\", end=\"\")\r\n lst0 = [1, \"apple\", \"foo\", \"anaconda\", True, []]\r\n assert(count_a_words(lst0) == 2)\r\n lst1 = [\"alligator\"]\r\n assert(count_a_words(lst1) == 1)\r\n lst2 = [True] \r\n assert(count_a_words(lst2) == 0)\r\n lst3 = [\"alligator\", \"anaconda\"]\r\n assert(count_a_words(lst3) == 2)\r\n lst4 = [\"foo\", \"bar\", \"hello\", \"world\"] \r\n assert(count_a_words(lst4) == 0)\r\n lst5 = []\r\n assert(count_a_words(lst5) == 0)\r\n lst6 = [\"Alligator\", \"alligator\"]\r\n assert(count_a_words(lst6) == 1)\r\n print(\"Passed!\")\r\n\r\ntest_count_a_words()\r\n "
},
{
"alpha_fraction": 0.39498433470726013,
"alphanum_fraction": 0.4561128616333008,
"avg_line_length": 22.538461685180664,
"blob_id": "9d9a82144218ee3b12dfdae71131ae264a738158",
"content_id": "071e135dffed9f2867a51e6cfc85a4bfbd9b9aa4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 638,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 26,
"path": "/Lab6/sum_odds.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def sum_odds(x):\r\n #base case\r\n if x == []:\r\n return 0 \r\n #recursive\r\n elif (x[0] % 2 == 0):\r\n return sum_odds(x[1:])\r\n #excludes the first index at the begining of the list\r\n elif (x[0] % 2 != 0):\r\n return x[0] + sum_odds(x[1:])\r\n\r\ndef test_sum_odds(): \r\n print(\"Testing sum_odds()...\", end=\"\")\r\n x0 = []\r\n assert(sum_odds(x0) == 0)\r\n x1 = [5]\r\n assert(sum_odds(x1) == 5)\r\n x2 = [1, 2, 3]\r\n assert(sum_odds(x2) == 4)\r\n x3 = [2, 4, 6, 8]\r\n assert(sum_odds(x3) == 0)\r\n x4 = [1, 2, 3, 4, 5, 6]\r\n assert(sum_odds(x4) == 9)\r\n print(\"Passed!\")\r\n\r\ntest_sum_odds()\r\n"
},
{
"alpha_fraction": 0.5679012537002563,
"alphanum_fraction": 0.5802469253540039,
"avg_line_length": 21,
"blob_id": "ce98d2814989b2c3b503257f1104b93c87be42c2",
"content_id": "bb8726e3f70b82b9e6b0f3b4fd04ed446ab22a87",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 162,
"license_type": "no_license",
"max_line_length": 46,
"num_lines": 7,
"path": "/Programming_activity4/geo_mean.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "import math \r\n\r\ndef geo_mean(numbers):\r\n product = 1 \r\n for n in numbers:\r\n product = product * n \r\n return math.pow(product, (1/len(numbers))) \r\n"
},
{
"alpha_fraction": 0.49234339594841003,
"alphanum_fraction": 0.56658935546875,
"avg_line_length": 26.01298713684082,
"blob_id": "5c1739105ba1ea980d7eed8a0bcfa033ef45d5b2",
"content_id": "b6fb4463f535ab7e53d3e95d2e419c33e87be14d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2155,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 77,
"path": "/Programming_a3/test_pa3.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "from largest import largest\r\nfrom wages import pay, pay_table\r\nfrom make_triangle import make_triangle\r\nfrom vacation import vacation\r\n\r\ndef test_all():\r\n test_largest()\r\n # test_pay()\r\n # test_pay_table()\r\n # test_vacation()\r\n # test_make_triangle()\r\n # print(\"All tests completed\")\r\n\r\ndef test_largest():\r\n assert largest(10,100,0)==100\r\n assert largest(300,100,500)==500\r\n assert largest(700,300,500)==700\r\n assert largest(-1,3,4)==4\r\n print (\"Largest: Test complete\")\r\n\r\ndef test_pay():\r\n assert pay(10,15) == 150\r\n assert pay(10,45) == 475.0\r\n assert pay(10,40) == 400\r\n assert pay(10,43) == 445.0\r\n assert pay(10,44) == 460.0\r\n print (\"Test complete\")\r\n\r\ndef test_pay_table():\r\n print (\"PAY TABLE: You must check visually that your output looks like the following:\")\r\n print (\"Week 1 : 150\")\r\n print (\"Week 2 : 460.0\")\r\n print (\"Week 3 : 475.0\")\r\n print (\"Week 1 : 0\")\r\n print (\"Week 2 : 100\")\r\n print (\"Week 3 : 800\")\r\n print (\"Week 4 : 1250.0\")\r\n print (\"Here is your output:\")\r\n pay_table(10,[15,44,45])\r\n pay_table(20,[0,5,40,55])\r\n print (\"Test complete\")\r\n\r\ndef test_vacation():\r\n places = [\"San Francisco\", \"New York\", \"Orlando\", \"Philadelphia\", \"Chicago\"]\r\n temps = [80,50,100,60,50]\r\n costs = [400,180,303,250,200]\r\n assert vacation(places,temps,costs,100)==\"Orlando\"\r\n assert vacation(places,temps,costs,59)==\"Philadelphia\"\r\n assert vacation(places,temps,costs,50)== \"New York\"\r\n assert vacation(places,temps,costs,130)== \"Home\"\r\n print (\"VACATION: Test complete\")\r\n\r\ndef test_make_triangle():\r\n print(\"MAKER TRIANGLE: You must check visually that your output looks like the following:\")\r\n print (\"*\")\r\n print (\"\\n\")\r\n print (\"*\")\r\n print (\"* *\")\r\n print (\"* * *\")\r\n print (\"\\n\")\r\n print (\"*\")\r\n print (\"* *\")\r\n print (\"* *\")\r\n print (\"* *\")\r\n print (\"* * * * *\")\r\n print(\"Here is your output:\")\r\n make_triangle(1)\r\n print (\"\\n\")\r\n make_triangle(3)\r\n print (\"\\n\")\r\n make_triangle(5)\r\n print (\"\\n\")\r\n print (\"Test complete\")\r\n\r\n\r\n\r\ntest_all()"
},
{
"alpha_fraction": 0.6141975522041321,
"alphanum_fraction": 0.6574074029922485,
"avg_line_length": 30.399999618530273,
"blob_id": "d52f604b97416d1dd310a7631dcbee1a991e10d5",
"content_id": "ed6e47cfa3e902bd3e3e4152ec800af9b8ca1cb4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 324,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 10,
"path": "/Programming_a2/cone.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "import math\r\n\r\ndef cone_volume(radius, height):\r\n return(1/3) * math.pi * math.pow(radius, 2) * height \r\n\r\nprint(\"volume for cone one: \", cone_volume(6, 12))\r\nprint(\"volume for cone 2\", cone_volume(6,8))\r\n\r\ndef print_object_volume():\r\n print (\"The total volume of the two cones is\", cone_volume(6,12) + cone_volume(6,8))\r\n"
},
{
"alpha_fraction": 0.4399038553237915,
"alphanum_fraction": 0.5480769276618958,
"avg_line_length": 24.90322494506836,
"blob_id": "07e462e863a7c18b4b9b40a8d83ae668d01b31c0",
"content_id": "843001d4b1a60c69937f1f2f4f0f321abd14ba0b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 832,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 31,
"path": "/Lab_2/q1.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "import tkinter\r\nfrom tkinter import Canvas \r\n\r\ndef olympic_rings():\r\n window = tkinter.Tk()\r\n c = Canvas(window, width = 600, height = 400)\r\n \r\n #blue\r\n c.create_oval(10, 10, 50, 50, fill= \"blue\")\r\n c.create_oval(15, 15, 45, 45, fill = \"white\")\r\n\r\n #black\r\n c.create_oval(50, 10, 90, 50, fill = \"black\")\r\n c.create_oval(55, 15, 85, 45, fill = \"white\")\r\n\r\n #red\r\n c.create_oval(90, 10, 130, 50, fill = \"red\", outline= \"black\")\r\n c.create_oval(95, 15, 125, 45, fill = \"white\",outline= \"black\" )\r\n \r\n #yellow\r\n c.create_oval(30, 45, 70, 85, fill = \"yellow\")\r\n c.create_oval(35, 50, 65, 80, fill = \"white\")\r\n \r\n #green\r\n c.create_oval(70, 45, 110, 85, fill = \"green\")\r\n c.create_oval(75, 50, 105, 80, fill = \"white\")\r\n \r\n c.pack()\r\n window.mainloop()\r\n\r\nolympic_rings()"
},
{
"alpha_fraction": 0.5368421077728271,
"alphanum_fraction": 0.5526315569877625,
"avg_line_length": 15.272727012634277,
"blob_id": "688d8911af249112ef1b14c79835917a71bcb1d4",
"content_id": "e2b23a940910bad4d11f8efd69030afdc26aef39",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 190,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 11,
"path": "/hello.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "import random \r\nfrom random import randint\r\n\r\ndef loaded_coin():\r\n unfair = randint(1, 4)\r\n if unfair >= 2:\r\n return \"H\"\r\n else:\r\n return \"T\"\r\n\r\nprint(loaded_coin())\r\n"
},
{
"alpha_fraction": 0.40316206216812134,
"alphanum_fraction": 0.4466403126716614,
"avg_line_length": 13.9375,
"blob_id": "e178506fe9344faf37cb458abb6b51ae7718c77c",
"content_id": "54082a9f3a20c677f1b2ec4eb74faf41d7042014",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 253,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 16,
"path": "/yay.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "# def f(n):\r\n# print(n, end= \" \")\r\n# if n < 3: \r\n# return n\r\n# else:\r\n# return f(n // 3) + f(n // 2)\r\n\r\n\r\n# print(f(12))\r\n\r\n\r\nimport random \r\nfrom random import randint \r\nvals = [1, 2, 3, 4, 5, 6]\r\n\r\nprint(randint(str(vals)))"
},
{
"alpha_fraction": 0.3776595890522003,
"alphanum_fraction": 0.3989361822605133,
"avg_line_length": 29.66666603088379,
"blob_id": "4785496bd2cff336bed3ac64e5d497b4dbfc4b85",
"content_id": "79487694743186a141d11aba4ec0d80c9a744267",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 188,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 6,
"path": "/lll5.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def f2(floatA, floatB): \r\n count = 0\r\n while(floatA < floatB):\r\n floatA = floatA / 2\r\n count = count + 1\r\n return count"
},
{
"alpha_fraction": 0.4051724076271057,
"alphanum_fraction": 0.4482758641242981,
"avg_line_length": 19.272727966308594,
"blob_id": "a4f8bc62c158549c99b21f112147d8c54a41f415",
"content_id": "985e10dbc53c24cad846fd709b3636f2b79be527",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 232,
"license_type": "no_license",
"max_line_length": 28,
"num_lines": 11,
"path": "/Programming_a4/ps3.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def findmin(lst):\r\n min_num = lst[0]\r\n i = 1\r\n while i < len(lst): \r\n if lst[i] < min_num:\r\n min_num = lst[i]\r\n i = i + 1\r\n return min_num.index\r\n\r\nlst = [7, 4, 6, -1, 4, 19]\r\nprint(findmin(lst))"
},
{
"alpha_fraction": 0.43478259444236755,
"alphanum_fraction": 0.47826087474823,
"avg_line_length": 20,
"blob_id": "773dc3c72322f6e33e2871789c8919b8b9697468",
"content_id": "26855cc57f0e8ea3774a3ee491a636bffa27e73f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 46,
"license_type": "no_license",
"max_line_length": 22,
"num_lines": 2,
"path": "/Programming_a6/left_index.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def left_index(i):\r\n return (i * 2) + 1\r\n\r\n"
},
{
"alpha_fraction": 0.42915812134742737,
"alphanum_fraction": 0.48254621028900146,
"avg_line_length": 20.045454025268555,
"blob_id": "7bed7a26ff9f4747550b0884e5ea8f2f8027613f",
"content_id": "3bf28e081ee0b051743ae3d6935a9b13d2635ac5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 487,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 22,
"path": "/Lab6/multiply.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def multiply(a, b):\r\n #base case\r\n if (b == 1):\r\n return a\r\n \r\n if a == 0 or b == 0:\r\n return 0 \r\n \r\n #recursion case b > 1\r\n else:\r\n return a + multiply(a, b-1)\r\n\r\ndef test_multiply(): \r\n print(\"Testing multiply()...\", end=\"\")\r\n assert(multiply(0, 3) == 0)\r\n assert(multiply(0, 0) == 0)\r\n assert(multiply(1, 2) == 2)\r\n assert(multiply(4, 6) == 24)\r\n assert(multiply(11, 11) == 121)\r\n print(\"Passed!\")\r\n\r\ntest_multiply()\r\n "
},
{
"alpha_fraction": 0.42113563418388367,
"alphanum_fraction": 0.4637224078178406,
"avg_line_length": 19.689655303955078,
"blob_id": "e03081f77cecbebc14c79afb9599a9923fba3b80",
"content_id": "2d6143f0f19a5d15d0c3735e69dd9c0eb197c575",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 636,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 29,
"path": "/tester.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "# def search_pair(items):\r\n# for i in range((len(items)) - 1):\r\n# assert i + 1 < len(items)\r\n# if items[i] > items[ i + 1]:\r\n# return i \r\n# return None\r\n\r\n# items = [1, 3, 4, 6, 4, 7, 7]\r\n# print(search_pair(items))\r\n\r\n\r\n# num_A = ([1, 2, 3, 4])\r\n# num_B = ([5, 6, 7, 8])\r\n# num_B.insert(0, num_A.pop(1) )\r\n# print(num_B)\r\n# print(num_A)\r\n\r\n\r\ndef mystery1(m, n): \r\n i=0 \r\n while i < n: \r\n i=i+1 \r\n print(i ** m, end=\", \")\r\n\r\nmystery_val = mystery1(2, 3) \r\nif mystery_val == 9: \r\n print(\"Here is Nine: \", mystery_val) \r\nelse: \r\n print(\"Here I’m: value\", mystery_val) \r\n\r\n\r\n"
},
{
"alpha_fraction": 0.4881889820098877,
"alphanum_fraction": 0.5039370059967041,
"avg_line_length": 16.428571701049805,
"blob_id": "cdee2f61041904b62e6ee34749deff603b7ffcf4",
"content_id": "f2764ada930916ec369391efc5e5bb91def90b4c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 127,
"license_type": "no_license",
"max_line_length": 26,
"num_lines": 7,
"path": "/Programming_a2/digit.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def digit(num, pos):\r\n num > 0 \r\n 0 < pos < num \r\n return int(num) % pos\r\n\r\ndef digit():\r\n print (digit(num, pos))"
},
{
"alpha_fraction": 0.4333333373069763,
"alphanum_fraction": 0.4692307710647583,
"avg_line_length": 17.600000381469727,
"blob_id": "024a2a1d10e9c635c54c80883193dc117834b04d",
"content_id": "bd9ba97088d7f5c735c134cff35c457b627c4b4c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 390,
"license_type": "no_license",
"max_line_length": 29,
"num_lines": 20,
"path": "/test7.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "# def contains_even(list):\r\n# for num in list:\r\n# if num % 2 == 0:\r\n# return True \r\n# else: \r\n# return False\r\n\r\n# list = [1, 2, 3, 4, 5]\r\n# print(contains_even(list))\r\n\r\n\r\ndef counts_even(list):\r\n count = 0 \r\n for num in list:\r\n if num % 2 == 0:\r\n count = count + 1\r\n return count \r\n\r\nlist = [1, 3, 5]\r\nprint(counts_even(list))"
},
{
"alpha_fraction": 0.40909090638160706,
"alphanum_fraction": 0.44545453786849976,
"avg_line_length": 11.058823585510254,
"blob_id": "17f8c8ef87fb587b755d4a7d19f5e02137ed635c",
"content_id": "5330bf31a9b198f3d9200b2093040e4c64943d77",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 220,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 17,
"path": "/Programming_a4/test.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def d7(list, value):\r\n for num in list:\r\n if value == num:\r\n return(True)\r\n \r\n return(False)\r\n\r\nlist = [1, 2, 3]\r\nvalue = 2\r\nprint(d7(list, value))\r\n\r\n'''\r\nhi \r\nnum = 1 \r\nvalue = 2 \r\n \r\n'''"
},
{
"alpha_fraction": 0.5634328126907349,
"alphanum_fraction": 0.5634328126907349,
"avg_line_length": 20.16666603088379,
"blob_id": "5bfe12fc85d4c1ce2dc994b4a0c82bd5fe46d90c",
"content_id": "8c9af8d6d2ee4153d748dc4e89d562a7afe425c8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 268,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 12,
"path": "/Programming_a6/leaf.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "from left_index import left_index\r\nfrom right_index import right_index\r\n\r\ndef is_leaf(tree, i):\r\n l = left_index(i)\r\n r = right_index(i)\r\n if l < len(tree):\r\n return False\r\n if r < len(tree):\r\n return False\r\n else:\r\n return True\r\n\r\n"
},
{
"alpha_fraction": 0.5040872097015381,
"alphanum_fraction": 0.5395095348358154,
"avg_line_length": 18.5,
"blob_id": "02030cc6a6ef2d073960ad30a000589f6882e7a8",
"content_id": "6b0bceeeed180c55988eca6390aa60fb10976e47",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 367,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 18,
"path": "/PS9/dungeon.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "from random import randint\r\n\r\ndef roll():\r\n return randint(1,20,5)\r\n\r\ndef game():\r\n critHitTotal = 0\r\n critMissTotal = 0\r\n for i in range(20):\r\n value = roll()\r\n if value == 20:\r\n critHitTotal += 1\r\n elif value == 1:\r\n critMissTotal += 1\r\n return (critHitTotal, critMissTotal)\r\n\r\nprint(roll())\r\nprint(game())"
},
{
"alpha_fraction": 0.6114864945411682,
"alphanum_fraction": 0.625,
"avg_line_length": 22.66666603088379,
"blob_id": "62d6f436dbfcae85be55227d0d0d1416553b9fa2",
"content_id": "0675cbce3ca5eb67c13347ddd9f929dd6d251de3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 296,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 12,
"path": "/Programming_a5/cumulative_product.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def cumulative_product_helper(nums, subtotal):\r\n #base case\r\n if nums == []:\r\n return []\r\n #recursive\r\n return [nums[0] * subtotal] + cumulative_product_helper(nums[1:], subtotal * nums[0])\r\n\r\n\r\n\r\n\r\ndef cumulative_product(nums):\r\n return cumulative_product_helper(nums, 1)\r\n"
},
{
"alpha_fraction": 0.47290822863578796,
"alphanum_fraction": 0.5506818890571594,
"avg_line_length": 36.75714111328125,
"blob_id": "4c8499a5578a1e3e2f013edb5621b15ce23b028d",
"content_id": "36773f972897a44b578cd51ff6bcee2f8150c4f8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2713,
"license_type": "no_license",
"max_line_length": 114,
"num_lines": 70,
"path": "/Programming_activity4/test_pa4.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "from first_even import first_even\r\nfrom num_even import num_even\r\nfrom geo_mean import geo_mean\r\nfrom second_largest import second_largest\r\nfrom counting_sort import counting_sort\r\n\r\ndef test_first_even():\r\n print(\"Testing first_even()...\\n\")\r\n assert(first_even(list(range(5))) == 0)\r\n assert(first_even([1, 3, 1, 5, 7, 9, 11, 13, 0]) == 8)\r\n assert(first_even([1, 3, 1, 5, 7, 9, 11, 13, 0, 11, 4]) == 8)\r\n assert(first_even([-5, 5, -1, 1, -4, 4]) == 4)\r\n assert(first_even([0]) == 0)\r\n assert(first_even([4, 4]) == 0)\r\n assert(first_even([]) == None)\r\n assert(first_even([1, 1, 1, 1]) == None)\r\n print(\"Finished testing first_even()!\\n\")\r\n\r\ndef test_num_even():\r\n print(\"Testing num_even()...\\n\")\r\n assert(num_even([]) == 0)\r\n assert(num_even(list(range(10))) == 5)\r\n assert(num_even([-1]*10) == 0)\r\n assert(num_even([0]*10) == 10)\r\n assert(num_even([-6, -4, -2, 0, 2, 4, 6, 99]) == 7)\r\n assert(num_even([99, -6, -4, -2, 0, 2, 4, 6]) == 7)\r\n print(\"Finished testing num_even()!\\n\")\r\n\r\ndef test_geo_mean():\r\n print(\"Testing geo_mean()...\\n\")\r\n epsilon = 0.001\r\n assert((geo_mean([9]) - 9.0) < epsilon)\r\n assert((geo_mean([2, 8]) - 4.0) < epsilon)\r\n assert((geo_mean([.5, 32]) - 4.0) < epsilon)\r\n assert((geo_mean([1/32, 1, 4]) - 0.5) < epsilon)\r\n assert((geo_mean([2, 8]) - 4.0) < epsilon)\r\n print(\"Finished testing geo_mean()!\\n\")\r\n\r\ndef test_second_largest():\r\n print(\"Testing second_largest()...\\n\")\r\n assert(second_largest([3, -2, 10, -1, 5]) == 5)\r\n assert(second_largest([-2, 1, 1, -3, 5]) == 1)\r\n assert(second_largest([1, 1, 3, 3]) == 3)\r\n assert(second_largest([\"alpha\", \"gamma\", \"beta\", \"delta\"]) == \"delta\")\r\n assert(second_largest([3.1, 3.1]) == 3.1)\r\n assert(second_largest([False, True, False, False]) == False)\r\n assert(second_largest([True, False, True]) == True)\r\n print(\"Finished testing second_largest()!\\n\")\r\n\r\ndef test_counting_sort():\r\n print(\"Testing counting_sort()...\\n\")\r\n assert counting_sort([44, 22, 44, 11, 33, 33, 22, 44, 33, 44], 44) == [11, 22, 22, 33, 33, 33, 44, 44, 44, 44]\r\n assert counting_sort([], 0) == []\r\n assert counting_sort([5], 5) == [5]\r\n assert counting_sort([5, 5, 5, 5], 5) == [5, 5, 5, 5]\r\n assert counting_sort(list(range(10)), 9) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\r\n assert counting_sort(list(range(9, -1, -1)), 9) == [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]\r\n print(\"Finished testing counting_sort()!\\n\")\r\n \r\n\r\ndef test_all():\r\n print(\"Testing all functions...\\n\")\r\n test_first_even()\r\n test_num_even()\r\n test_geo_mean()\r\n test_second_largest()\r\n test_counting_sort()\r\n print(\"All tests completed\\n\")\r\n\r\ntest_all()\r\n"
},
{
"alpha_fraction": 0.40096619725227356,
"alphanum_fraction": 0.4299516975879669,
"avg_line_length": 32.16666793823242,
"blob_id": "56e13230aa108a529301e4d3e74883e9a47b949f",
"content_id": "b883aabe6a423d9d65ba1f2cedc002b30e2358b7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 207,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 6,
"path": "/Lab6/list_a_words.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "def list_a_words(lst):\r\n if lst == []:\r\n return []\r\n if isinstance(lst[0], str) == True:\r\n if (lst[0] != \"\") and (lst[0][0] == 'a'):\r\n return lst[0] + list_a_words(lst[1:])\r\n\r\n"
},
{
"alpha_fraction": 0.5171086192131042,
"alphanum_fraction": 0.6167664527893066,
"avg_line_length": 31.399999618530273,
"blob_id": "1e8f6ef68b15abb23ab0961bb402f06768bec3c4",
"content_id": "99b94f07434282bb0029447e025886e1e48608d7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2338,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 70,
"path": "/Programming_a2/test_pa2_v2.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "from cone import cone_volume, print_object_volume\r\nfrom quadratic import quadratic\r\nfrom list_cubic import list_cubic\r\n# from digit import digit, reverse_num, pal_num\r\n\r\n\r\nimport math\r\n\r\ndef test_all():\r\n test_cone_volume()\r\n test_print_object_volume()\r\n test_quadratic()\r\n test_list_cubic()\r\n test_digit()\r\n # test_reverse_num()\r\n # test_pal_num()\r\n print(\"All tests completed\")\r\n\r\ndef test_cone_volume():\r\n assert round(cone_volume(3, 5), 5) == round(1/3 * math.pi * 9 * 5, 5)\r\n assert round(cone_volume(4, 10), 5) == round(1/3 * math.pi * 16 * 10, 5)\r\n assert round(cone_volume(4, 15), 5) == round(1/3 * math.pi * 16 * 15, 5)\r\n assert round(cone_volume(1, 1), 5) == round(1/3 * math.pi * 1 * 1, 5)\r\n print(\"Test complete\")\r\n \r\ndef test_print_object_volume():\r\n print(\"You must check visually that your output looks like the following (it may be slightly different in the final digits):\")\r\n print(\"The total volume of the two cones is \" + str(1/3*math.pi*6*6*8 + 1/3*math.pi*6*6*12))\r\n print(\"Here is your output:\")\r\n print_object_volume()\r\n print(\"Test complete\")\r\n\r\ndef test_quadratic():\r\n print(\"You must check visually that your output looks like the following:\")\r\n print(\"[x1: 1.0, x2: -4.0]\")\r\n print(\"[x1: -2.0, x2: -2.0]\")\r\n print(\"[x1: -0.5, x2: -0.5]\")\r\n print(\"Here is your output:\")\r\n quadratic(1, 3, -4)\r\n quadratic(1, 4, 4)\r\n quadratic(4, 4, 1)\r\n print(\"Test complete\")\r\n\r\ndef test_list_cubic():\r\n print(\"You must check visually that your output looks like the following:\")\r\n print(\"2\\n6\\n36\\n110\\n246\\n462\\n776\\n1206\\n1770\\n2486\\n3372\\n4446\\n5726\\n7230\\n8976\\n10982\\n13266\\n15846\\n18740\\n21966\\n25542\")\r\n print(\"Here is your output:\")\r\n list_cubic(3, 4, -3, 2)\r\n print(\"Test complete\")\r\n\r\ndef test_digit():\r\n assert digit(123, 3) == 1\r\n assert digit(293586, 4) == 3\r\n assert digit(123456, 3) == 4\r\n print(\"Test complete\")\r\n\r\ndef test_reverse_num():\r\n assert reverse_num(12345, 5) == 54321\r\n assert reverse_num(596920 ,6) == 29695\r\n assert reverse_num(2020, 4) == 202\r\n print(\"Test complete\")\r\n\r\ndef test_pal_num():\r\n assert pal_num(1234, 4) == False\r\n assert pal_num(1234321, 7) == True\r\n assert pal_num(1234 + reverse_num(1234, 4), 4) == True\r\n print(\"Test complete\")\r\n\r\n\r\ntest_all()\r\n"
},
{
"alpha_fraction": 0.44859811663627625,
"alphanum_fraction": 0.4672897160053253,
"avg_line_length": 24.850000381469727,
"blob_id": "37f10c780b09176884bb57a03343308d88e72648",
"content_id": "40a371bfacb3a45cc507e9269b40376bdf88eced",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 535,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 20,
"path": "/Lab_2/q2.py",
"repo_name": "juliafox8/cm-codes",
"src_encoding": "UTF-8",
"text": "# def rowSums(matrix):\r\n# for row in range (0, len(matrix)):\r\n# sum = 0\r\n# for col in range (0, len(matrix[row])):\r\n# sum = sum + matrix[row][col]\r\n# print(\"Sumofrow\", \" \", row, \":\", \" \", sum, sep = '')\r\n\r\n\r\n# def terminate(matrix):\r\n# for i in range(0, len(matrix)):\r\n# for j in range(0, len(matrix[i])):\r\n if j != 1:\r\n# return False \r\n# else:\r\n# return True\r\n\r\n\r\nimport random \r\nfrom random import randint\r\nprint((randint(1, 50)) * 5)"
}
] | 50 |
L1NNA/Covid19-ScamHunter | https://github.com/L1NNA/Covid19-ScamHunter | f1ed023e3713e6d3a8fa8d36d0b27d40b9fd6bb3 | 2ae0c8cadf53313135a34793c362e9fc75dce406 | c81557619fd0d0a4e5f78f0508e578df141aa445 | refs/heads/master | 2021-05-17T06:43:05.888896 | 2020-04-07T22:28:34 | 2020-04-07T22:28:34 | 250,679,710 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5620553493499756,
"alphanum_fraction": 0.5675889253616333,
"avg_line_length": 32.24324417114258,
"blob_id": "641068d76a40157e5e4ead10f696162705a63a05",
"content_id": "d545e1538c2c1ec93d86ae01686d15990a065b89",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1265,
"license_type": "permissive",
"max_line_length": 92,
"num_lines": 37,
"path": "/utils/ipTracker.py",
"repo_name": "L1NNA/Covid19-ScamHunter",
"src_encoding": "UTF-8",
"text": "import geoip2.database\r\nimport requests\r\n\r\ndef getIP(url):\r\n try:\r\n rsp = requests.get(url, stream=True)\r\n return rsp.raw._fp.fp.raw._sock.socket.getpeername()[0]\r\n except Exception:\r\n return None\r\n\r\ndef getGeoInfo(ip):\r\n if ip is not None:\r\n reader = geoip2.database.Reader('utils/GeoLite2-City.mmdb')\r\n response = reader.city(ip)\r\n return {\"country\" : response.country.name, \"city\" : response.city.name}\r\n else:\r\n return {\"country\" : \"N/A\", \"city\" : \"N/A\"}\\\r\n\r\n\r\n# def observe_geoip(self, req: UrlBasedRequest, mis: MissionStatus):\r\n# url = req.url\r\n# try:\r\n# rsp = requests.get(url, stream=True)\r\n# ip = rsp.raw._fp.fp.raw._sock.socket.getpeername()[0]\r\n# reader = geoip2.database.Reader('utils/GeoLite2-City.mmdb')\r\n# response = reader.city(ip)\r\n# return {\"ip\" : ip, \"country\" : response.country.name, \"city\" : response.city.name}\r\n# except Exception:\r\n# return {\"ip\" : \"N/A\", \"country\" : \"N/A\", \"city\" : \"N/A\"}\r\n\r\nfor i in [{\"url\" : \"https://google.ca\"}]:\r\n print(i[\"url\"])\r\n i[\"ip\"] = getIP(i[\"url\"])\r\n geo_info = getGeoInfo(getIP(i[\"url\"]))\r\n i[\"country\"] = geo_info[\"country\"]\r\n i[\"city\"] = geo_info[\"city\"]\r\n print(i)"
},
{
"alpha_fraction": 0.7577319741249084,
"alphanum_fraction": 0.7628865838050842,
"avg_line_length": 42,
"blob_id": "ef3d4b17368458eca7c1a086d67d7f2ad516f7ab",
"content_id": "0a28d03a99d367568351300dd2718b91c6b778b4",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 388,
"license_type": "permissive",
"max_line_length": 62,
"num_lines": 9,
"path": "/README.md",
"repo_name": "L1NNA/Covid19-ScamHunter",
"src_encoding": "UTF-8",
"text": "# Covid19-ScamHunter\nContent-based URL monitoring and analysis for scam hunting\n\n- [ ] retrieve URL and extract its content as natural language\n- [ ] apply pre-trained bert model to extract embedding\n- [ ] design elasticsearch search model\n- [ ] store it in to the elasticsearch database\n- [ ] apply clustering models from scikit-learn or hdbscan\n- [ ] extract keywords based on cluster\n\n"
},
{
"alpha_fraction": 0.5907859206199646,
"alphanum_fraction": 0.5934959053993225,
"avg_line_length": 24.35714340209961,
"blob_id": "9ed88a92cd39f529b616a7a2233f7dbf97fd5be9",
"content_id": "925db6bade01be9ad0483037b6ece13a15e818e8",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 369,
"license_type": "permissive",
"max_line_length": 60,
"num_lines": 14,
"path": "/utils/OCR.py",
"repo_name": "L1NNA/Covid19-ScamHunter",
"src_encoding": "UTF-8",
"text": "from PIL import Image\r\nimport pytesseract\r\n\r\n\r\nclass OCR():\r\n @staticmethod\r\n def image_to_string(file):\r\n return pytesseract.image_to_string(Image.open(file))\r\n @staticmethod\r\n def batch_image_to_string(file):\r\n if (file[-4:] == \".txt\"):\r\n return pytesseract.image_to_string(file)\r\n else:\r\n raise \"wrong format\"\r\n"
},
{
"alpha_fraction": 0.6089541912078857,
"alphanum_fraction": 0.6131514310836792,
"avg_line_length": 29.645160675048828,
"blob_id": "f4d19529894f4205fbfe5962affb04ff1699fc3b",
"content_id": "834d457b9c6e82a095db8f87030818a525a9b885",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2859,
"license_type": "permissive",
"max_line_length": 148,
"num_lines": 93,
"path": "/collectors/cefweb.py",
"repo_name": "L1NNA/Covid19-ScamHunter",
"src_encoding": "UTF-8",
"text": "\"\"\"\npip install cefpython3==57.0\n\"\"\"\n\nfrom cefpython3 import cefpython as cef\nimport os\nimport platform\nimport subprocess\nimport sys\nimport time\nfrom threading import Thread\nfrom datetime import datetime\n\n\n\nclass CEFBrowser:\n def __init__(self):\n self.browser = None\n self.data = {}\n\n def start(self):\n def run():\n sys.excepthook = cef.ExceptHook # To shutdown all CEF processes on error\n # Off-screen-rendering requires setting \"windowless_rendering_enabled\"\n # option, so that RenderHandler callbacks are called.\n cef.Initialize(settings={\"windowless_rendering_enabled\": True, \"downloads_enabled\": False})\n self._create_browser()\n cef.MessageLoop()\n cef.Shutdown()\n t = Thread(target=run)\n t.start()\n time.sleep(3)\n \n \n def ceff_callback(self, tms, val):\n self.data[tms] = val\n \n def _rebind(self):\n bindings = cef.JavascriptBindings(\n bindToFrames=True, bindToPopups=True)\n bindings.SetObject('cefcontroller', self)\n self.browser.SetJavascriptBindings(bindings)\n time.sleep(1)\n \n def _create_browser(self):\n # Create browser in off-screen-rendering mode (windowless mode)\n # by calling SetAsOffscreen method. In such mode parent window\n # handle can be NULL (0).\n parent_window_handle = 0\n window_info = cef.WindowInfo()\n # window_info.SetAsOffscreen(parent_window_handle)\n browser = cef.CreateBrowserSync(window_info=window_info,\n url='https://www.google.com')\n \n # browser.SetClientHandler(LoadHandler())\n # browser.SetClientHandler(RenderHandler())\n browser.SendFocusEvent(True)\n # You must call WasResized at least once to let know CEF that\n # viewport size is available and that OnPaint may be called.\n browser.WasResized()\n self.browser = browser\n self._rebind()\n\n def goto(self, url):\n self.browser.LoadUrl(url)\n \n\n def dump(self):\n self._rebind()\n tms = time.time()\n self.browser.ExecuteJavascript(\"function ceff_dump(tms){cefcontroller.ceff_callback(tms, new XMLSerializer().serializeToString(document))}\")\n self.browser.ExecuteFunction(\"ceff_dump\", tms)\n qstart = datetime.now()\n while tms not in self.data:\n continue\n val = self.data[tms]\n del self.data[tms]\n return val\n\n def exit(self):\n self.browser.CloseBrowser()\n cef.QuitMessageLoop()\n\n\n\n\nif __name__ == '__main__':\n brw = CEFBrowser()\n brw.start()\n #brw.goto('https://www.hybrid-analysis.com/recent-submissions?filter=file&sort=^timestamp&page=1')\n #time.sleep(10)\n #print(brw.dump())\n #brw.exit()\n \n "
},
{
"alpha_fraction": 0.5617935061454773,
"alphanum_fraction": 0.5644310712814331,
"avg_line_length": 37.463768005371094,
"blob_id": "d603098bca31cb1915fb452920bd19b16396e432",
"content_id": "8985e5685b4edc3af75a865903bc44099b9988ee",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2654,
"license_type": "permissive",
"max_line_length": 137,
"num_lines": 69,
"path": "/spider/webspider/spiders/general.py",
"repo_name": "L1NNA/Covid19-ScamHunter",
"src_encoding": "UTF-8",
"text": "from scrapy.spiders import Spider\nfrom scrapy.selector import Selector\nimport scrapy\nimport re\nfrom webspider.items import Website\nfrom inscriptis import get_text\nimport datetime\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch_dsl import Search\n\nclass GeneralSpider(scrapy.Spider):\n name = 'general'\n # urls = open(\"URLs\", \"r\").readlines()\n # allowed_domains = [(re.split(r'h..p.*://', i, maxsplit=0)[1] if re.match(r'h..p.*://', i) else i).strip() for i in urls if i]\n # # print(allowed_domains[30])\n # start_urls = list(set([\"https://\"+i for i in allowed_domains]))\n # allowed_domains = ['baidu.com']\n # start_urls = ['https://www.baidu.com']\n\n def __init__(self, source=\"es\", *args, **kwargs):\n super(GeneralSpider, self).__init__(*args, **kwargs)\n if (source==\"es\"):\n client = Elasticsearch()\n s = Search(using=client, index=\"website\", doc_type=\"items\")\n s = s.source([])\n self.start_urls = [h.meta.id for h in s.scan()]\n else:\n urls = open(source, \"r\").readlines()\n allowed_domains = [(re.split(r'h..p.*://', i, maxsplit=0)[1] if re.match(r'h..p.*://', i) else i).strip() for i in urls if i]\n self.start_urls = list(set([\"https://\"+i for i in allowed_domains]))\n \n\n\n def parse(self, response):\n # \"\"\"\n # The lines below is a spider contract. For more info see:\n # http://doc.scrapy.org/en/latest/topics/contracts.html\n\n # @url http://www.dmoz.org/Computers/Programming/Languages/Python/Resources/\n # @scrapes name\n # \"\"\"\n # sel = Selector(response)\n # sites = sel.xpath('//ul[@class=\"directory-url\"]/li')\n # items = []\n item = Website()\n markup = response.xpath('/html').extract()\n regex = re.compile(r'[\\n\\r\\t]')\n content = get_text(regex.sub(\" \", markup[0]))\n \n item[\"url\"] = response.request.url\n item[\"snapshot\"] = {}\n\n item[\"snapshot\"][\"response_url\"] = response.url\n item[\"snapshot\"][\"status\"] = response.status\n item[\"snapshot\"][\"title\"] = response.xpath('/html/head/title/text()').extract_first()\n item[\"snapshot\"][\"content\"] = content\n item[\"snapshot\"][\"timestamp\"] = datetime.datetime.now().timestamp()\n \n return item\n\n\n # for site in sites:\n # item = Website()\n # item['name'] = site.xpath('a/text()').extract()\n # item['url'] = site.xpath('a/@href').extract()\n # item['description'] = site.xpath('text()').re('-\\s[^\\n]*\\\\r')\n # items.append(item)\n\n # return items\n"
},
{
"alpha_fraction": 0.5762711763381958,
"alphanum_fraction": 0.5770416259765625,
"avg_line_length": 29.186046600341797,
"blob_id": "f3302400458bea9620b406e195f45cf6352d32b3",
"content_id": "bd6e83a82a72d41564fe4a50d0b1a891e2c5dbd2",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1298,
"license_type": "permissive",
"max_line_length": 84,
"num_lines": 43,
"path": "/spider/webspider/pipelines.py",
"repo_name": "L1NNA/Covid19-ScamHunter",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nfrom datetime import datetime\nfrom elasticsearch import Elasticsearch\nfrom elasticsearch_dsl import Document, Date, Integer, Keyword, Text\nfrom elasticsearch_dsl.connections import connections\nfrom elasticsearch_dsl.update_by_query import UpdateByQuery\n\n# Define your item pipelines here\n#\n# Don't forget to add your pipeline to the ITEM_PIPELINES setting\n# See: https://docs.scrapy.org/en/latest/topics/item-pipeline.html\n\n\nclass WebspiderPipeline(object):\n\n def open_spider(self, spider):\n self.client = Elasticsearch()\n\n def close_spider(self, spider):\n pass\n\n def process_item(self, item, spider):\n doc = {}\n\n item\n url = item[\"url\"]\n snapshot = item[\"snapshot\"]\n doc[\"url\"] = url\n doc[\"snapshot\"] = [snapshot]\n try:\n self.client.create(index=\"website\", id=url, body=doc)\n except:\n query={\n \"script\": {\n \"source\": \"ctx._source.snapshot.add(params.snapshot)\",\n \"lang\": \"painless\",\n \"params\": {\n \"snapshot\": snapshot\n }\n }\n }\n self.client.update(index=\"website\", doc_type=\"_doc\", id=url, body=query)\n return item\n"
},
{
"alpha_fraction": 0.4977443516254425,
"alphanum_fraction": 0.5032581686973572,
"avg_line_length": 31.28333282470703,
"blob_id": "167e07137f9960c8144bca86063b96edc22cc4e8",
"content_id": "b4d2dce06aac0bc72dcf944587068d4f692b23d0",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1995,
"license_type": "permissive",
"max_line_length": 130,
"num_lines": 60,
"path": "/collectors/CTC_download.py",
"repo_name": "L1NNA/Covid19-ScamHunter",
"src_encoding": "UTF-8",
"text": "from urllib.request import Request, urlopen\r\nimport re\r\nimport whois\r\nimport socket\r\n\r\nGOV_LIST = [\".gov\", \"cic\", \".ca\", \"cic\", \"cra\", \"canada\", \".edu\"]\r\n\r\ndef get_txt(url, tags):\r\n req = Request(url)\r\n req.add_header('User-Agent', 'Mozilla/5.0')\r\n file = urlopen(req)\r\n res = []\r\n for line in file:\r\n i = line.decode(\"utf-8\").strip()\r\n if i[0] !=\"#\":\r\n m = re.search('https?://([A-Za-z_0-9.-]+).*', i)\r\n ip = \"N/A\"\r\n web_url = \"N/A\"\r\n domain = i\r\n domain_info = {}\r\n tmp = {}\r\n if m:\r\n domain = m.group(1)\r\n web_url = i\r\n try:\r\n domain_info = whois.whois(domain).__dict__\r\n ip = socket.gethostbyname(i)\r\n pass\r\n except Exception:\r\n pass\r\n\r\n tmp = {\"url\" : web_url, \"domain\" : domain, \"tag\" : tags, \"whois\" : domain_info, \"ip\" : ip}\r\n if \"good\" in tags and any(substring in i for substring in GOV_LIST):\r\n tmp[\"tag\"] = tags + [\"offical\"]\r\n elif \"good\" in tags:\r\n tmp[\"tag\"] = tags + [\"other\"]\r\n res.append(tmp)\r\n\r\n return res\r\n\r\n\r\n # return [{\"url\" : i, \"domain\" : i.split(\"/\")[2], \"tag\" : tag} for line in file if (i := line.decode(\"utf-8\").strip())]\r\n # return [{\"url\" : i, \"domain\" : i.split(\"/\")[2], \"tag\" : tags} for i in (line.decode(\"utf-8\").strip() for line in file) if i]\r\n\r\n\r\ndef get_vetted():\r\n url = \"https://blacklist.cyberthreatcoalition.org/vetted/url.txt\"\r\n return get_txt(url, [\"bad\", \"vetted\"])\r\ndef get_unvetted():\r\n url = \"https://blacklist.cyberthreatcoalition.org/unvetted/url.txt\"\r\n return get_txt(url, [\"bad\", \"unvetted\"])\r\n\r\ndef get_good():\r\n url = \"https://raw.githubusercontent.com/Cyber-Threat-Coalition/goodlist/master/hostnames.txt\"\r\n return get_txt(url, [\"good\"])\r\n\r\ndef get_data():\r\n return get_vetted() + get_unvetted()\r\n\r\nprint(get_good())"
}
] | 7 |
drgonzalomora/Flip-Track-your-personal-financial-situation | https://github.com/drgonzalomora/Flip-Track-your-personal-financial-situation | a960436406d546fc45ce8b0fc6ee259e1a48a277 | 9b26fd3bf8a876313de2e262c1e8b28341d9029e | 02878e75881d201a7ac340f9745c9d4e206cc20d | refs/heads/master | 2023-07-15T11:48:27.158252 | 2017-12-11T20:14:00 | 2017-12-11T20:14:00 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6111111044883728,
"alphanum_fraction": 0.6284722089767456,
"avg_line_length": 24.086956024169922,
"blob_id": "de5d8d060efcd6acb5e908406216e31e44cf4657",
"content_id": "6e77d091e4aa008be1b027e1cb7484e24e3ef2ea",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 576,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 23,
"path": "/dbsetup.py",
"repo_name": "drgonzalomora/Flip-Track-your-personal-financial-situation",
"src_encoding": "UTF-8",
"text": "import psycopg2\ntry:\n conn = psycopg2.connect(\"dbname='flipDB' user='diego' host='localhost' password='diego93'\")\nexcept:\n print(\"I am unable to connect to the database\")\n\ncur = conn.cursor()\n\ncur.execute('''CREATE TABLE usuarios\n (IDusuario INT PRIMARY KEY NOT NULL,\n nombre varchar(100));''')\n\ncur.execute('''CREATE TABLE transacciones\n (IDusuario \tINT NOT NULL references usuarios (IDusuario),\n tipo varchar(50) NOT NULL,\n monto money,\n concepto varchar(150));''')\n\n\n\n\nconn.commit()\nconn.close()"
},
{
"alpha_fraction": 0.8297872543334961,
"alphanum_fraction": 0.8297872543334961,
"avg_line_length": 22.5,
"blob_id": "04aa842016441ec97581bdb0cdf2a7ef7663387b",
"content_id": "8998c1e62154c63f42fcb316b40f56f45b5b4b52",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 47,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 2,
"path": "/README.md",
"repo_name": "drgonzalomora/Flip-Track-your-personal-financial-situation",
"src_encoding": "UTF-8",
"text": "# Flip\nTrack your personal financial situation\n"
},
{
"alpha_fraction": 0.647926926612854,
"alphanum_fraction": 0.662684440612793,
"avg_line_length": 23.953216552734375,
"blob_id": "7a0d31aa6391b9ba9f011b13b10efcede39fa981",
"content_id": "186b3d6a05da2613c3cddbdde5b4b226bd2f6054",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4276,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 171,
"path": "/fil_main.py",
"repo_name": "drgonzalomora/Flip-Track-your-personal-financial-situation",
"src_encoding": "UTF-8",
"text": "import pandas as pd\nimport datetime\nimport smtplib\nimport os\nimport psycopg2\n\n\n\nclass transaccion:\n \tCount = 0\n\n \tdef __init__(self, idUsuario, tipo, monto, concepto):\n\t self.tipo = tipo\n\t self.idUsuario = idUsuario\n\t self.monto = monto\n\t self.fecha = datetime.datetime.now()\n\t self.concepto = concepto\n\t transaccion.Count += 1\n\n\tdef getTipo(self):\n\t\treturn self.tipo\n\n\tdef getMonto(self):\n\t\treturn self.monto\n\n\tdef getFecha(self):\n\t\treturn self.fecha\n\n\tdef getConcepto(self):\n\t\treturn self.concepto\n\n\tdef verTransaccion(self):\n \t\tprint(\"Tipo : \", self.tipo, \", Fecha: \", self.fecha, \", concepto: \", self.concepto)\n\n\tdef registro(self):\n\t if self.tipo == \"efectivo\":\n\t res = [self.fecha,self.monto,0,0,0,self.concepto]\n\t elif self.tipo == \"debito\":\n\t res = [self.fecha,0,self.monto,0,0,self.concepto]\n\t elif self.tipo == \"credito\":\n\t res = [self.fecha,0,0,self.monto,0,self.concepto]\n\t elif self.tipo == \"deuda\":\n\t res = [self.fecha,0,0,0,self.monto,self.concepto]\n\t else:\n\t \t\tres = \"no\"\n\t return res\n\n\nclass usuario:\n\tCount = 0\n\n\tdef __init__(self, id, nombre):\n\t\tself.id = id\n\t\tself.nombre = nombre\n\t\tusuario.Count += 1\n\n\tdef nombre(self):\n\t\treturn self.nombre\n\n\n\n\nbase = pd.DataFrame(columns=[\"Fecha\",\"Efectivo\",\"Debito\",\"Credito\",\"Deudas\",\"Concepto\"])\n\ntransacciones = []\nflag = True\nwhile flag == True:\n\tvar1 = input(\"¿Que tipo de transaccion es? Puede ser efectivo, debito, credito o deuda\\n\")\n\tvar2 = input(\"Ingresa el monto de la transacción.\\n\")\n\tvar3 = input(\"Ingresa el concepto de la transacción\\n\")\n\tvar4 = input(\"Quieres ingresar otra transacción? Si o no\\n\")\n\ttransacciones.append(transaccion(1,var1,int(var2),var3))\n\tif (var4 != \"si\") and (var4 != \"Si\"):\n\t\tflag = False\n\n\n\n'''transacciones.append(transaccion(1,\"efectivo\",200,\"Saldo Inicial\"))\ntransacciones.append(transaccion(1,\"debito\",10364.77,\"Saldo Inicial\"))\ntransacciones.append(transaccion(1,\"credito\",-6513.81,\"Saldo Inicial\"))\ntransacciones.append(transaccion(1,\"deuda\",1555,\"Libros escuela\"))\ntransacciones.append(transaccion(1,\"deuda\",10355,\"Expenses\"))'''\n\n\n\ntry:\n conn = psycopg2.connect(\"dbname='flipDB' user='diego' host='localhost' password='diego93'\")\nexcept:\n print(\"I am unable to connect to the database\")\n\ncur = conn.cursor()\n\nfor i in transacciones:\n\tif i.registro() != \"in\":\n\t\tbase.loc[len(base)] = i.registro()\n\n\t\tIDusuario = 1\n\n\t\tquery = '''select nombre from usuarios where IDusuario == %;'''\n\t\tdata = (IDusuario)\n\t\tcur.execute(query,data)\n\n\t\tnombre = cur.fetchone()\n\n\t\tquery = '''insert into usuarios(IDusuario, nombre) values (%,%);'''\n\t\tdata = (IDusuario, nombre)\n\t\tcur.execute(query,data)\n\n\t\ttipo = i.getTipo()\n\t\tmonto = i.getMonto()\n\t\tconcepto = i.getConcepto()\n\n\t\tquery = '''insert into transacciones(IDusuario, tipo, monto, concepto) values (%,%,%,%);'''\n\t\tdata = (IDusuario, tipo, monto, concepto)\n\t\tcur.execute()\n\n\nconn.commit()\nconn.close()\n \n\ndef reporte(panda):\n\t#Create the excel file\n\tresumen = pd.DataFrame(columns=[\"Saldo débito\",\"Saldo crédito\",\"Saldo efectivo\",\"Subtotal\",\"Total Deudas\",\"Total general\"])\n\tdebito = panda[\"Debito\"].sum()\n\tcredito = panda[\"Credito\"].sum()\n\tefectivo = panda[\"Efectivo\"].sum()\n\tdeudas = panda[\"Deudas\"].sum()\n\tsubtotal = debito + credito + efectivo\n\ttotal = deudas + subtotal\n\tresumen.loc[0] = [debito,credito,efectivo,subtotal,deudas,total]\n\twriter = pd.ExcelWriter(\"ResumenFinanciero.xlsx\")\n\tresumen.to_excel(writer,'Resumen')\n\tpanda.to_excel(writer,'Detalle')\n\twriter.save()\n\tos.system(\"open ResumenFinanciero.xlsx\")\n\n\t#Send via email\n\n\n\t'''sender = '[email protected]'\n\treceivers = ['[email protected]']\n\tsubject = \"Prueba\"\n\tmsg = \"Hola\"\n\temail = \"\"\"\\ \n\tFrom: %s \n\tTo: %s \n\tSubject: %s\n\n\t%s\n\t\"\"\" % (sender, \", \".join(receivers), subject, msg)\n\temail = email.encode()\n\n\ttry:\n\t\tserver = smtplib.SMTP(host='smtp.gmail.com', port=587)\n\t\tserver.ehlo()\n\t\tserver.starttls()\n\t\tserver.ehlo()\n\t\tserver.login(\"[email protected]\", \"PASSWORD\")\n\t\tserver.sendmail(sender, receivers, msg)\n\t\tserver.close()\n\n\t\tprint(\"Email sent\")\n\texcept Exception as e: \n\t\tprint(e)\n\t\tprint(\"something went wrong...\")'''\nprint(\"Tus transacciones son las siguientes:\")\nprint(base)\nprint()\nprint(\"Tu resumen de situación financiera es el siguiente\")\nreporte(base)\n\n\n"
}
] | 3 |
jaztsong/rlpyt | https://github.com/jaztsong/rlpyt | e5049140297c48dd7a2d81e04139843c63c8c4da | 42b6f3ac3ffcaa139cdfa3b109bc3d565c8d8258 | 95e533a30b65aad6632a1b2b0ce97232e2a0c585 | refs/heads/master | 2021-01-16T14:53:57.734684 | 2020-04-08T19:21:52 | 2020-04-08T19:21:52 | 243,159,340 | 0 | 0 | MIT | 2020-02-26T03:27:00 | 2020-02-26T01:17:27 | 2020-02-26T01:17:25 | null | [
{
"alpha_fraction": 0.6273645162582397,
"alphanum_fraction": 0.6297823786735535,
"avg_line_length": 39.40229797363281,
"blob_id": "6cc5f2658112d8e5f6df3bfac7b4f2d325a16cd8",
"content_id": "459735b44a097d15602399b32dbed7bfab18b9f2",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7031,
"license_type": "permissive",
"max_line_length": 108,
"num_lines": 174,
"path": "/rlpyt/agents/mb/gp_mlp_agent.py",
"repo_name": "jaztsong/rlpyt",
"src_encoding": "UTF-8",
"text": "\nimport torch\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nfrom torch.nn.parallel import DistributedDataParallelCPU as DDPC\n\nfrom rlpyt.agents.base import BaseAgent, AgentStep\nfrom rlpyt.utils.quick_args import save__init__args\nfrom rlpyt.distributions.gaussian import Gaussian, DistInfo\nfrom rlpyt.distributions.discrete import DiscreteMixin\nfrom rlpyt.utils.buffer import buffer_to\nfrom rlpyt.utils.logging import logger\nfrom rlpyt.models.qpg.mlp import MuMlpModel\nfrom rlpyt.models.mb.mgpr import GPDynamicsModel\nfrom rlpyt.models.utils import update_state_dict\nfrom rlpyt.utils.collections import namedarraytuple\n\n\nAgentInfo = namedarraytuple(\"AgentInfo\", [\"mu\"])\n\n\nclass GP_MlpAgent(BaseAgent):\n \"\"\"Agent for deep deterministic policy gradient algorithm.\"\"\"\n\n shared_mu_model = None\n\n def __init__(\n self,\n ModelCls=MuMlpModel, # Mu model.\n DModelCls=GPDynamicsModel,\n model_kwargs=None, # Mu model.\n d_model_kwargs=None,\n initial_model_state_dict=None, # Mu model.\n initial_d_model_state_dict=None,\n action_std=0.1,\n action_noise_clip=None,\n ):\n \"\"\"Saves input arguments; default network sizes saved here.\"\"\"\n if model_kwargs is None:\n model_kwargs = dict(hidden_sizes=[20])\n if d_model_kwargs is None:\n # d_model_kwargs = dict(num_inducing_pts=100)\n d_model_kwargs = dict()\n save__init__args(locals())\n super().__init__() # For async setup.\n\n def initialize(self, env_spaces, share_memory=False,\n global_B=1, env_ranks=None):\n \"\"\"Instantiates mu and gp, and target_mu.\"\"\"\n super().initialize(env_spaces, share_memory,\n global_B=global_B, env_ranks=env_ranks)\n self.d_model = self.DModelCls(**self.env_model_kwargs,\n **self.d_model_kwargs)\n if self.initial_d_model_state_dict is not None:\n self.d_model.load_state_dict(self.initial_d_model_state_dict)\n self.target_model = self.ModelCls(**self.env_model_kwargs,\n **self.model_kwargs)\n if self.initial_model_state_dict is not None:\n self.target_model.load_state_dict(self.model.state_dict())\n assert len(env_spaces.action.shape) == 1\n self.distribution = Gaussian(\n dim=env_spaces.action.shape[0],\n std=self.action_std,\n noise_clip=self.action_noise_clip,\n clip=env_spaces.action.high[0], # Assume symmetric low=-high.\n )\n # self.distribution = DiscreteMixin(dim=env_spaces.action.n)\n\n def to_device(self, cuda_idx=None):\n super().to_device(cuda_idx) # Takes care of self.model.\n self.target_model.to(self.device)\n self.d_model.to(self.device)\n\n def data_parallel(self):\n super().data_parallel() # Takes care of self.model.\n if self.device.type == \"cpu\":\n self.d_model = DDPC(self.d_model)\n else:\n self.d_model = DDP(self.d_model)\n\n def make_env_to_model_kwargs(self, env_spaces):\n assert len(env_spaces.action.shape) == 1\n return dict(\n observation_shape=env_spaces.observation.shape,\n action_size=env_spaces.action.shape[0],\n )\n # # CartPole agent\n # return dict(observation_shape=env_spaces.observation.shape,\n # action_size=env_spaces.action.n)\n\n def predict_obs_delta(self, observation, prev_action, prev_reward, action, train=True):\n \"\"\"Compute the next state for input state/observation and action (with grad).\"\"\"\n model_inputs = buffer_to((observation, prev_action, prev_reward,\n action), device=self.device)\n predict_obs_delta = self.d_model(*model_inputs, train=train)\n # Warning: Ideally, the output of the agent should always be on cpu.\n # But due to the complexity to migrate the GP output from gpu to cpu,\n # I decide to just leave it on device and defer to data sync in algo\n return predict_obs_delta\n\n def predict_next_obs_at_mu(self, observation, prev_action, prev_reward):\n \"\"\"Compute Q-value for input state/observation, through the mu_model\n (with grad).\"\"\"\n model_inputs = buffer_to((observation, prev_action, prev_reward),\n device=self.device)\n mu = self.model(*model_inputs)\n next_obs = self.d_model(\n *model_inputs, mu) + model_inputs[0] # model_inputs[0] is the observation\n return next_obs.cpu()\n\n @torch.no_grad()\n def step(self, observation, prev_action, prev_reward):\n \"\"\"Computes distribution parameters (mu) for state/observation,\n returns (gaussian) sampled action.\"\"\"\n model_inputs = buffer_to((observation, prev_action, prev_reward),\n device=self.device)\n mu = self.model(*model_inputs)\n action = self.distribution.sample(DistInfo(mean=mu))\n # action = self.distribution.to_onehot(torch.argmax(mu))\n agent_info = AgentInfo(mu=mu)\n action, agent_info = buffer_to((action, agent_info), device=\"cpu\")\n return AgentStep(action=action, agent_info=agent_info)\n\n def update_target(self, tau=1):\n update_state_dict(self.target_model, self.model.state_dict(), tau)\n\n def d_parameters(self):\n # FIXME: What should be the parameters: gp + likelihood\n return self.d_model.parameters()\n\n def mu_parameters(self):\n return self.model.parameters()\n\n def train_mode(self, itr):\n super().train_mode(itr)\n self.d_model.train()\n\n def sample_mode(self, itr):\n super().sample_mode(itr)\n self.d_model.eval()\n # self.distribution.set_std(self.action_std)\n\n def eval_mode(self, itr):\n super().eval_mode(itr)\n self.d_model.eval()\n # self.distribution.set_std(0.) # Deterministic.\n \n def train_d_model(self):\n self.d_model.gp.train()\n self.d_model.likelihood.train()\n\n def eval_d_model(self):\n self.d_model.gp.eval()\n self.d_model.likelihood.eval()\n\n def state_dict(self):\n return dict(\n model=self.model.state_dict(),\n d_model=self.d_model.state_dict(),\n target_model=self.target_model.state_dict(),\n )\n\n def get_d_model_params(self):\n lengthscales = self.d_model.gp.covar_module.base_kernel.lengthscale.cpu().detach().numpy().squeeze()\n variance = self.d_model.gp.covar_module.outputscale.cpu().detach().numpy().squeeze()\n noise = self.d_model.likelihood.noise.cpu().detach().numpy().squeeze()\n print('-----Learned models------')\n print('---Lengthscales---\\n',lengthscales)\n print('---Variances---\\n',variance)\n print('---Noises---\\n',noise)\n\n\n def load_state_dict(self, state_dict):\n self.model.load_state_dict(state_dict[\"model\"])\n self.d_model.load_state_dict(state_dict[\"d_model\"])\n self.target_model.load_state_dict(state_dict[\"target_model\"])\n"
},
{
"alpha_fraction": 0.6776149272918701,
"alphanum_fraction": 0.6781202554702759,
"avg_line_length": 42.93333435058594,
"blob_id": "3cf63ffdf90073913b4b999311b2d6aadf44f29f",
"content_id": "5c0c6fdcb120595174155e64383aa49455a445ed",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1979,
"license_type": "permissive",
"max_line_length": 94,
"num_lines": 45,
"path": "/rlpyt/models/smgpr.py",
"repo_name": "jaztsong/rlpyt",
"src_encoding": "UTF-8",
"text": "\nimport math\nimport torch\nimport gpytorch\n\n\nclass MultitaskGPModel(gpytorch.models.ApproximateGP):\n def __init__(self, input_size, output_size, num_inducing_pts):\n # We have to mark the CholeskyVariationalDistribution as batch\n # so that we learn a variational distribution for each task\n self._output_size = output_size\n inducing_points = torch.rand(output_size, num_inducing_pts, input_size)\n variational_distribution = gpytorch.variational.CholeskyVariationalDistribution(\n inducing_points.size(-2), batch_shape=torch.Size([output_size])\n )\n\n # We have to wrap the VariationalStrategy in a MultitaskVariationalStrategy\n # so that the output will be a MultitaskMultivariateNormal rather than a batch output\n variational_strategy = gpytorch.variational.MultitaskVariationalStrategy(\n gpytorch.variational.VariationalStrategy(\n self, inducing_points, variational_distribution, learn_inducing_locations=True\n ), num_tasks=output_size\n )\n\n super().__init__(variational_strategy)\n\n # The mean and covariance modules should be marked as batch\n # so we learn a different set of hyperparameters\n self.mean_module = gpytorch.means.ConstantMean(batch_shape=torch.Size([output_size]))\n self.covar_module = gpytorch.kernels.ScaleKernel(\n gpytorch.kernels.RBFKernel(\n ard_num_dims=input_size, batch_shape=torch.Size([output_size])),\n batch_shape=torch.Size([output_size])\n )\n\n def forward(self, x):\n # The forward function should be written as if we were dealing with each output\n # dimension in batch\n mean_x = self.mean_module(x)\n covar_x = self.covar_module(x)\n return gpytorch.distributions.MultivariateNormal(mean_x, covar_x)\n\n @property\n def output_size(self):\n \"\"\"Returns the final output size.\"\"\"\n return self._output_size\n\n"
},
{
"alpha_fraction": 0.5535101890563965,
"alphanum_fraction": 0.558950662612915,
"avg_line_length": 45.4290657043457,
"blob_id": "1d8fe9243c5a0fb731c864c51cd23c2ff42ff1a3",
"content_id": "04b70ce459b75796d86894913478c97747829420",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 13418,
"license_type": "permissive",
"max_line_length": 141,
"num_lines": 289,
"path": "/rlpyt/algos/mb/gp_mlp.py",
"repo_name": "jaztsong/rlpyt",
"src_encoding": "UTF-8",
"text": "import torch\nfrom collections import namedtuple\n\nfrom gpytorch.mlls import ExactMarginalLogLikelihood\n\nfrom rlpyt.algos.base import RlAlgorithm\nfrom rlpyt.utils.quick_args import save__init__args\nfrom rlpyt.utils.logging import logger\nfrom rlpyt.replays.model_based import ModelBasedBuffer\nfrom rlpyt.utils.collections import namedarraytuple\nfrom rlpyt.agents.base import AgentInputs\nfrom rlpyt.utils.tensor import valid_mean\nfrom rlpyt.utils.visom import VisdomLinePlotter\nfrom rlpyt.algos.utils import valid_from_done\n\nOptInfo = namedtuple(\"OptInfo\",\n [\"muLoss\", \"dLoss\", \"muGradNorm\", \"dGradNorm\"])\n\nSamplesToBuffer = namedarraytuple(\"SamplesToBuffer\",\n [\"observation\", \"prev_observation\", \"action\", \"reward\", \"done\", \"timeout\"])\n\nclass GP_Mlp(RlAlgorithm):\n \"\"\"Model-based algorithm that uses Gaussian Process to predict model and a deep\n neural network to control.\"\"\"\n\n opt_info_fields = tuple(f for f in OptInfo._fields) # copy\n\n def __init__(\n self,\n discount=0.99,\n batch_size=500,\n buffer_size=int(1e6),\n min_steps_learn=int(1e1), # very efficient\n target_update_tau=0.9,\n target_update_interval=5,\n policy_update_interval=5,\n learning_rate=1e-2,\n d_learning_rate=1e-2,\n OptimCls=torch.optim.Adam,\n optim_kwargs=None,\n initial_optim_state_dict=None,\n clip_grad_norm=1e8,\n d_target_clip=1e6,\n updates_per_sync=1, # For async mode only.\n bootstrap_timelimit=True,\n obs_cost_fn=None\n ):\n \"\"\"Saves input arguments.\"\"\"\n if optim_kwargs is None:\n optim_kwargs = dict()\n self._batch_size = batch_size\n del batch_size # Property.\n save__init__args(locals())\n\n def initialize(self, agent, n_itr, batch_spec, mid_batch_reset, examples,\n world_size=1, rank=0):\n \"\"\"Stores input arguments and initializes optimizer.\n Use in non-async runners.\"\"\"\n self.agent = agent\n self.n_itr = n_itr\n self.mid_batch_reset = mid_batch_reset\n self.sampler_bs = sampler_bs = batch_spec.size\n self.updates_per_optimize = 5\n self.min_itr_learn = int(self.min_steps_learn // sampler_bs)\n # Agent give min itr learn.?\n self.optim_initialize(rank)\n self.initialize_buffer(examples,batch_spec)\n self.initialize_visom()\n\n def async_initialize(self, agent, sampler_n_itr, batch_spec, mid_batch_reset,\n examples, world_size=1):\n \"\"\"Used in async runner only; returns buffer allocated in shared\n memory, does not instantiate optimizer. \"\"\"\n self.agent = agent\n self.n_itr = sampler_n_itr\n self.mid_batch_reset = mid_batch_reset\n self.sampler_bs = sampler_bs = batch_spec.size\n self.updates_per_optimize = self.updates_per_sync\n self.min_itr_learn = int(self.min_steps_learn // sampler_bs)\n return self.buffer\n\n def initialize_buffer(self, examples, batch_spec, async_=False):\n \"\"\"\n Allocates buffer using examples and with the fields in `SamplesToBuffer`\n namedarraytuple.\n \"\"\"\n example_to_buffer = SamplesToBuffer(\n observation=examples[\"observation\"],\n prev_observation=examples[\"observation\"],\n action=examples[\"action\"],\n reward=examples[\"reward\"],\n done=examples[\"done\"],\n timeout=getattr(examples[\"env_info\"], \"timeout\", None)\n )\n buffer_kwargs = dict(\n example=example_to_buffer,\n size=self.buffer_size,\n B=batch_spec.B,\n )\n BufferCls = ModelBasedBuffer\n self.buffer = BufferCls(**buffer_kwargs)\n\n def optim_initialize(self, rank=0):\n \"\"\"Called in initilize or by async runner after forking sampler.\"\"\"\n self.rank = rank\n self.mu_optimizer = self.OptimCls(self.agent.mu_parameters(),\n lr=self.learning_rate, **self.optim_kwargs)\n self.d_optimizer = self.OptimCls(self.agent.d_parameters(),\n lr=self.d_learning_rate, **self.optim_kwargs)\n if self.initial_optim_state_dict is not None:\n self.d_optimizer.load_state_dict(self.initial_optim_state_dict[\"d\"])\n self.mu_optimizer.load_state_dict(self.initial_optim_state_dict[\"mu\"])\n\n def initialize_visom(self):\n self.plotter = VisdomLinePlotter(env_name='main')\n\n\n def optimize_agent(self, itr, samples_from_buffer=None, sampler_itr=None):\n \"\"\"\n Extracts the needed fields from input samples and stores them in the \n replay buffer. Then samples from the replay buffer to train the agent\n by gradient updates (with the number of updates determined by replay\n ratio, sampler batch size, and training batch size).\n \"\"\"\n itr = itr if sampler_itr is None else sampler_itr # Async uses sampler_itr.\n if samples_from_buffer is not None:\n samples_to_buffer = self.samples_to_buffer(samples_from_buffer)\n self.buffer.append_samples(samples_to_buffer)\n opt_info = OptInfo(*([] for _ in range(len(OptInfo._fields))))\n if itr < self.min_itr_learn:\n return opt_info\n\n for _ in range(self.updates_per_optimize):\n samples_from_buffer = self.buffer.sample_batch(self.batch_size)\n if self.mid_batch_reset and not self.agent.recurrent:\n valid = torch.ones_like(samples_from_buffer.done, dtype=torch.float)\n else:\n valid = valid_from_done(samples_from_buffer.done)\n if self.bootstrap_timelimit:\n # To avoid non-use of bootstrap when environment is 'done' due to\n # time-limit, turn off training on these samples.\n valid *= 1 - samples_from_buffer.timeout.float()\n \n # optimize_dynamic_model\n optimizing_model_iter = 20\n # self.set_requires_grad(self.agent.d_model, True)\n self.agent.train_d_model()\n for itr_ in range(optimizing_model_iter):\n self.d_optimizer.zero_grad()\n d_loss = self.d_loss(samples_from_buffer, itr_)\n d_loss.backward()\n d_grad_norm = torch.nn.utils.clip_grad_norm_(\n self.agent.d_parameters(), self.clip_grad_norm)\n self.d_optimizer.step()\n opt_info.dLoss.append(d_loss.item())\n opt_info.dGradNorm.append(d_grad_norm)\n # print('Iter %d/%d - Loss: %.3f' % (itr_ + 1, optimizing_model_iter, d_loss.item()))\n \n # self.agent.get_d_model_params()\n\n self.update_counter += 1\n # self.set_requires_grad(self.agent.d_model, False)\n self.agent.eval_d_model()\n if self.update_counter % self.policy_update_interval == 0:\n optimizing_policy_iter = 20\n for _ in range(optimizing_policy_iter):\n self.mu_optimizer.zero_grad()\n mu_loss = self.mu_loss(samples_from_buffer, valid)\n mu_loss.backward()\n mu_grad_norm = torch.nn.utils.clip_grad_norm_(\n self.agent.mu_parameters(), self.clip_grad_norm)\n self.mu_optimizer.step()\n opt_info.muLoss.append(mu_loss.item())\n opt_info.muGradNorm.append(mu_grad_norm)\n\n if self.update_counter % self.target_update_interval == 0:\n self.agent.update_target(self.target_update_tau)\n\n return opt_info\n\n\n def samples_to_buffer(self, samples):\n \"\"\"Defines how to add data from sampler into the replay buffer. Called\n in optimize_agent() if samples are provided to that method.\"\"\"\n return SamplesToBuffer(\n observation=samples.env.observation[1:, :, :],\n prev_observation=samples.env.observation[:-1, :, :],\n action=samples.agent.action[:-1,:,:],\n reward=samples.env.reward[1:, :],\n done=samples.env.done[1:, :],\n timeout=getattr(samples.env.env_info[1:, :], \"timeout\", None)\n )\n\n def mu_loss(self, samples, valid):\n \"\"\"Computes the mu_loss by rolling out from s_0.\"\"\"\n n_samples = samples.observation.size(0)\n T = 40 if n_samples > 40 else n_samples\n mu_loss = 0\n n_obs_dim = samples.observation.size(-1)\n #debug one-step prediction\n if self.update_counter % (self.policy_update_interval) == 0:\n # for dim in range(n_obs_dim):\n # self.plotter.plot('dim='+str(dim), 'true',\n # 'Model One-Step Prediction dim='+str(dim),\n # range(T),\n # samples.observation[-T:, 0, dim].data.numpy(), update='replace')\n # self.plotter.plot('dim='+str(dim), 'predict',\n # 'Model One-Step Prediction dim='+str(dim), [0], [0], update='remove')\n # Debug multi-step\n #######################################################\n for dim in range(n_obs_dim):\n self.plotter.plot('multi_dim='+str(dim), 'true',\n 'Model Multi-Step Prediction dim='+str(dim),\n range(T),\n samples.observation[-T:, 0, dim].data.cpu().numpy(), update='replace')\n self.plotter.plot('multi_dim='+str(dim), 'predict',\n 'Model Multi-Step Prediction dim='+str(dim), [0], [0], update='remove')\n #######################################################\n prev_obs = samples.prev_observation[-T:, :, :]\n done = samples.done[-T:, :].squeeze(-1)\n prev_action = samples.action[0, :, :]\n prev_reward = samples.reward[0, :]\n next_obs = prev_obs[0]\n t_next_obs = prev_obs[0]\n for t in range(T):\n mu_loss += self.obs_cost_fn(next_obs)\n if t > 0 and done[t - 1]:\n next_obs = prev_obs[t]\n else:\n next_obs = self.agent.predict_next_obs_at_mu(\n next_obs, prev_action, prev_reward)\n # next_obs = self.agent.predict_obs_delta(\n # prev_obs[t], prev_action, prev_reward, samples.action[t], train=False).cpu() + prev_obs[t]\n # print(\"delta_prediction:\", t_next_obs)\n \n #######################################################\n if self.update_counter % (self.policy_update_interval) == 0:\n if t > 0 and done[t - 1]:\n t_next_obs = prev_obs[t]\n else:\n t_next_obs = self.agent.predict_obs_delta(\n t_next_obs, prev_action, prev_reward, samples.action[t], train=False).cpu() + t_next_obs\n for dim in range(n_obs_dim):\n # self.plotter.plot('multi_dim='+str(dim), 'predict',\n # 'Model Multi-Step Prediction dim='+str(dim), [t], next_obs[:, dim].data.cpu().numpy(), update='append')\n \n self.plotter.plot('multi_dim='+str(dim), 'predict',\n 'Model One-Step Prediction dim='+str(dim), [t], t_next_obs[:, dim].data.cpu().numpy(), update='append')\n #######################################################\n\n return mu_loss\n\n def d_loss(self, samples, itr):\n mml = ExactMarginalLogLikelihood(\n self.agent.d_model.likelihood, self.agent.d_model.gp)\n obs_delta = samples.observation - samples.prev_observation\n if itr == 0:\n self.agent.d_model.set_train_data(samples.prev_observation.float().to(\n self.agent.device), samples.action.float().to(self.agent.device), obs_delta.float().to(self.agent.device))\n # self.agent.d_model.randomize()\n pred_obs_delta = self.agent.predict_obs_delta(samples.prev_observation,\n samples.prev_observation, samples.reward,\n samples.action)\n # next_obs = torch.clamp(\n # next_obs, -samples.env.observation_space.high, samples.env.observation_space.high)\n d_loss = -mml(pred_obs_delta, obs_delta.view(obs_delta.shape[0]*obs_delta.shape[1], -1).cuda())\n \n return d_loss\n\n def optim_state_dict(self):\n return dict(d=self.d_optimizer.state_dict(),\n mu=self.mu_optimizer.state_dict())\n\n def load_optim_state_dict(self, state_dict):\n self.d_optimizer.load_state_dict(state_dict[\"d\"])\n self.mu_optimizer.load_state_dict(state_dict[\"mu\"])\n\n def set_requires_grad(self, nets, requires_grad=False):\n \"\"\"Set requies_grad=Fasle for all the networks to avoid unnecessary computations\n Parameters:\n nets (network list) -- a list of networks\n requires_grad (bool) -- whether the networks require gradients or not\n \"\"\"\n if not isinstance(nets, list):\n nets = [nets]\n for net in nets:\n if net is not None:\n for param in net.parameters():\n param.requires_grad = requires_grad\n"
},
{
"alpha_fraction": 0.6394813656806946,
"alphanum_fraction": 0.6516101956367493,
"avg_line_length": 33.14285659790039,
"blob_id": "7df977021574c00a2d3c1517a13640f3cbc46880",
"content_id": "ec568bc24d74aae6511ae2ee09c09c0ffeac8e05",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2391,
"license_type": "permissive",
"max_line_length": 89,
"num_lines": 70,
"path": "/examples/test_example.py",
"repo_name": "jaztsong/rlpyt",
"src_encoding": "UTF-8",
"text": "\n\"\"\"\nRuns one instance of the environment and optimizes using the Soft Actor\nCritic algorithm. Can use a GPU for the agent (applies to both sample and\ntrain). No parallelism employed, everything happens in one python process; can\nbe easier to debug.\n\nRequires OpenAI gym (and maybe mujoco). If not installed, move on to next\nexample.\n\n\"\"\"\n\nfrom rlpyt.samplers.serial.sampler import SerialSampler\nfrom rlpyt.envs.gym import make as gym_make\nfrom rlpyt.algos.mb.gp_mlp import GP_Mlp\nfrom rlpyt.agents.mb.gp_mlp_agent import GP_MlpAgent\nfrom rlpyt.runners.minibatch_rl import MinibatchRlEval\nfrom rlpyt.utils.logging.context import logger_context\nimport torch\n\n\ndef build_and_train(env_id=\"Hopper-v3\", run_ID=0, cuda_idx=None):\n sampler = SerialSampler(\n EnvCls=gym_make,\n env_kwargs=dict(id=env_id),\n eval_env_kwargs=dict(id=env_id),\n batch_T=50, # One time-step per sampler iteration.\n batch_B=1, # One environment (i.e. sampler Batch dimension).\n max_decorrelation_steps=0,\n eval_n_envs=2,\n eval_max_steps=int(51e3),\n eval_max_trajectories=200,\n )\n # The cost function for InvertedPendulumBulletEnv\n def obs_cost_fn(x):\n target = torch.FloatTensor([0,0,1,0,0])\n c = (x - target)**2\n c = -c.sum(dim=1)\n return -c.exp()\n algo = GP_Mlp(obs_cost_fn=obs_cost_fn) # Run with defaults.\n agent = GP_MlpAgent()\n runner = MinibatchRlEval(\n algo=algo,\n agent=agent,\n sampler=sampler,\n n_steps=1e6,\n log_interval_steps=200,\n affinity=dict(cuda_idx=cuda_idx),\n )\n config = dict(env_id=env_id)\n name = \"gp_mlp_\" + env_id\n log_dir = \"example_1\"\n with logger_context(log_dir, run_ID, name, config, snapshot_mode='last'):\n runner.train()\n\n\n\nif __name__ == \"__main__\":\n import argparse\n parser = argparse.ArgumentParser(\n formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument('--env_id', help='environment ID',\n default='InvertedPendulumBulletEnv-v0')\n parser.add_argument('--run_ID', help='run identifier (logging)', type=int, default=0)\n parser.add_argument('--cuda_idx', help='gpu to use ', type=int, default=0)\n args = parser.parse_args()\n build_and_train(\n env_id=args.env_id,\n run_ID=args.run_ID,\n cuda_idx=args.cuda_idx,\n )\n"
},
{
"alpha_fraction": 0.6036036014556885,
"alphanum_fraction": 0.6063756346702576,
"avg_line_length": 34.19512176513672,
"blob_id": "eac248e2bc86e0eee56c6c02ee91ff430d9b862d",
"content_id": "2ed709a876d2a0f21ec65bb049f9c2d8aac78654",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1443,
"license_type": "permissive",
"max_line_length": 82,
"num_lines": 41,
"path": "/rlpyt/models/mb/smgpr.py",
"repo_name": "jaztsong/rlpyt",
"src_encoding": "UTF-8",
"text": "\nimport numpy as np\nimport torch\nimport gpytorch\n\nfrom rlpyt.utils.tensor import infer_leading_dims, restore_leading_dims\nfrom rlpyt.models.smgpr import MultitaskGPModel\n\n\nclass GPDynamicsModel(torch.nn.Module):\n \"\"\"Gaussian Process Model for learning environment transition.\"\"\"\n\n def __init__(\n self,\n observation_shape,\n action_size,\n num_inducing_pts\n ):\n \"\"\"Instantiate neural net according to inputs.\"\"\"\n super().__init__()\n self._obs_ndim = len(observation_shape)\n self.gp = MultitaskGPModel(\n input_size=int(np.prod(observation_shape)) + action_size,\n output_size=int(np.prod(observation_shape)),\n num_inducing_pts=num_inducing_pts,\n )\n self.likelihood = gpytorch.likelihoods.MultitaskGaussianLikelihood(\n num_tasks=int(np.prod(observation_shape)))\n def forward(self, observation, prev_action, prev_reward, action, train=False):\n lead_dim, T, B, _ = infer_leading_dims(observation,\n self._obs_ndim)\n gp_input = torch.cat(\n [observation.view(T * B, -1), action.view(T * B, -1)], dim=1)\n if train:\n gp = self.gp(gp_input)\n return gp\n\n with gpytorch.settings.fast_pred_var():\n gp = self.likelihood(self.gp(gp_input)).mean.squeeze(-1)\n\n gp = restore_leading_dims(gp, lead_dim, T, B)\n return gp"
},
{
"alpha_fraction": 0.6138527989387512,
"alphanum_fraction": 0.6207792162895203,
"avg_line_length": 38.72413635253906,
"blob_id": "382f8c1a14e11685fe12d917c58325b56ff715e8",
"content_id": "a8e6deacc5bb8152d7f22d2a95b0e66720d34711",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1155,
"license_type": "permissive",
"max_line_length": 94,
"num_lines": 29,
"path": "/rlpyt/models/mgpr.py",
"repo_name": "jaztsong/rlpyt",
"src_encoding": "UTF-8",
"text": "\nimport math\nimport torch\nimport gpytorch\n\n\nclass ExactGPModel(gpytorch.models.ExactGP):\n def __init__(self, train_x, train_y, likelihood):\n super(ExactGPModel, self).__init__(train_x, train_y, likelihood)\n self.num_out = train_y.shape[1]\n self.mean_module = gpytorch.means.ConstantMean(batch_shape=torch.Size([self.num_out]))\n self.covar_module = gpytorch.kernels.ScaleKernel(\n gpytorch.kernels.RBFKernel(ard_num_dims=train_x.shape[1],\n # lengthscale_prior = gpytorch.priors.GammaPrior(1,10),\n batch_shape=torch.Size([self.num_out])),\n batch_shape=torch.Size([self.num_out]),\n # outputscale_prior = gpytorch.priors.GammaPrior(1.5,2),\n )\n\n def forward(self, x):\n mean_x = self.mean_module(x)\n covar_x = self.covar_module(x)\n return gpytorch.distributions.MultitaskMultivariateNormal.from_batch_mvn(\n gpytorch.distributions.MultivariateNormal(mean_x, covar_x)\n )\n\n @property\n def output_size(self):\n \"\"\"Returns the final output size.\"\"\"\n return self._output_size\n\n\n"
},
{
"alpha_fraction": 0.6089207530021667,
"alphanum_fraction": 0.6121067404747009,
"avg_line_length": 40.14754104614258,
"blob_id": "628be4440101e1674b03157f5ae307df37ec89cb",
"content_id": "0448b1e55b15f455b2216ce92710a4284a8093ec",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2511,
"license_type": "permissive",
"max_line_length": 84,
"num_lines": 61,
"path": "/rlpyt/replays/model_based.py",
"repo_name": "jaztsong/rlpyt",
"src_encoding": "UTF-8",
"text": "\nimport math\nimport numpy as np\n\n\nfrom rlpyt.replays.base import BaseReplayBuffer\nfrom rlpyt.utils.buffer import buffer_from_example, get_leading_dims\nfrom rlpyt.utils.buffer import torchify_buffer\n\nclass ModelBasedBuffer(BaseReplayBuffer):\n \"\"\" A simple sequential buffer that stores pairs of dynamics/states transitions.\n It helps extract individual episodes.\n\n \"\"\"\n\n def __init__(self, example, size, B):\n self.T = T = math.ceil(size / B)\n self.B = B\n self.size = T * B\n self.t = 0 # Cursor (in T dimension).\n self.samples = buffer_from_example(example, (T, B),\n share_memory=self.async_)\n self.samples_return_ = self.samples.reward\n self.samples_done_n = self.samples.done\n self._buffer_full = False\n self.off_backward = 1 # Current invalid samples.\n self.off_forward = 1 # i.e. current cursor, prev_action overwritten.\n\n def append_samples(self, samples):\n \"\"\"Write the samples into the buffer and advance the time cursor.\n Handle wrapping of the cursor if necessary (boundary doesn't need to\n align with length of ``samples``). Compute and store returns with\n newly available rewards.\"\"\"\n # filter out the invalid states\n after_done = samples.done.squeeze().roll(1)\n #fill the very first element as valid\n after_done[0] = False \n # Extract all the valid samples\n samples = samples[(after_done == False).nonzero().squeeze()]\n T, B = get_leading_dims(samples, n_dim=2) # samples.env.reward.shape[:2]\n assert B == self.B\n t = self.t\n if t + T > self.T: # Wrap.\n idxs = np.arange(t, t + T) % self.T\n else:\n idxs = slice(t, t + T)\n self.samples[idxs] = samples\n if not self._buffer_full and t + T >= self.T:\n self._buffer_full = True # Only changes on first around.\n self.t = (t + T) % self.T\n return T, idxs # Pass these on to subclass.\n\n def sample_batch(self, batch_T):\n \"\"\"Can dynamically input length of sequences to return, by ``batch_T``,\n else if ``None`` will use interanlly set value. Returns batch with\n leading dimensions ``[batch_T, batch_B]``.\n \"\"\"\n if self.t > batch_T:\n return torchify_buffer(self.samples[0:int(batch_T)])\n # return torchify_buffer(self.samples[self.t-int(batch_T):self.t])\n else:\n return torchify_buffer(self.samples[:self.t])\n"
},
{
"alpha_fraction": 0.5794205665588379,
"alphanum_fraction": 0.5894106030464172,
"avg_line_length": 34.75,
"blob_id": "63c65d7c9c56c83bb24e365244d2d489f7c0a801",
"content_id": "fc64bb3a4ff85ac8f7dfbde70e1d8cc7b1fc8cda",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2002,
"license_type": "permissive",
"max_line_length": 86,
"num_lines": 56,
"path": "/rlpyt/models/mb/mgpr.py",
"repo_name": "jaztsong/rlpyt",
"src_encoding": "UTF-8",
"text": "\nimport numpy as np\nimport torch\nimport gpytorch\n\nfrom rlpyt.utils.tensor import infer_leading_dims, restore_leading_dims\nfrom rlpyt.models.mgpr import ExactGPModel\n\n\nclass GPDynamicsModel(torch.nn.Module):\n \"\"\"Gaussian Process Model for learning environment transition.\"\"\"\n\n def __init__(\n self,\n observation_shape,\n action_size,\n ):\n \"\"\"Instantiate GP according to inputs.\"\"\"\n super().__init__()\n self._obs_ndim = len(observation_shape)\n self.likelihood = gpytorch.likelihoods.MultitaskGaussianLikelihood(\n num_tasks=int(np.prod(observation_shape)))\n # get 10 random points as placeholder\n self.gp = ExactGPModel(\n torch.rand(10, int(np.prod(observation_shape) + action_size)), torch.rand(\n 10, int(np.prod(observation_shape))), self.likelihood\n )\n\n def set_train_data(self, observation, action, delta):\n lead_dim, T, B, _ = infer_leading_dims(observation,\n self._obs_ndim)\n X = torch.cat(\n [observation.view(T * B, -1), action.view(T * B, -1)], dim=1)\n Y = delta.view(T * B, -1)\n self.gp.set_train_data(X, Y, strict=False)\n\n def forward(self, observation, prev_action, prev_reward, action, train=False):\n lead_dim, T, B, _ = infer_leading_dims(observation,\n self._obs_ndim)\n gp_input = torch.cat(\n [observation.view(T * B, -1), action.view(T * B, -1)], dim=1)\n if train:\n gp = self.gp(gp_input)\n return gp\n\n with gpytorch.settings.fast_pred_var():\n gp = self.likelihood(self.gp(gp_input)).mean.squeeze(-1)\n\n gp = restore_leading_dims(gp, lead_dim, T, B)\n return gp\n\n def randomize(self):\n mean = 0; sigma = 1\n with torch.no_grad():\n self.gp.covar_module.base_kernel._set_lengthscale(0)\n self.gp.covar_module._set_outputscale(0)\n self.likelihood._set_noise(0.1)"
}
] | 8 |
BlakeMThorson/book-maker | https://github.com/BlakeMThorson/book-maker | 6dff45235b233703230b656659b855e95d95e8c9 | 53c6ec9f80a633b6965701eb5efbfac22419c54c | ed9290042f98aa3f1997b8c249a700f660d96849 | refs/heads/master | 2022-12-26T15:04:56.401417 | 2020-09-30T15:12:10 | 2020-09-30T15:12:10 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.47801077365875244,
"alphanum_fraction": 0.4889589846134186,
"avg_line_length": 19.286792755126953,
"blob_id": "68aa3a37bbd7cd13249e473d283c5fe7f1dd303c",
"content_id": "e5e59be1adf0a95890ec21967f4d22774bf8005a",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5389,
"license_type": "permissive",
"max_line_length": 139,
"num_lines": 265,
"path": "/bookMaker.py",
"repo_name": "BlakeMThorson/book-maker",
"src_encoding": "UTF-8",
"text": "from urllib.request import urlopen as uReq\nfrom bs4 import BeautifulSoup as Soup\nimport random\nimport json\nimport pickle\nimport glob, os\nimport shutil\nimport re\n\n#old code\n\n#regex replace\n#article = re.sub(r'(?is)</html>.+', '</html>', article)\n\n# set the filepath and load in a shapefile\n\nmap_df = gpd.read_file(fp)\n# check data type so we can see that this is not a normal dataframe, but a GEOdataframe\nmap_df.head()\n\n\n\ndef test1(A,n):\n n = n - 1 \n base = ( n * ( n + 1 ) ) / 2\n \n total = sum(A)\n return total - base\n\n\ndef test(L, A):\n n = len(L)\n if len(A) == 0:\n return n\n else:\n newList = []\n for t in range(0,n):\n newList.append(L[t])\n newList.append( [A[0],L[t]] )\n A = A[1:]\n print(newList)\n print(A)\n print(\"_________\")\n return test(newList,A)\n\n\ndef reRev(A):\n if A == \"\":\n return \"\"\n return A[-1] + reRev(A[:-1])\n\n\ndef threeWayInPlace(A):\n LI = 0\n RI = len(A)-1\n \n while LI != RI:\n #if we can swap them do it\n if A[LI] != \"r\" and A[RI] == \"r\":\n temp = A[LI]\n A[LI] = A[RI] \n A[RI] = temp\n #if our left indice tracker isn't over something that needs to be swapped increase it\n elif A[LI] == \"r\":\n LI += 1\n else:\n RI -= 1\n \n RI = len(A)-1\n \n print([LI,RI])\n \n print(A)\n \n while LI != RI:\n #if we can swap them do it\n if A[LI] != \"w\" and A[RI] == \"w\":\n temp = A[LI]\n A[LI] = A[RI] \n A[RI] = temp\n #if our left indice tracker isn't over something that needs to be swapped increase it\n elif A[LI] == \"w\":\n LI += 1\n else:\n RI -= 1 \n \n \n return A \n\n\n\ndef lics(A):\n oldMax = [[],0]\n currentMax = [[A[0]],A[0]]\n for i in range(1, len(A)):\n if A[i] > A[i-1]:\n currentMax[0].append(A[i])\n currentMax[1] += A[i]\n else:\n if currentMax[1] > oldMax[1]:\n oldMax[0] = currentMax[0]\n oldMax[1] = currentMax[1]\n currentMax = [[A[i]],A[i]]\n return oldMax\n \n\n\n \n\n\n\ndef swapInPlace(A):\n mid = A[0]\n \n #swap A[0] and the middle value\n A[0] = A[ round(len(A)/2) ]\n A[ round(len(A)/2) ] = mid\n \n #left and right indice tracker\n LI = 0\n RI = len(A)-1\n \n \n while LI != RI:\n #if we can swap them do it\n if A[LI] >= mid and A[RI] < mid:\n temp = A[LI]\n A[LI] = A[RI] \n A[RI] = temp\n #if our left indice tracker isn't over something that needs to be swapped increase it\n elif A[LI] < mid:\n LI += 1\n else:\n RI -= 1\n return A\n \n \n \n \n\n \n \n\n\n\ndef licLen(A):\n lastElement = [1]*len(A)\n \n for i in range(1, len(A)):\n if A[i] > A[i-1]:\n lastElement[i] = lastElement[i-1] + 1\n else:\n pass\n return max(lastElement)\n\n#def schedule(A,T):\n #A.sort()\n #time = 0\n #total = 0\n #for i in A:\n #if time >= T:\n #return total\n #else:\n #time += i\n #total += 1\n #return total\n \n\n\n\n\n\n\ndef makeDoc():\n newBook = open(\"Book.txt\",\"w\")\n toWrite = \"\" \n \n for i in range(250):\n print(i)\n toWrite += makeBook() + \"\\n\\n ***** \\n\\n\"\n \n newBook.write(toWrite)\n \n newBook.close()\n \n\n\ndef makeBook():\n import markovify\n \n # Get raw text as string.\n with open(\"newBook.txt\") as f:\n text = f.read()\n \n # Build the model.\n text_model = markovify.Text(text)\n \n return text_model.make_short_sentence(1800)\n\n\n\n\n\n\ndef getFiles():\n os.chdir(r\"C:\\Users\\white\\Desktop\\Book Maker\\unread\")\n books = glob.glob('*.txt')\n return books\n\ndef smallFormat(myString):\n #get rid of those foreign characters\n x = ''.join([i if ord(i) < 128 else ' ' for i in myString])\n \n #fuck capitalizations and shit\n x = x.lower()\n \n try:\n #fuck numbers\n x = re.sub(r'[\\d*:\\d*]', '', x)\n \n #get rid of the end disclaimer\n x = x[:x.index(\"end of\")]\n \n #get rid of starting credit\n x = x[x.index(\"***\\n\"):]\n except:\n pass\n \n return x\n \n\n\ndef massFormat(books):\n \n #if book exist\n try:\n newBook = open(\"newBook.txt\",\"r+\")\n toWrite = newBook.read()\n except:\n newBook = open(\"newBook.txt\",\"w\")\n toWrite = \"\"\n \n for book in books:\n print(book)\n try:\n unformBook = open(r\"C:\\Users\\white\\Desktop\\Book Maker\\unread\\{}\".format(book),encoding=\"utf8\")\n except:\n unformBook = open(r\"C:\\Users\\white\\Desktop\\Book Maker\\unread\\{}\".format(book))\n formBook = smallFormat(unformBook.read())\n toWrite += \"\\n\" + formBook\n newBook.write(toWrite)\n newBook.close()\n \n \n\ndef massMove(books):\n for book in books:\n shutil.move(r\"C:\\Users\\white\\Desktop\\Book Maker\\unread\\{}\".format(book), r\"C:\\Users\\white\\Desktop\\Book Maker\\read\\{}\".format(book))\n\ndef main():\n #get all the books as text files\n allBooks = getFiles()\n #throw all the books into a text file\n massFormat( allBooks )\n massMove( allBooks ) \n \n \n "
},
{
"alpha_fraction": 0.7820122241973877,
"alphanum_fraction": 0.7820122241973877,
"avg_line_length": 80.875,
"blob_id": "4938ab2ba083ba49b862cbbce1acc5c5a01d29db",
"content_id": "8b45e7deddfcd18265464023867d32f7e3926f56",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 656,
"license_type": "permissive",
"max_line_length": 331,
"num_lines": 8,
"path": "/README.md",
"repo_name": "BlakeMThorson/book-maker",
"src_encoding": "UTF-8",
"text": "# What is book maker?\nit takes any number of text files and combines them together into a single corpus for Markovify, it will then generate a thousand pieces of text that can be anywhere from a sentence to a paragraph. It will then take those pices of text and combine them into a single document in the style of Clement's \"The Trouble With Being Born\"\n\n# To make a new book\ntake text files from project gutenberg, throw them all in unread, and run the script. Then your new book will appear in the main folder, and the text files will be moved over to read.\n\n# How Does It Work?\nIt uses Markovify and spaCy to create more complete sentences in seconds. \n"
}
] | 2 |
btorquato70/Aula-12---exerc | https://github.com/btorquato70/Aula-12---exerc | 2b60b9ae1e9c9d5133f702d46e4c4df2aca3bf96 | f117773cfac86e1f2253eb0693b752846bb8e4f1 | 3e1cd945b81b28767ce23f7d103334de9272332d | refs/heads/master | 2022-12-14T17:15:55.753780 | 2020-09-11T16:22:43 | 2020-09-11T16:22:43 | 294,743,788 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7063829898834229,
"alphanum_fraction": 0.7106382846832275,
"avg_line_length": 35.07692337036133,
"blob_id": "f5bae675a6ed73828aca7b714c08df45f5351378",
"content_id": "fc04b95f5981995104107a70c51870fd9813ffc2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 480,
"license_type": "no_license",
"max_line_length": 176,
"num_lines": 13,
"path": "/exercicio_aula12.py",
"repo_name": "btorquato70/Aula-12---exerc",
"src_encoding": "UTF-8",
"text": "#Faça um programa que receba um número. Após isso, ele deve pedir ao usuário a quantidade solicitada de números. Ao fim, ele deve exibir a média de todos os números informados.\n\nqtd_num = float(input('Digite a quantidade desejada: '))\nvalores = []\ncont = 1\n\nwhile len(valores) != qtd_num:\n valores.append(float(input('Digite o valor {}: '.format(cont))))\n cont +=1\n\nmedia = sum(valores)/qtd_num\n\nprint('A média de todos os números informados é {}'.format(media))\n\n"
}
] | 1 |
darkfist/web-crawler | https://github.com/darkfist/web-crawler | bf75a765cd5b14e5423963f12f386e3510224ec9 | 5800196881c41edb38043888abf18d1ca1e18259 | c6b17859f8fc20fd5ee90dcdbb31d820287ff552 | refs/heads/master | 2020-09-17T11:30:18.216138 | 2016-09-09T23:40:04 | 2016-09-09T23:40:04 | 67,839,242 | 4 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.655112624168396,
"alphanum_fraction": 0.65684574842453,
"avg_line_length": 22.079999923706055,
"blob_id": "3239b60a36b63de12a543456acca5ccf8401b415",
"content_id": "4b485af1554a4abcf8effb885caff6c01010b932",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1154,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 50,
"path": "/main.py",
"repo_name": "darkfist/web-crawler",
"src_encoding": "UTF-8",
"text": "import threading\nfrom queue import Queue\nfrom spider import Spider\nfrom domain import *\nfrom general import *\n\nprint(\"\\nWelcome to this python Web Crawler. \\n\")\nproject_name = input(\"Give a name to this project: \")\nhomepage = input(\"Enter the url you want to crawl: \")\ndomain_name = get_domain_name(homepage)\nqueue_file = project_name + \"/queue.txt\"\ncrawled_file = project_name + \"/crawled.txt\"\nnumber_of_spiders = 4\nqueue = Queue()\nSpider(project_name, homepage, domain_name)\n\n\n# spider threads\ndef spiders():\n for i in range(number_of_spiders):\n t = threading.Thread(target=work)\n t.daemon = True\n t.start()\n\n\n# do the next job in queue\ndef work():\n while True:\n url = queue.get()\n Spider.crawl_page(threading.current_thread().name, url)\n queue.task_done\n\n\n# job for the spiders\ndef jobs():\n for link in file_to_set(queue_file):\n queue.put(link)\n queue.join()\n crawl()\n\n\n# crawl all the links in the queue\ndef crawl():\n queued_links = file_to_set(queue_file)\n if len(queued_links) > 0:\n print(str(len(queued_links)) + \" links in the queue\")\n jobs()\n\nspiders()\ncrawl()\n"
},
{
"alpha_fraction": 0.681034505367279,
"alphanum_fraction": 0.6982758641242981,
"avg_line_length": 24.77777862548828,
"blob_id": "d64b69adf1a897627afb3566b0f376141c488ef1",
"content_id": "21c670ab8b60d39ff7e3d31aaeff28411ef5029a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 232,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 9,
"path": "/README.md",
"repo_name": "darkfist/web-crawler",
"src_encoding": "UTF-8",
"text": "# Web Crawler\nA cool web crawler written in Python\n\n1. Run main.py\n2. Enter a name for the project.\n3. Enter the url to crawl.\n4. Sit back and relax.\n\nNote: url must be entered with \"http://\" or \"https://\" like \"http://example.com\"\n"
}
] | 2 |
SerenaQuinn/AdsGNN | https://github.com/SerenaQuinn/AdsGNN | da23b0101e5db6e41c3680473943fb64452024dc | 14c4d83b436f34a16af09a4401f6156384174fde | 4724a98638a4484924a079c59889d100fbab840c | refs/heads/main | 2023-03-04T03:36:34.852073 | 2021-02-17T04:24:51 | 2021-02-17T04:24:51 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5662747025489807,
"alphanum_fraction": 0.5726884007453918,
"avg_line_length": 38.69565200805664,
"blob_id": "f348e4dee02847791f143c108ce75ed62cf5cbdb",
"content_id": "dbc291a094a6ac84bd8b2d8d13d9e9b868f0e8cc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3742,
"license_type": "no_license",
"max_line_length": 139,
"num_lines": 92,
"path": "/KD/data_loader.py",
"repo_name": "SerenaQuinn/AdsGNN",
"src_encoding": "UTF-8",
"text": "import logging\r\nimport glob\r\nimport os\r\nfrom tqdm import tqdm\r\nimport traceback\r\nfrom itertools import cycle\r\nfrom functools import partial\r\n\r\nimport numpy as np\r\nimport torch\r\n\r\nlogger = logging.getLogger(__name__)\r\nlogging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt = '%m/%d/%Y %H:%M:%S', level = logging.INFO)\r\n\r\nclass GnnKdDataset(torch.utils.data.IterableDataset):\r\n def __init__(self, data_path, repeat=True, max_seq_len=20, column_count=5, text_separator=',', **kwargs):\r\n super().__init__()\r\n logger.info(f\"reading data from {data_path}\")\r\n self.data_path_iter = cycle([data_path]) if repeat else [data_path]\r\n self.max_seq_len = max_seq_len\r\n self.column_count = column_count\r\n self.text_separator = text_separator\r\n\r\n def __iter__(self):\r\n for data_path in self.data_path_iter:\r\n logger.info(f'loading data from {data_path}...')\r\n with open(data_path, 'r', encoding='utf-8') as reader:\r\n for line in reader:\r\n try:\r\n result = self._process_line(line)\r\n if result is not None:\r\n yield result\r\n except Exception as e:\r\n tb = traceback.format_exc()\r\n print(f\"Got exception: {e}, traceback: {tb}\")\r\n \r\n def _process_line(self, line):\r\n items = line.rstrip('\\r\\n').split('\\t')\r\n if len(items) < self.column_count:\r\n return None\r\n line_id = items[0]\r\n title = items[1]\r\n title_ids = items[2]\r\n src_emb_text = items[3]\r\n target_emb_text = items[4]\r\n\r\n input_id, attention_mask = self.tokenize(title_ids)\r\n src_emb = self.get_emb_tensor(src_emb_text)\r\n target_emb = self.get_emb_tensor(target_emb_text)\r\n data = [input_id, attention_mask, src_emb, target_emb, line_id]\r\n return data\r\n\r\n def get_emb_tensor(self, emb_text):\r\n if not emb_text:\r\n # dummy emb for empty input\r\n emb = [0.0]\r\n else:\r\n emb = [float(x) for x in emb_text.split(self.text_separator)]\r\n emb_np = np.array(emb)\r\n return torch.from_numpy(emb_np).float()\r\n\r\n def tokenize(self, ids):\r\n ids = ids.strip()\r\n if not ids:\r\n return self.get_zero_tensor(), self.get_zero_tensor()\r\n ids_tensor = torch.LongTensor([int(x) for x in ids.split(',')])\r\n input_id = torch.zeros(self.max_seq_len, dtype=torch.long)\r\n attention_mask = torch.zeros(self.max_seq_len, dtype=torch.long)\r\n input_id[:len(ids_tensor)] = ids_tensor\r\n attention_mask[:len(ids_tensor)] = torch.ones(len(ids_tensor), dtype=torch.long)\r\n return input_id, attention_mask\r\n\r\n def get_zero_tensor(self):\r\n return torch.zeros(self.max_seq_len, dtype=torch.long)\r\n\r\nclass GnnKdInferenceDataset(GnnKdDataset):\r\n def __init__(self, data_path, max_seq_len=64, column_count=3, text_separator=',', **kwargs):\r\n super().__init__(data_path, repeat=False, max_seq_len=max_seq_len, column_count=column_count, text_separator=text_separator)\r\n\r\n def _process_line(self, line):\r\n items = line.rstrip('\\r\\n').split('\\t')\r\n if len(items) < self.column_count:\r\n return None\r\n line_id = items[0]\r\n title_ids = items[1]\r\n src_emb_text = items[2]\r\n\r\n input_id, attention_mask = self.tokenize(title_ids)\r\n src_emb = self.get_emb_tensor(src_emb_text)\r\n assert src_emb.size(0) == 128, f\"assertion error: src_emb size is not 128: {src_emb}\"\r\n data = [input_id, attention_mask, src_emb, line_id]\r\n return data"
},
{
"alpha_fraction": 0.5524187684059143,
"alphanum_fraction": 0.5617818236351013,
"avg_line_length": 44.17948532104492,
"blob_id": "2a0ef7ebd41a093c95e0415f45dfefc807b768f7",
"content_id": "df77e830f4dddcd0c4782150cf6a78a20b891eaa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14098,
"license_type": "no_license",
"max_line_length": 172,
"num_lines": 312,
"path": "/model/tokenmodel/models/bi_topo_modeling.py",
"repo_name": "SerenaQuinn/AdsGNN",
"src_encoding": "UTF-8",
"text": "from models.topo_modeling import *\n\n\nclass GraphAggregation(BertSelfAttention):\n def __init__(self,config):\n super(GraphAggregation, self).__init__(config)\n self.output_attentions = False\n self.mapping_graph = True if config.mapping_graph>0 else False\n if self.mapping_graph:\n self.selfoutput = BertSelfOutput(config)\n self.intermediate = BertIntermediate(config)\n self.output = BertOutput(config)\n\n def forward(self,hidden_states,attention_mask=None,rel_pos=None,activate_station=None):\n \"\"\"\n hidden_states[:,0] for the center node, hidden_states[:,1:] for the neighbours\n hidden_states: B SN D\n attention_mask: B 1 1 SN\n rel_pos:B Head_num 1 SN\n \"\"\"\n query = self.query(hidden_states)\n key = self.key(hidden_states)\n value = self.value(hidden_states)\n station_embed = self.multi_head_attention(query=query,\n key=key,\n value=value,\n attention_mask=attention_mask,\n rel_pos=rel_pos)[0] #B 1 D\n\n if self.mapping_graph:\n attention_output = self.selfoutput(station_embed, query)\n intermediate_output = self.intermediate(attention_output)\n station_embed = self.output(intermediate_output, attention_output)\n\n if activate_station is not None:\n station_embed[:,0] = torch.mul(station_embed[:,0],activate_station.unsqueeze(1))\n station_embed = station_embed.squeeze(1)\n\n return station_embed\n\n\nclass GraphBertEncoder(nn.Module):\n def __init__(self, config):\n super(GraphBertEncoder, self).__init__()\n\n self.output_attentions = config.output_attentions\n self.output_hidden_states = config.output_hidden_states\n self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layers)])\n\n self.neighbor_type = config.neighbor_type #config.neighbor_type: 0:No neighbors; 1-2;\n if config.neighbor_type>0:\n self.graph_attention = GraphAggregation(config=config)\n\n def forward(self,\n hidden_states,\n attention_mask,\n node_mask=None,\n node_rel_pos=None,\n rel_pos=None,\n activate_station=None,\n return_last_station_emb=False):\n '''\n Args:\n hidden_states: N L D\n attention_mask: N 1 1 L\n node_mask: B subgraph_node_num(SN)\n node_rel_pos: B head_num 1 subgraph_node_num\n rel_pos: N head_num L L\n '''\n all_hidden_states = ()\n all_attentions = ()\n\n all_nodes_num,seq_length,emb_dim = hidden_states.shape\n if self.neighbor_type > 0:\n batch_size,_,_, subgraph_node_num = node_mask.shape\n\n for i, layer_module in enumerate(self.layer):\n if self.output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if self.neighbor_type > 0:\n if i > 0:\n\n hidden_states = hidden_states.view(batch_size,subgraph_node_num,seq_length,emb_dim) #B SN L D\n station_emb = hidden_states[:, :, 1] # B SN D\n station_emb = self.graph_attention(hidden_states=station_emb, attention_mask=node_mask, rel_pos=node_rel_pos, activate_station=activate_station) #B SN D\n\n #update the station in the query/key\n hidden_states[:,:,0] = station_emb\n hidden_states = hidden_states.view(all_nodes_num,seq_length,emb_dim)\n\n layer_outputs = layer_module(hidden_states, attention_mask=attention_mask, rel_pos=rel_pos)\n\n else:\n temp_attention_mask = attention_mask.clone()\n temp_attention_mask[:,:,:,0] = -10000.0\n layer_outputs = layer_module(hidden_states, attention_mask=temp_attention_mask, rel_pos=rel_pos)\n else:\n layer_outputs = layer_module(hidden_states, attention_mask=attention_mask, rel_pos=rel_pos)\n\n hidden_states = layer_outputs[0]\n\n if self.output_attentions:\n all_attentions = all_attentions + (layer_outputs[1],)\n\n # Add last layer\n if self.output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n outputs = (hidden_states,)\n if self.output_hidden_states:\n outputs = outputs + (all_hidden_states,)\n if self.output_attentions:\n outputs = outputs + (all_attentions,)\n if return_last_station_emb:\n hidden_states = hidden_states.view(batch_size, subgraph_node_num, seq_length, emb_dim) # B SN L D\n station_emb = hidden_states[:, :, 1] # B SN D\n station_emb = self.graph_attention[-1](hidden_states=station_emb, attention_mask=node_mask,rel_pos=node_rel_pos) #B D\n outputs = outputs + (station_emb,)\n\n return outputs # last-layer hidden state, (all hidden states), (all attentions), (station_emb)\n\n\n\nclass BiTopoGram(TuringNLRv3PreTrainedModel):\n def __init__(self, config):\n super(BiTopoGram, self).__init__(config=config)\n self.config = config\n self.embeddings = BertEmbeddings(config=config)\n self.encoder = GraphBertEncoder(config=config)\n\n if self.config.rel_pos_bins > 0:\n self.rel_pos_bias = nn.Linear(self.config.rel_pos_bins+self.config.neighbor_type, config.num_attention_heads,\n bias=False)\n else:\n self.rel_pos_bias = None\n\n def forward(self,\n input_ids,\n attention_mask,\n neighbor_mask=None,\n mask_self_in_graph=False,\n return_last_station_emb=False):\n '''\n Args:\n input_ids: Tensor(N:node_num,L:seq_length)\n attention_mask: Tensor(N,L)\n neighbor_mask: Tensor(B:batch_size, neighbor_num)\n\n Retures:\n last_hidden_state, (all hidden states), (all attentions), (station_emb)\n '''\n all_nodes_num,seq_length = input_ids.shape\n batch_size,subgraph_node_num = neighbor_mask.shape\n\n embedding_output, position_ids = self.embeddings(input_ids=input_ids)\n\n attention_mask = attention_mask.type(embedding_output.dtype)\n neighbor_mask = neighbor_mask.type(embedding_output.dtype)\n node_mask = None\n activate_station = None\n if self.config.neighbor_type > 0:\n station_mask = torch.ones(all_nodes_num, 1).type(attention_mask.dtype).to(attention_mask.device) #N 1\n attention_mask = torch.cat([station_mask,attention_mask],dim=-1) #N 1+L\n # only use the station for selfnode\n # attention_mask[::(subgraph_node_num),0] = 1.0\n\n # node_mask = torch.ones(batch_size,1,dtype=neighbor_mask.dtype,device=neighbor_mask.device)\n # node_mask = torch.cat([node_mask,neighbor_mask],dim=-1)\n if mask_self_in_graph:\n neighbor_mask[:,0] = 0\n activate_station = torch.sum(neighbor_mask,dim=-1)\n activate_station = activate_station.masked_fill(activate_station>0,1)\n node_mask = (1.0 - neighbor_mask[:, None, None, :]) * -10000.0\n\n extended_attention_mask = (1.0 - attention_mask[:, None, None, :]) * -10000.0\n\n if self.config.rel_pos_bins > 0:\n node_rel_pos = None\n rel_pos_mat = position_ids.unsqueeze(-2) - position_ids.unsqueeze(-1)\n rel_pos = relative_position_bucket(rel_pos_mat, num_buckets=self.config.rel_pos_bins,\n max_distance=self.config.max_rel_pos)\n\n if self.config.neighbor_type > 0:\n # rel_pos: (N,L,L) -> (N,1+L,L)\n temp_pos = torch.zeros(all_nodes_num, 1, seq_length,dtype=rel_pos.dtype,device=rel_pos.device)\n rel_pos = torch.cat([temp_pos,rel_pos], dim=1)\n # rel_pos: (N,1+L,L) -> (N,1+L,1+L)\n station_relpos = torch.full((all_nodes_num,seq_length+1,1), self.config.rel_pos_bins,dtype=rel_pos.dtype,device=rel_pos.device)\n rel_pos = torch.cat([station_relpos, rel_pos], dim=-1)\n\n #node_rel_pos:(B:batch_size, Head_num, neighbor_num+1)\n node_pos = self.config.rel_pos_bins + self.config.neighbor_type - 1\n node_rel_pos = torch.full((batch_size,subgraph_node_num,subgraph_node_num),node_pos,dtype=rel_pos.dtype,device=rel_pos.device)\n node_rel_pos = node_rel_pos*(1-torch.eye(subgraph_node_num).to(node_rel_pos.device)).to(rel_pos.dtype)\n node_rel_pos = F.one_hot(node_rel_pos, num_classes=self.config.rel_pos_bins + self.config.neighbor_type).type_as(\n embedding_output)\n node_rel_pos = self.rel_pos_bias(node_rel_pos).permute(0, 3, 1, 2)\n\n # rel_pos: (N,Head_num,1+L,1+L)\n rel_pos = F.one_hot(rel_pos, num_classes=self.config.rel_pos_bins + self.config.neighbor_type).type_as(\n embedding_output)\n rel_pos = self.rel_pos_bias(rel_pos).permute(0, 3, 1, 2)\n\n else:\n node_rel_pos = None\n rel_pos = None\n\n if self.config.neighbor_type > 0:\n # Add station_placeholder\n station_placeholder = torch.zeros(all_nodes_num, 1, embedding_output.size(-1)).type(\n embedding_output.dtype).to(embedding_output.device)\n embedding_output = torch.cat([station_placeholder, embedding_output], dim=1) # N 1+L D\n\n encoder_outputs = self.encoder(\n embedding_output,\n attention_mask=extended_attention_mask,\n node_mask=node_mask,\n node_rel_pos=node_rel_pos,\n rel_pos=rel_pos,\n activate_station=activate_station,\n return_last_station_emb=return_last_station_emb)\n\n return encoder_outputs\n\n\nclass BiTopoGramForNeighborPredict(GraphTuringNLRPreTrainedModel):\n def __init__(self,config):\n super().__init__(config)\n self.bert = BiTopoGram(config)\n self.cls = BertLMLoss(config)\n if config.graph_transform > 0:\n self.graph_transform = nn.Linear(config.hidden_size*2,config.hidden_size)\n self.init_weights()\n\n def retrieve_loss(self,q,k):\n score = torch.matmul(q, k.transpose(0, 1))\n loss = F.cross_entropy(score,torch.arange(start=0, end=score.shape[0],\n dtype=torch.long, device=score.device))\n return loss\n\n def forward(self,\n input_ids_query,\n attention_masks_query,\n masked_lm_labels_query,\n mask_query,\n input_ids_key,\n attention_masks_key,\n masked_lm_labels_key,\n mask_key,\n neighbor_num,\n mask_self_in_graph=False,\n mlm_loss=True,\n return_last_station_emb=False):\n '''\n Args:\n input_ids: Tensor(batch_size*(neighbor_num+1),seq_length)\n '''\n assert input_ids_query.size(0)==masked_lm_labels_query.size(0)*(neighbor_num+1) \\\n and input_ids_key.size(0)==masked_lm_labels_key.size(0)*(neighbor_num+1)\n\n all_nodes_num = mask_query.shape[0]\n batch_size = all_nodes_num//(neighbor_num+1)\n neighbor_mask_query = mask_query.view(batch_size,(neighbor_num+1))\n neighbor_mask_key = mask_key.view(batch_size,(neighbor_num+1))\n\n hidden_states_query = self.bert(input_ids_query, attention_masks_query,\n neighbor_mask=neighbor_mask_query,\n mask_self_in_graph=mask_self_in_graph,\n return_last_station_emb=return_last_station_emb\n )\n hidden_states_key = self.bert(input_ids_key, attention_masks_key,\n neighbor_mask=neighbor_mask_key,\n mask_self_in_graph=mask_self_in_graph,\n return_last_station_emb=return_last_station_emb\n )\n last_hidden_states_query = hidden_states_query[0]\n last_hidden_states_key = hidden_states_key[0]\n\n #delete the station_placeholder hidden_state:(N,1+L,D)->(N,L,D)\n last_hidden_states_query = last_hidden_states_query[:,1:]\n last_hidden_states_key = last_hidden_states_key[:, 1:]\n\n #hidden_state:(N,L,D)->(B,L,D)\n query = last_hidden_states_query[::(neighbor_num+1)]\n key = last_hidden_states_key[::(neighbor_num+1)]\n\n masked_lm_loss = 0\n if mlm_loss:\n masked_lm_loss = self.cls(query,\n self.bert.embeddings.word_embeddings.weight,\n masked_lm_labels_query)\n masked_lm_loss += self.cls(key,\n self.bert.embeddings.word_embeddings.weight,\n masked_lm_labels_key)\n\n if return_last_station_emb:\n #B D\n last_neighbor_hidden_states_query = hidden_states_query[-1]\n last_neighbor_hidden_states_key = hidden_states_key[-1]\n\n query = torch.cat([query[:, 0], last_neighbor_hidden_states_query], dim=-1)\n query = self.graph_transform(query)\n key = torch.cat([key[:, 0], last_neighbor_hidden_states_key], dim=-1)\n key = self.graph_transform(key)\n\n else:\n query = query[:,0]\n key = key[:,0]\n neighbor_predict_loss = self.retrieve_loss(query, key)\n\n return masked_lm_loss+neighbor_predict_loss\n\n\n"
},
{
"alpha_fraction": 0.6428108215332031,
"alphanum_fraction": 0.6484324336051941,
"avg_line_length": 49.411109924316406,
"blob_id": "ae2843841e2dd8b9a64248eecaeeb7bb90c0cbae",
"content_id": "2079bb0c0df745b603fb39b3d7510ddeb6022548",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4625,
"license_type": "no_license",
"max_line_length": 161,
"num_lines": 90,
"path": "/KD/models.py",
"repo_name": "SerenaQuinn/AdsGNN",
"src_encoding": "UTF-8",
"text": "import os\r\nimport numpy as np\r\nimport torch\r\nimport torch.nn as nn\r\nimport torch.nn.functional as F\r\n\r\nfrom transformers import AutoTokenizer, AutoModel, BertConfig, BertModel\r\n\r\n# Pooling strategies\r\ndef get_pooled_output(sequence_output, pooled_output, all_hidden_states, layer, attention_mask):\r\n return pooled_output # [batch, hidden_size]\r\ndef get_first_token_output(sequence_output, pooled_output, all_hidden_states, layer, attention_mask):\r\n # all_hidden_states is: embedding + all layers of hidden output: tuple (size layer_count+1) of [batch_size, max_seq_len, hidden_size], last layer is -1\r\n return all_hidden_states[layer][:,0,:] # [batch_size, hidden_size]\r\ndef get_reduce_mean_output(sequence_output, pooled_output, all_hidden_states, layer, attention_mask):\r\n target_layer_hidden_states = all_hidden_states[layer] # [batch_size, max_seq_len, hidden_size]\r\n output = torch.sum(target_layer_hidden_states * attention_mask.unsqueeze(-1), 1) / (torch.sum(attention_mask, -1, keepdim=True) + 1e-10)\r\n return output # [batch_size, hidden_size]\r\ndef get_reduce_max_output(sequence_output, pooled_output, all_hidden_states, layer, attention_mask):\r\n pass\r\ndef get_reduce_mean_max_output(sequence_output, pooled_output, all_hidden_states, layer, attention_mask):\r\n pass\r\n\r\npooling_method_map = {\r\n \"pooled\": get_pooled_output,\r\n \"first_token\": get_first_token_output,\r\n \"reduce_mean\": get_reduce_mean_output,\r\n \"reduce_max\": get_reduce_max_output,\r\n \"reduce_mean_max\": get_reduce_mean_max_output\r\n}\r\n\r\nclass TransformerEncoder(nn.Module):\r\n def __init__(self, pretrained_weights, dense_sizes, pooling_strategy='reduce_mean', layer=-1, dropout_rate=0.2, use_src_emb=False):\r\n super().__init__()\r\n path_lower = pretrained_weights.lower()\r\n if 'web' in path_lower and 'bert' in path_lower:\r\n config_path = os.path.join(pretrained_weights, \"Web-Bert-V5_config.json\")\r\n model_path = os.path.join(pretrained_weights, \"Web-Bert-V5.pt\")\r\n config = BertConfig.from_json_file(config_path)\r\n self.transformer_model = BertModel(config)\r\n self.transformer_model.load_state_dict(torch.load(model_path))\r\n self.pooling_method = pooling_method_map[\"pooled\"]\r\n print(f\"Loaded web bert with config: {config_path}, and model: {model_path}\")\r\n else:\r\n self.transformer_model = AutoModel.from_pretrained(pretrained_weights)\r\n self.pooling_method = pooling_method_map[pooling_strategy]\r\n self.layer = layer\r\n self.use_src_emb = use_src_emb\r\n self.dropout = nn.Dropout(dropout_rate)\r\n dense_layers = []\r\n input_size = self.transformer_model.config.hidden_size\r\n if self.use_src_emb:\r\n input_size += int(dense_sizes.split(',')[-1])\r\n for dense_size in [int(x) for x in dense_sizes.split(',')]:\r\n dense_layers.append(nn.Linear(input_size, dense_size))\r\n input_size = dense_size\r\n self.dense_laysers = nn.ModuleList(dense_layers)\r\n\r\n def forward(self, input_ids, attention_mask, src_emb):\r\n sequence_output, pooled_output, all_hidden_states = self.transformer_model(input_ids=input_ids, attention_mask=attention_mask, output_hidden_states=True)\r\n transformer_encoding = self.pooling_method(sequence_output, pooled_output, all_hidden_states, self.layer, attention_mask)\r\n if self.use_src_emb:\r\n output = torch.cat([transformer_encoding, src_emb], 1)\r\n else:\r\n output = transformer_encoding\r\n for i in range(len(self.dense_laysers)-1):\r\n output = F.relu(self.dense_laysers[i](output))\r\n output = self.dropout(output)\r\n output = self.dense_laysers[-1](output)\r\n output = F.normalize(output, dim=-1, p=2)\r\n return output\r\n\r\nclass MLP(nn.Module):\r\n def __init__(self, input_size, dense_sizes, dropout_rate=0.2):\r\n super().__init__()\r\n self.dropout = nn.Dropout(dropout_rate)\r\n dense_layers = []\r\n for dense_size in [int(x) for x in dense_sizes.split(',')]:\r\n dense_layers.append(nn.Linear(input_size, dense_size))\r\n input_size = dense_size\r\n self.dense_laysers = nn.ModuleList(dense_layers)\r\n\r\n def forward(self, src_emb):\r\n output = src_emb\r\n for i in range(len(self.dense_laysers)-1):\r\n output = F.relu(self.dense_laysers[i](output))\r\n output = self.dropout(output)\r\n output = self.dense_laysers[-1](output)\r\n output = F.normalize(output, dim=-1, p=2)\r\n return output"
},
{
"alpha_fraction": 0.535424530506134,
"alphanum_fraction": 0.5470516681671143,
"avg_line_length": 42.24309539794922,
"blob_id": "d7a41a692beef9c5ef3bac39c21a9fcdbb739ddc",
"content_id": "24fd30eec79b204a604386560e5bfcf58d0786af",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 15653,
"license_type": "no_license",
"max_line_length": 241,
"num_lines": 362,
"path": "/model/tokenmodel/models/data_handler_4_graph_only_title.py",
"repo_name": "SerenaQuinn/AdsGNN",
"src_encoding": "UTF-8",
"text": "import random\nimport numpy as np\nfrom dataclasses import dataclass\nfrom typing import Any, Dict, List, Tuple, Callable\nfrom torch.utils.data.dataset import IterableDataset\nimport torch\nfrom torch.nn.utils.rnn import pad_sequence\nimport json\nimport os\nfrom queue import Queue\nfrom filelock import FileLock\n\nfrom transformers.utils import logging\nfrom transformers import BertTokenizerFast\nfrom concurrent.futures import ThreadPoolExecutor\n\nlogger = logging.get_logger(__name__)\n\n\nclass DatasetForMatching(IterableDataset):\n def __init__(\n self,\n tokenizer: BertTokenizerFast,\n file_path: str,\n neighbor_num:int,\n overwrite_cache=False,\n tokenizing_batch_size=32768\n ):\n directory, filename = os.path.split(file_path)\n cached_features_file = os.path.join(\n directory,\n \"cached_{}_{}\".format(\n tokenizer.__class__.__name__,\n filename,\n ),\n )\n\n # Make sure only the first process in distributed training processes the dataset,\n # and the others will use the cache.\n lock_path = cached_features_file + \".lock\"\n\n # Input file format:\n # One title and one description per line, split by '\\t'.\n #\n # Example:\n # US-12509721$$17017982 |*| alberta ferretti girl sweatshirt dark blue size 14 100% cotton |'| |'| |'| |'| |'| \t US-12520123$$17017982 |*| alberta ferretti girl sweatshirt black size 12 100% paper |'| |'| |'| |'| |'| \t 1\n # catch105168$$6298 |*| karcher g3200xk 3200 psi (gas-cold water) pressure washer w/ kohler engine |'| |'| |'| |'| |'| \t catchCMFSBMPN-105168$$6298 |*| karcher 1.107-388.0 |'| |'| |'| |'| |'| \t 1\n\n with FileLock(lock_path):\n if os.path.exists(cached_features_file + \".finish\") and not overwrite_cache:\n self.data_file = open(cached_features_file, \"r\", encoding=\"utf-8\")\n else:\n logger.info(f\"Creating features from dataset file at {directory}\")\n batch_query, batch_key = [], []\n with open(file_path, encoding=\"utf-8\") as f, open(cached_features_file, \"w\", encoding=\"utf-8\")as fout:\n for line in f:\n line = line.strip()\n if not line: continue\n query_and_nn,key_and_nn=line.strip('\\n').split('\\t')[:2]\n for query in query_and_nn.split(\"|\\'|\"):\n query=query.strip()\n if not query:\n batch_query.append(\"\")\n else:\n # batch_query.append(query.split(\"|*|\")[1].strip())\n batch_query.append(query)\n\n for key in key_and_nn.split(\"|\\'|\"):\n key=key.strip()\n if not key:\n batch_key.append(\"\")\n else:\n # batch_key.append(key.split(\"|*|\")[1].strip())\n batch_key.append(key)\n if len(batch_query) >= tokenizing_batch_size:\n tokenized_result_query = tokenizer.batch_encode_plus(batch_query,add_special_tokens=False)\n tokenized_result_key = tokenizer.batch_encode_plus(batch_key,add_special_tokens=False)\n samples=[[],[]]\n for j,(tokens_query, tokens_key) in enumerate(zip(tokenized_result_query['input_ids'],\n tokenized_result_key['input_ids'])):\n samples[0].append(tokens_query)\n samples[1].append(tokens_key)\n if j%(neighbor_num+1)==neighbor_num:\n fout.write(json.dumps(samples)+'\\n')\n samples=[[],[]]\n batch_query, batch_key = [], []\n\n if len(batch_query) > 0:\n tokenized_result_query = tokenizer.batch_encode_plus(batch_query, add_special_tokens=False)\n tokenized_result_key = tokenizer.batch_encode_plus(batch_key, add_special_tokens=False)\n samples = [[], []]\n for j, (tokens_query, tokens_key) in enumerate(zip(tokenized_result_query['input_ids'],\n tokenized_result_key['input_ids'])):\n samples[0].append(tokens_query)\n samples[1].append(tokens_key)\n if j % (neighbor_num + 1) == neighbor_num:\n fout.write(json.dumps(samples) + '\\n')\n samples = [[], []]\n batch_query, batch_key = [], []\n logger.info(f\"Finish creating\")\n with open(cached_features_file + \".finish\", \"w\", encoding=\"utf-8\"):\n pass\n self.data_file = open(cached_features_file, \"r\", encoding=\"utf-8\")\n\n def __iter__(self):\n for line in self.data_file:\n tokens_title = json.loads(line)\n yield tokens_title\n\n\n@dataclass\nclass DataCollatorForMatching:\n \"\"\"\n Data collator used for language modeling.\n - collates batches of tensors, honoring their tokenizer's pad_token\n - preprocesses batches for masked language modeling\n \"\"\"\n\n tokenizer: BertTokenizerFast\n mlm: bool\n neighbor_num:int\n neighbor_mask:bool\n block_size: int\n mlm_probability: float = 0.15\n\n def __call__(self, samples: List[List[List[List[int]]]]) -> Dict[str, torch.Tensor]:\n input_id_queries=[]\n attention_mask_queries=[]\n mask_queries=[]\n input_id_keys=[]\n attention_mask_keys=[]\n mask_keys=[]\n for i, sample in (enumerate(samples)):\n input_id_queries_and_nn,attention_mask_queries_and_nn,mask_query,input_id_keys_and_nn,attention_mask_keys_and_nn,mask_key = self.create_training_sample(sample)\n input_id_queries.extend(input_id_queries_and_nn)\n attention_mask_queries.extend(attention_mask_queries_and_nn)\n mask_queries.extend(mask_query)\n input_id_keys.extend(input_id_keys_and_nn)\n attention_mask_keys.extend(attention_mask_keys_and_nn)\n mask_keys.extend(mask_key)\n if self.mlm:\n input_id_queries, mlm_labels_queries = self.mask_tokens(self._tensorize_batch(input_id_queries, self.tokenizer.pad_token_id), self.tokenizer.mask_token_id)\n input_id_keys, mlm_labels_keys = self.mask_tokens(self._tensorize_batch(input_id_keys, self.tokenizer.pad_token_id), self.tokenizer.mask_token_id)\n else:\n input_id_queries = self._tensorize_batch(input_id_queries, self.tokenizer.pad_token_id)\n input_id_keys = self._tensorize_batch(input_id_keys, self.tokenizer.pad_token_id)\n mask_queries=torch.tensor(mask_queries)\n mask_keys=torch.tensor(mask_keys)\n return {\n \"input_id_query\": input_id_queries,\n \"attention_masks_query\": self._tensorize_batch(attention_mask_queries, 0),\n \"masked_lm_labels_query\": mlm_labels_queries if self.mlm else None,\n \"mask_query\":mask_queries,\n \"input_id_key\": input_id_keys,\n \"attention_masks_key\": self._tensorize_batch(attention_mask_keys, 0),\n \"masked_lm_labels_key\": mlm_labels_keys if self.mlm else None,\n \"mask_key\":mask_keys,\n }\n\n def _tensorize_batch(self, examples: List[torch.Tensor], padding_value) -> torch.Tensor:\n length_of_first = examples[0].size(0)\n are_tensors_same_length = all(x.size(0) == length_of_first for x in examples)\n if are_tensors_same_length:\n return torch.stack(examples, dim=0)\n else:\n return pad_sequence(examples, batch_first=True, padding_value=padding_value)\n\n def create_training_sample(self, sample: List[List[List[int]]]):\n \"\"\"Creates a training sample from the tokens of a title.\"\"\"\n\n max_num_tokens = self.block_size - self.tokenizer.num_special_tokens_to_add(pair=False)\n\n token_queries,token_keys = sample\n\n mask_queries, mask_keys = [], []\n query_neighbor_list=[]\n key_neighbor_list=[]\n for i, (token_query, token_key) in enumerate(zip(token_queries, token_keys)):\n if len(token_query)==0:\n mask_queries.append(torch.tensor(0))\n else:\n if i!=0: query_neighbor_list.append(i)\n mask_queries.append(torch.tensor(1))\n if len(token_key)==0:\n mask_keys.append(torch.tensor(0))\n else:\n if i!=0: key_neighbor_list.append(i)\n mask_keys.append(torch.tensor(1))\n\n if self.neighbor_mask:\n if np.random.random() < 0.5:\n mask_query_neighbor_num = min(np.random.randint(1, self.neighbor_num),len(query_neighbor_list))\n else:\n mask_query_neighbor_num = 0\n if np.random.random() < 0.5:\n mask_key_neighbor_num = min(np.random.randint(1, self.neighbor_num),len(key_neighbor_list))\n else:\n mask_key_neighbor_num = 0\n\n mask_query_set = set(\n np.random.choice(query_neighbor_list, mask_query_neighbor_num, replace=False))\n mask_key_set = set(\n np.random.choice(key_neighbor_list, mask_key_neighbor_num, replace=False))\n\n input_id_queries,input_id_keys,attention_mask_queries,attention_mask_keys=[],[],[],[]\n for i,(token_query,token_key) in enumerate(zip(token_queries,token_keys)):\n input_id_queries.append(torch.tensor(self.tokenizer.build_inputs_with_special_tokens(token_query[:max_num_tokens])))\n input_id_keys.append(torch.tensor(self.tokenizer.build_inputs_with_special_tokens(token_key[:max_num_tokens])))\n attention_mask_queries.append(torch.tensor([1]*len(input_id_queries[-1])))\n attention_mask_keys.append(torch.tensor([1]*len(input_id_keys[-1])))\n if self.neighbor_mask:\n if i in mask_query_set:\n mask_queries[i]=torch.tensor(0)\n if i in mask_key_set:\n mask_keys[i]=torch.tensor(0)\n\n return input_id_queries,attention_mask_queries,mask_queries,input_id_keys,attention_mask_keys,mask_keys\n\n def mask_tokens(self, inputs_origin: torch.Tensor, mask_id: int) -> Tuple[torch.Tensor, torch.Tensor]:\n \"\"\"\n Prepare masked tokens inputs/labels for masked language modeling.\n \"\"\"\n inputs = inputs_origin.clone()\n labels = torch.zeros((inputs.shape[0]//(self.neighbor_num+1),inputs.shape[1]),dtype=torch.long)-100\n num=0\n for i, input_origin in enumerate(inputs_origin):\n if i%(self.neighbor_num+1)!=0:continue\n mask_num, valid_length = 0, 0\n start_indexes=[]\n for index, x in enumerate(input_origin):\n if int(x) not in self.tokenizer.all_special_ids:\n valid_length += 1\n start_indexes.append(index)\n labels[num][index] = -99\n random.shuffle(start_indexes)\n while mask_num / valid_length < self.mlm_probability:\n start_index = start_indexes.pop()\n span_length = 1e9\n while span_length > 10: span_length = np.random.geometric(0.2)\n for j in range(start_index, min(start_index+span_length,len(input_origin))):\n if labels[num][j] != -99: continue\n labels[num][j] = input_origin[j].clone()\n rand=np.random.random()\n if rand<0.8:\n inputs[i][j] = mask_id\n elif rand<0.9:\n inputs[i][j]=np.random.randint(0,self.tokenizer.vocab_size-1)\n mask_num += 1\n if mask_num / valid_length >= self.mlm_probability:\n break\n labels[num] = torch.masked_fill(labels[num], labels[num] < 0, -100)\n num+=1\n return inputs, labels\n\n\n@dataclass\nclass MultiProcessDataLoaderForMatching:\n dataset: IterableDataset\n batch_size: int\n collate_fn: Callable\n local_rank: int\n world_size: int\n prefetch_step: Any\n end: Any\n drop_last: bool = True\n\n def _start(self):\n self.end.value = False\n self.aval_count = 0\n self.outputs = Queue(10)\n self.pool = ThreadPoolExecutor(1)\n self.pool.submit(self._produce)\n\n def sync(self):\n while sum(self.prefetch_step) != self.prefetch_step[self.local_rank] * self.world_size:\n if self.end.value: break\n\n def _produce(self):\n for batch in self._generate_batch():\n self.prefetch_step[self.local_rank] += 1\n self.sync()\n if self.end.value:\n break\n self.outputs.put(batch)\n self.aval_count += 1\n # print(self.local_rank, self.prefetch_step[self.local_rank])\n self.pool.shutdown(wait=False)\n raise\n\n def _generate_batch(self):\n batch = []\n for i, sample in enumerate(self.dataset):\n if i % self.world_size != self.local_rank: continue\n batch.append(sample)\n if len(batch)>=self.batch_size:\n yield self.collate_fn(batch[:self.batch_size])\n batch = batch[self.batch_size:]\n else:\n if len(batch) > 0 and not self.drop_last:\n yield self.collate_fn(batch)\n batch = []\n self.end.value = True\n\n def __iter__(self):\n self._start()\n return self\n\n def __next__(self):\n if self.aval_count == 0 and self.end.value:\n raise StopIteration\n next_batch = self.outputs.get()\n self.outputs.task_done()\n self.aval_count -= 1\n return next_batch\n\n@dataclass\nclass SingleProcessDataLoaderForMatching:\n dataset: IterableDataset\n batch_size: int\n collate_fn: Callable\n drop_last: bool = True\n\n def _start(self):\n self.end = False\n self.aval_count = 0\n self.outputs = Queue(10)\n self.pool = ThreadPoolExecutor(1)\n self.pool.submit(self._produce)\n\n def _produce(self):\n for batch in self._generate_batch():\n if self.end:\n break\n self.outputs.put(batch)\n self.aval_count += 1\n self.pool.shutdown(wait=False)\n raise\n\n def _generate_batch(self):\n batch = []\n for i, sample in enumerate(self.dataset):\n batch.append(sample)\n if len(batch)>=self.batch_size:\n yield self.collate_fn(batch[:self.batch_size])\n batch = batch[self.batch_size:]\n else:\n if len(batch) > 0 and not self.drop_last:\n yield self.collate_fn(batch)\n batch = []\n self.end = True\n\n def __iter__(self):\n self._start()\n return self\n\n def __next__(self):\n if self.aval_count == 0 and self.end:\n raise StopIteration\n next_batch = self.outputs.get()\n self.outputs.task_done()\n self.aval_count -= 1\n return next_batch"
},
{
"alpha_fraction": 0.5099099278450012,
"alphanum_fraction": 0.5636035799980164,
"avg_line_length": 38.838233947753906,
"blob_id": "0fffbae7ac78f6a7bcfd7b65ad21a1202142e2c7",
"content_id": "0ad5317a813e77ffd94d5b2e9be6aa48531ac93a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2775,
"license_type": "no_license",
"max_line_length": 139,
"num_lines": 68,
"path": "/KD/run.py",
"repo_name": "SerenaQuinn/AdsGNN",
"src_encoding": "UTF-8",
"text": "import os\r\nimport logging\r\n\r\nlogging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt = '%m/%d/%Y %H:%M:%S', level = logging.INFO)\r\nlogger = logging.getLogger(__name__)\r\n\r\ndef run(cmd):\r\n logger.info(f\"run command: {cmd}\")\r\n retval = os.system(cmd)\r\n if retval != 0:\r\n raise Exception(f\"Finished cmd {cmd} with return value: {retval}\")\r\n\r\ndef train_model_w_unseen():\r\n cmd = r\"python main.py \" \\\r\n \"--mode train \" \\\r\n \"--data_path ./bert_kd_data_train.txt --valid_data_path ./bert_kd_data_valid_100k.txt \" \\\r\n \"--transformer_pretrained_weights google/bert_uncased_L-2_H-128_A-2 \" \\\r\n \"--num_data_workers 4 --pin_memory --use_src_emb \" \\\r\n \"--model_dir bert_data_kd_model_with_src_emb --max_seq_len 64 \" \\\r\n \"--max_steps 10000000 --warmup_steps 2000 \" \\\r\n \"--learning_rate 5e-5 \" \\\r\n \"--max_seq_len 64 --dense_sizes 1024,128 \" \\\r\n \"--log_steps 10 --eval_steps 1000 --save_steps 2000 --batch_size 6000 \"\r\n run(cmd)\r\n\r\ndef train_model_title_only():\r\n cmd = r\"python main.py \" \\\r\n \"--mode train \" \\\r\n \"--data_path ./bert_kd_data_train.txt --valid_data_path ./bert_kd_data_valid_100k.txt \" \\\r\n \"--transformer_pretrained_weights google/bert_uncased_L-2_H-128_A-2 \" \\\r\n \"--num_data_workers 4 --pin_memory \" \\\r\n \"--model_dir bert_data_kd_model_title_only --max_seq_len 64 \" \\\r\n \"--max_steps 10000000 --warmup_steps 2000 \" \\\r\n \"--learning_rate 5e-5 \" \\\r\n \"--max_seq_len 64 --dense_sizes 1024,128 \" \\\r\n \"--log_steps 10 --eval_steps 1000 --save_steps 2000 --batch_size 6000 \"\r\n run(cmd)\r\n\r\ndef train_model_mlp():\r\n cmd = r\"python main.py \" \\\r\n \"--mode train \" \\\r\n \"--data_path ./kd_data_train.txt --valid_data_path ./kd_data_valid_100k.txt \" \\\r\n \"--num_data_workers 0 --pin_memory --use_src_emb \" \\\r\n \"--model_dir kd_model_mlp_only --max_seq_len 64 \" \\\r\n \"--max_steps 10000000 --warmup_steps 2000 \" \\\r\n \"--learning_rate 5e-5 \" \\\r\n \"--max_seq_len 64 --dense_sizes 1024,1024,50 \" \\\r\n \"--log_steps 10 --eval_steps 1000 --save_steps 2000 --batch_size 8000 \"\r\n run(cmd)\r\n\r\ndef run_inference():\r\n cmd = r\"CUDA_VISIBLE_DEVICES= python main.py \" \\\r\n \"--mode inference \" \\\r\n \"--inference_input_path ./test_input.txt \" \\\r\n \"--inference_output_path ./test_output.txt \" \\\r\n \"--model_dir bert_data_kd_model_with_src_emb --transformer_pretrained_weights dummy \" \\\r\n \"--max_seq_len 64 --log_steps 1000 \"\r\n #\" --use_src_emb \" \\\r\n run(cmd)\r\n\r\ndef main():\r\n #train_model_title_only()\r\n #train_model_w_unseen()\r\n #train_model_mlp()\r\n run_inference()\r\n\r\nif __name__ == \"__main__\":\r\n main()"
},
{
"alpha_fraction": 0.5604540705680847,
"alphanum_fraction": 0.5681785941123962,
"avg_line_length": 47.80229949951172,
"blob_id": "7637ff13a0c7bfcc073986f34c9a1c1fdd8c83b0",
"content_id": "95ec108e3ed66a0589202ae6bc4f8aa66845868e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 21231,
"license_type": "no_license",
"max_line_length": 175,
"num_lines": 435,
"path": "/model/tokenmodel/models/topo_modeling.py",
"repo_name": "SerenaQuinn/AdsGNN",
"src_encoding": "UTF-8",
"text": "from models.retrieve_modeling import *\n\n\nclass GraphTuringNLRPreTrainedModel(TuringNLRv3PreTrainedModel):\n @classmethod\n def from_pretrained(\n cls, pretrained_model_name_or_path, reuse_position_embedding=None,\n replace_prefix=None, *model_args, **kwargs,\n ):\n model_type = kwargs.pop('model_type', 'tnlrv3')\n if model_type is not None and \"state_dict\" not in kwargs:\n if model_type in cls.supported_convert_pretrained_model_archive_map:\n pretrained_model_archive_map = cls.supported_convert_pretrained_model_archive_map[model_type]\n if pretrained_model_name_or_path in pretrained_model_archive_map:\n state_dict = get_checkpoint_from_transformer_cache(\n archive_file=pretrained_model_archive_map[pretrained_model_name_or_path],\n pretrained_model_name_or_path=pretrained_model_name_or_path,\n pretrained_model_archive_map=pretrained_model_archive_map,\n cache_dir=kwargs.get(\"cache_dir\", None), force_download=kwargs.get(\"force_download\", None),\n proxies=kwargs.get(\"proxies\", None), resume_download=kwargs.get(\"resume_download\", None),\n )\n state_dict = state_dict_convert[model_type](state_dict)\n kwargs[\"state_dict\"] = state_dict\n logger.info(\"Load HF ckpts\")\n elif os.path.isfile(pretrained_model_name_or_path):\n state_dict = torch.load(pretrained_model_name_or_path, map_location='cpu')\n kwargs[\"state_dict\"] = state_dict_convert[model_type](state_dict)\n logger.info(\"Load local ckpts\")\n elif os.path.isdir(pretrained_model_name_or_path):\n state_dict = torch.load(os.path.join(pretrained_model_name_or_path, WEIGHTS_NAME),\n map_location='cpu')\n kwargs[\"state_dict\"] = state_dict_convert[model_type](state_dict)\n logger.info(\"Load local ckpts\")\n else:\n raise RuntimeError(\"Not fined the pre-trained checkpoint !\")\n\n if kwargs[\"state_dict\"] is None:\n logger.info(\"TNLRv3 does't support the model !\")\n raise NotImplementedError()\n\n config = kwargs[\"config\"]\n state_dict = kwargs[\"state_dict\"]\n # initialize new position embeddings (From Microsoft/UniLM)\n _k = 'bert.embeddings.position_embeddings.weight'\n if _k in state_dict:\n if config.max_position_embeddings > state_dict[_k].shape[0]:\n logger.info(\"Resize > position embeddings !\")\n old_vocab_size = state_dict[_k].shape[0]\n new_postion_embedding = state_dict[_k].data.new_tensor(torch.ones(\n size=(config.max_position_embeddings, state_dict[_k].shape[1])), dtype=torch.float)\n new_postion_embedding = nn.Parameter(data=new_postion_embedding, requires_grad=True)\n new_postion_embedding.data.normal_(mean=0.0, std=config.initializer_range)\n max_range = config.max_position_embeddings if reuse_position_embedding else old_vocab_size\n shift = 0\n while shift < max_range:\n delta = min(old_vocab_size, max_range - shift)\n new_postion_embedding.data[shift: shift + delta, :] = state_dict[_k][:delta, :]\n logger.info(\" CP [%d ~ %d] into [%d ~ %d] \" % (0, delta, shift, shift + delta))\n shift += delta\n state_dict[_k] = new_postion_embedding.data\n del new_postion_embedding\n elif config.max_position_embeddings < state_dict[_k].shape[0]:\n logger.info(\"Resize < position embeddings !\")\n old_vocab_size = state_dict[_k].shape[0]\n new_postion_embedding = state_dict[_k].data.new_tensor(torch.ones(\n size=(config.max_position_embeddings, state_dict[_k].shape[1])), dtype=torch.float)\n new_postion_embedding = nn.Parameter(data=new_postion_embedding, requires_grad=True)\n new_postion_embedding.data.normal_(mean=0.0, std=config.initializer_range)\n new_postion_embedding.data.copy_(state_dict[_k][:config.max_position_embeddings, :])\n state_dict[_k] = new_postion_embedding.data\n del new_postion_embedding\n\n # initialize new rel_pos weight\n _k = 'bert.rel_pos_bias.weight'\n if _k in state_dict and state_dict[_k].shape[1] != (config.neighbor_type + config.rel_pos_bins):\n logger.info(\n f\"rel_pos_bias.weight.shape[1]:{state_dict[_k].shape[1]} != config.bus_num+config.rel_pos_bins:{config.neighbor_type + config.rel_pos_bins}\")\n old_rel_pos_bias = state_dict[_k]\n new_rel_pos_bias = torch.cat(\n [old_rel_pos_bias, old_rel_pos_bias[:, -1:].expand(old_rel_pos_bias.size(0), config.neighbor_type)], -1)\n new_rel_pos_bias = nn.Parameter(data=new_rel_pos_bias, requires_grad=True)\n state_dict[_k] = new_rel_pos_bias.data\n del new_rel_pos_bias\n\n if replace_prefix is not None:\n new_state_dict = {}\n for key in state_dict:\n if key.startswith(replace_prefix):\n new_state_dict[key[len(replace_prefix):]] = state_dict[key]\n else:\n new_state_dict[key] = state_dict[key]\n kwargs[\"state_dict\"] = new_state_dict\n del state_dict\n\n return super().from_pretrained(pretrained_model_name_or_path, *model_args, **kwargs)\n\n\nclass GraphAggregation(BertSelfAttention):\n def __init__(self,config):\n super(GraphAggregation, self).__init__(config)\n self.output_attentions = False\n self.mapping_graph = True if config.mapping_graph>0 else False\n if self.mapping_graph:\n self.selfoutput = BertSelfOutput(config)\n self.intermediate = BertIntermediate(config)\n self.output = BertOutput(config)\n\n def forward(self,hidden_states,attention_mask=None,rel_pos=None,activate_station=None):\n \"\"\"\n hidden_states[:,0] for the center node, hidden_states[:,1:] for the neighbours\n hidden_states: B SN D\n attention_mask: B 1 1 SN\n rel_pos:B Head_num 1 SN\n \"\"\"\n query = self.query(hidden_states[:, :1]) #B 1 D\n key = self.key(hidden_states)\n value = self.value(hidden_states)\n station_embed = self.multi_head_attention(query=query,\n key=key,\n value=value,\n attention_mask=attention_mask,\n rel_pos=rel_pos)[0] #B 1 D\n\n if self.mapping_graph:\n attention_output = self.selfoutput(station_embed, query)\n intermediate_output = self.intermediate(attention_output)\n station_embed = self.output(intermediate_output, attention_output)\n\n station_embed = station_embed.squeeze(1)\n if activate_station is not None:\n station_embed = torch.mul(station_embed,activate_station.unsqueeze(1))\n\n return station_embed\n\n\nclass GraphBertEncoder(nn.Module):\n def __init__(self, config):\n super(GraphBertEncoder, self).__init__()\n\n self.output_attentions = config.output_attentions\n self.output_hidden_states = config.output_hidden_states\n self.layer = nn.ModuleList([BertLayer(config) for _ in range(config.num_hidden_layers)])\n\n self.neighbor_type = config.neighbor_type #config.neighbor_type: 0:No neighbors; 1-2;\n if config.neighbor_type>0:\n self.graph_attention = GraphAggregation(config=config)\n # self.graph_attention = nn.ModuleList([GraphAggregation(config=config) for _ in range(config.num_hidden_layers)])\n\n def forward(self,\n hidden_states,\n attention_mask,\n node_mask=None,\n node_rel_pos=None,\n rel_pos=None,\n activate_station=None,\n return_last_station_emb=False):\n '''\n Args:\n hidden_states: N L D\n attention_mask: N 1 1 L\n node_mask: B subgraph_node_num(SN)\n node_rel_pos: B head_num 1 subgraph_node_num\n rel_pos: N head_num L L\n '''\n all_hidden_states = ()\n all_attentions = ()\n\n all_nodes_num,seq_length,emb_dim = hidden_states.shape\n if self.neighbor_type > 0:\n batch_size,_,_, subgraph_node_num = node_mask.shape\n\n for i, layer_module in enumerate(self.layer):\n if self.output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n if self.neighbor_type > 0:\n if i > 0:\n\n hidden_states = hidden_states.view(batch_size,subgraph_node_num,seq_length,emb_dim) #B SN L D\n station_emb = hidden_states[:, :, 1] # B SN D\n station_emb = self.graph_attention(hidden_states=station_emb, attention_mask=node_mask,rel_pos=node_rel_pos, activate_station=activate_station) # B D\n # station_emb = self.graph_attention[i-1](hidden_states=station_emb, attention_mask=node_mask, rel_pos=node_rel_pos,activate_station=activate_station) #B D\n\n #update the station in the query/key\n hidden_states[:,0,0] = station_emb\n hidden_states = hidden_states.view(all_nodes_num,seq_length,emb_dim)\n\n layer_outputs = layer_module(hidden_states, attention_mask=attention_mask, rel_pos=rel_pos)\n\n else:\n temp_attention_mask = attention_mask.clone()\n temp_attention_mask[::subgraph_node_num,:,:,0] = -10000.0\n layer_outputs = layer_module(hidden_states, attention_mask=temp_attention_mask, rel_pos=rel_pos)\n else:\n layer_outputs = layer_module(hidden_states, attention_mask=attention_mask, rel_pos=rel_pos)\n\n hidden_states = layer_outputs[0]\n\n if self.output_attentions:\n all_attentions = all_attentions + (layer_outputs[1],)\n\n # Add last layer\n if self.output_hidden_states:\n all_hidden_states = all_hidden_states + (hidden_states,)\n\n outputs = (hidden_states,)\n if self.output_hidden_states:\n outputs = outputs + (all_hidden_states,)\n if self.output_attentions:\n outputs = outputs + (all_attentions,)\n if return_last_station_emb:\n hidden_states = hidden_states.view(batch_size, subgraph_node_num, seq_length, emb_dim) # B SN L D\n station_emb = hidden_states[:, :, 1] # B SN D\n # station_emb = self.graph_attention[-1](hidden_states=station_emb, attention_mask=node_mask,rel_pos=node_rel_pos) #B D\n station_emb = self.graph_attention(hidden_states=station_emb, attention_mask=node_mask,rel_pos=node_rel_pos) #B D\n outputs = outputs + (station_emb,)\n\n return outputs # last-layer hidden state, (all hidden states), (all attentions), (station_emb)\n\n\n\nclass TopoGram(TuringNLRv3PreTrainedModel):\n def __init__(self, config):\n super(TopoGram, self).__init__(config=config)\n self.config = config\n self.embeddings = BertEmbeddings(config=config)\n self.encoder = GraphBertEncoder(config=config)\n\n if self.config.rel_pos_bins > 0:\n self.rel_pos_bias = nn.Linear(self.config.rel_pos_bins+self.config.neighbor_type, config.num_attention_heads,\n bias=False)\n else:\n self.rel_pos_bias = None\n\n def forward(self,\n input_ids,\n attention_mask,\n neighbor_mask=None,\n mask_self_in_graph=False,\n return_last_station_emb=False):\n '''\n Args:\n input_ids: Tensor(N:node_num,L:seq_length)\n attention_mask: Tensor(N,L)\n neighbor_mask: Tensor(B:batch_size, neighbor_num)\n\n Retures:\n last_hidden_state, (all hidden states), (all attentions), (station_emb)\n '''\n all_nodes_num,seq_length = input_ids.shape\n batch_size,subgraph_node_num = neighbor_mask.shape\n\n embedding_output, position_ids = self.embeddings(input_ids=input_ids)\n\n attention_mask = attention_mask.type(embedding_output.dtype)\n neighbor_mask = neighbor_mask.type(embedding_output.dtype)\n node_mask = None\n activate_station = None\n if self.config.neighbor_type > 0:\n station_mask = torch.zeros(all_nodes_num, 1).type(attention_mask.dtype).to(attention_mask.device) #N 1\n attention_mask = torch.cat([station_mask,attention_mask],dim=-1) #N 1+L\n # only use the station for selfnode\n attention_mask[::(subgraph_node_num),0] = 1.0\n\n # node_mask = torch.ones(batch_size,1,dtype=neighbor_mask.dtype,device=neighbor_mask.device)\n # node_mask = torch.cat([node_mask,neighbor_mask],dim=-1)\n if mask_self_in_graph:\n neighbor_mask[:,0] = 0\n activate_station = torch.sum(neighbor_mask,dim=-1)\n activate_station = activate_station.masked_fill(activate_station>0,1)\n node_mask = (1.0 - neighbor_mask[:, None, None, :]) * -10000.0\n\n extended_attention_mask = (1.0 - attention_mask[:, None, None, :]) * -10000.0\n\n if self.config.rel_pos_bins > 0:\n node_rel_pos = None\n rel_pos_mat = position_ids.unsqueeze(-2) - position_ids.unsqueeze(-1)\n rel_pos = relative_position_bucket(rel_pos_mat, num_buckets=self.config.rel_pos_bins,\n max_distance=self.config.max_rel_pos)\n\n if self.config.neighbor_type > 0:\n # rel_pos: (N,L,L) -> (N,1+L,L)\n temp_pos = torch.zeros(all_nodes_num, 1, seq_length,dtype=rel_pos.dtype,device=rel_pos.device)\n rel_pos = torch.cat([temp_pos,rel_pos], dim=1)\n # rel_pos: (N,1+L,L) -> (N,1+L,1+L)\n station_relpos = torch.full((all_nodes_num,seq_length+1,1), self.config.rel_pos_bins,dtype=rel_pos.dtype,device=rel_pos.device)\n rel_pos = torch.cat([station_relpos, rel_pos], dim=-1)\n\n #node_rel_pos:(B:batch_size, Head_num, neighbor_num+1)\n node_pos = self.config.rel_pos_bins + self.config.neighbor_type - 1\n node_rel_pos = torch.full((batch_size,subgraph_node_num),node_pos,dtype=rel_pos.dtype,device=rel_pos.device)\n node_rel_pos[:,0]=0\n node_rel_pos = F.one_hot(node_rel_pos, num_classes=self.config.rel_pos_bins + self.config.neighbor_type).type_as(\n embedding_output)\n node_rel_pos = self.rel_pos_bias(node_rel_pos).permute(0, 2, 1) #B head_num, neighbor_num\n node_rel_pos = node_rel_pos.unsqueeze(2) #B head_num 1 neighbor_num\n\n # rel_pos: (N,Head_num,1+L,1+L)\n rel_pos = F.one_hot(rel_pos, num_classes=self.config.rel_pos_bins + self.config.neighbor_type).type_as(\n embedding_output)\n rel_pos = self.rel_pos_bias(rel_pos).permute(0, 3, 1, 2)\n\n else:\n node_rel_pos = None\n rel_pos = None\n\n if self.config.neighbor_type > 0:\n # Add station_placeholder\n station_placeholder = torch.zeros(all_nodes_num, 1, embedding_output.size(-1)).type(\n embedding_output.dtype).to(embedding_output.device)\n embedding_output = torch.cat([station_placeholder, embedding_output], dim=1) # N 1+L D\n\n encoder_outputs = self.encoder(\n embedding_output,\n attention_mask=extended_attention_mask,\n node_mask=node_mask,\n node_rel_pos=node_rel_pos,\n rel_pos=rel_pos,\n activate_station=activate_station,\n return_last_station_emb=return_last_station_emb)\n\n return encoder_outputs\n\n\nclass TopoGramForNeighborPredict(GraphTuringNLRPreTrainedModel):\n def __init__(self,config):\n super().__init__(config)\n self.bert = TopoGram(config)\n self.cls = BertLMLoss(config)\n if config.graph_transform > 0:\n self.graph_transform = nn.Linear(config.hidden_size*2,config.hidden_size)\n self.init_weights()\n\n def retrieve_loss(self,q,k):\n score = torch.matmul(q, k.transpose(0, 1))\n loss = F.cross_entropy(score,torch.arange(start=0, end=score.shape[0],\n dtype=torch.long, device=score.device))\n return loss\n\n def forward(self,\n input_ids_query,\n attention_masks_query,\n masked_lm_labels_query,\n mask_query,\n input_ids_key,\n attention_masks_key,\n masked_lm_labels_key,\n mask_key,\n neighbor_num,\n mask_self_in_graph=False,\n mlm_loss=True,\n return_last_station_emb=False):\n '''\n Args:\n input_ids: Tensor(batch_size*(neighbor_num+1),seq_length)\n '''\n # assert input_ids_query.size(0)==masked_lm_labels_query.size(0)*(neighbor_num+1) \\\n # and input_ids_key.size(0)==masked_lm_labels_key.size(0)*(neighbor_num+1)\n\n all_nodes_num = mask_query.shape[0]\n batch_size = all_nodes_num//(neighbor_num+1)\n neighbor_mask_query = mask_query.view(batch_size,(neighbor_num+1))\n neighbor_mask_key = mask_key.view(batch_size,(neighbor_num+1))\n\n hidden_states_query = self.bert(input_ids_query, attention_masks_query,\n neighbor_mask=neighbor_mask_query,\n mask_self_in_graph=mask_self_in_graph,\n return_last_station_emb=return_last_station_emb\n )\n hidden_states_key = self.bert(input_ids_key, attention_masks_key,\n neighbor_mask=neighbor_mask_key,\n mask_self_in_graph=mask_self_in_graph,\n return_last_station_emb=return_last_station_emb\n )\n last_hidden_states_query = hidden_states_query[0]\n last_hidden_states_key = hidden_states_key[0]\n\n #delete the station_placeholder hidden_state:(N,1+L,D)->(N,L,D)\n last_hidden_states_query = last_hidden_states_query[:,1:]\n last_hidden_states_key = last_hidden_states_key[:, 1:]\n\n #hidden_state:(N,L,D)->(B,L,D)\n query = last_hidden_states_query[::(neighbor_num+1)]\n key = last_hidden_states_key[::(neighbor_num+1)]\n\n masked_lm_loss = 0\n if mlm_loss:\n masked_lm_loss = self.cls(query,\n self.bert.embeddings.word_embeddings.weight,\n masked_lm_labels_query)\n masked_lm_loss += self.cls(key,\n self.bert.embeddings.word_embeddings.weight,\n masked_lm_labels_key)\n\n if return_last_station_emb:\n #B D\n last_neighbor_hidden_states_query = hidden_states_query[-1]\n last_neighbor_hidden_states_key = hidden_states_key[-1]\n\n query = torch.cat([query[:, 0], last_neighbor_hidden_states_query], dim=-1)\n query = self.graph_transform(query)\n key = torch.cat([key[:, 0], last_neighbor_hidden_states_key], dim=-1)\n key = self.graph_transform(key)\n\n else:\n query = query[:,0]\n key = key[:,0]\n neighbor_predict_loss = self.retrieve_loss(query, key)\n\n return masked_lm_loss+neighbor_predict_loss\n\n\nclass TopoGramForDownsStream(GraphTuringNLRPreTrainedModel):\n def __init__(self,config):\n super().__init__(config)\n self.bert = TopoGram(config)\n self.init_weights()\n\n def forward(self,\n input_ids,\n attention_mask,\n neighbor_mask,\n neighbor_num,\n return_last_station_emb=False):\n assert input_ids.size(0) // (neighbor_num + 1) == neighbor_mask.size(0)\n\n outputs = self.bert(input_ids,\n attention_mask,\n neighbor_mask=neighbor_mask,\n return_last_station_emb=return_last_station_emb)\n\n # delete the station_placeholder\n last_hidden_states = outputs[0][:, 1:]\n last_hidden_states = last_hidden_states[::(neighbor_num + 1)]\n return (last_hidden_states,) if not return_last_station_emb else (last_hidden_states,outputs[-1])\n\n\n"
},
{
"alpha_fraction": 0.629462718963623,
"alphanum_fraction": 0.6345327496528625,
"avg_line_length": 47.13840866088867,
"blob_id": "f54d13c2a1daf5916d7029eac1a30f9e27d57f39",
"content_id": "d91a91fa95a0f162587d94031fd8be0c503386fe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14201,
"license_type": "no_license",
"max_line_length": 206,
"num_lines": 289,
"path": "/KD/main.py",
"repo_name": "SerenaQuinn/AdsGNN",
"src_encoding": "UTF-8",
"text": "from argparse import ArgumentError\r\nimport os\r\nimport argparse\r\nimport logging\r\nimport time\r\n\r\nimport numpy as np\r\nimport torch\r\nfrom torch.utils.data import DataLoader\r\nfrom torch.optim.lr_scheduler import LambdaLR\r\n#import horovod.torch as hvd\r\n\r\nfrom data_loader import GnnKdDataset, GnnKdInferenceDataset\r\nfrom models import TransformerEncoder, MLP\r\n\r\nfrom transformers import AdamW\r\nfrom tensorboardX import SummaryWriter\r\n\r\nlogger = logging.getLogger(__name__)\r\nlogging.basicConfig(format = '%(asctime)s - %(levelname)s - %(name)s - %(message)s', datefmt = '%m/%d/%Y %H:%M:%S', level = logging.INFO)\r\n\r\ndef parse_arguments():\r\n parser = argparse.ArgumentParser()\r\n parser.add_argument(\"--mode\", default=\"train\", type=str, required=True, help=\"train, evaluate, inference\")\r\n parser.add_argument(\"--data_path\", default=None, type=str, help=\"The input data path.\")\r\n parser.add_argument(\"--model_dir\", default=None, type=str, help=\"The output directory where the model predictions and checkpoints will be written.\")\r\n parser.add_argument(\"--valid_data_path\", default=None, type=str, help=\"The validation data path.\")\r\n parser.add_argument(\"--inference_input_path\", default=None, type=str, help=\"Input file path for inference.\")\r\n parser.add_argument(\"--inference_output_path\", default=None, type=str, help=\"Output file path for inference.\")\r\n parser.add_argument(\"--transformer_pretrained_weights\", default=None, type=str, help=\"Path to pretrained model or model identifier from huggingface.co/models\")\r\n parser.add_argument(\"--max_seq_len\", default=64, type=int, help=\"Maximum sequence length in terms of word count.\")\r\n parser.add_argument(\"--batch_size\", default=8, type=int, help=\"Batch size.\")\r\n parser.add_argument(\"--num_data_workers\", default=0, type=int, help=\"Dataloader num workers.\")\r\n parser.add_argument(\"--pin_memory\", action='store_true', help=\"Pin memory in data loader\")\r\n parser.add_argument(\"--use_src_emb\", action='store_true', help=\"Whether to use the source embedding tensor in the model.\")\r\n parser.add_argument(\"--learning_rate\", default=5e-5, type=float, help=\"Learning rate.\")\r\n parser.add_argument(\"--max_grad_norm\", default=1.0, type=float, help=\"Max gradient norm.\")\r\n parser.add_argument(\"--weight_decay\", default=0.0, type=float, help=\"Weight decay if we apply some.\")\r\n parser.add_argument(\"--adam_epsilon\", default=1e-8, type=float, help=\"Epsilon for Adam optimizer.\")\r\n parser.add_argument(\"--warmup_steps\", default=0, type=int, help=\"Linear warmup over warmup_steps.\")\r\n parser.add_argument(\"--max_steps\", default=10000000, type=int, help=\"Stop training after N steps.\")\r\n parser.add_argument(\"--dense_sizes\", default=\"50\", type=str, help=\"The dense layer sizes separated by ',', last one will be output dimension.\")\r\n parser.add_argument(\"--log_steps\", default=20, type=int, help=\"Log training status every N steps.\")\r\n parser.add_argument('--logging_file', type=str, default=None, help='Log file to save.')\r\n parser.add_argument(\"--dropout_rate\", default=0.2, type=float, help=\"Dropout rate.\")\r\n parser.add_argument(\"--eval_steps\", default=200, type=int, help=\"Do evaluation every N steps.\")\r\n parser.add_argument('--save_steps', type=int, default=200, help=\"Save checkpoint every X updates steps.\")\r\n args = parser.parse_args()\r\n return args\r\n\r\ndef tally_parameters(model):\r\n n_params = 0\r\n for name, param in model.named_parameters():\r\n n_params += param.nelement()\r\n return n_params\r\n\r\ndef get_data_loader(args, data_path, mode, device, drop_last=True):\r\n if data_path is None:\r\n return None, None\r\n repeat = (mode == 'train')\r\n dataset = GnnKdDataset(data_path, max_seq_len=args.max_seq_len, repeat=repeat, device=device)\r\n data_loader = DataLoader(dataset, batch_size=args.batch_size, shuffle=False, sampler=None, num_workers=args.num_data_workers if (mode == 'train') else 0, pin_memory=args.pin_memory, drop_last=drop_last)\r\n return dataset, data_loader\r\n\r\ndef get_infer_data_loader(args, data_path, device):\r\n if data_path is None:\r\n raise ArgumentError(\"data path is None!\")\r\n dataset = GnnKdInferenceDataset(data_path, max_seq_len=args.max_seq_len, device=device)\r\n data_loader = DataLoader(dataset, batch_size=args.batch_size, shuffle=False, sampler=None, num_workers=0, pin_memory=False, drop_last=False)\r\n return data_loader\r\n\r\ndef get_linear_schedule_with_warmup(optimizer, num_warmup_steps, num_training_steps, last_epoch=-1):\r\n \"\"\"\r\n Create a schedule with a learning rate that decreases linearly from the initial lr set in the optimizer to 0,\r\n after a warmup period during which it increases linearly from 0 to the initial lr set in the optimizer.\r\n\r\n Args:\r\n optimizer (:class:`~torch.optim.Optimizer`):\r\n The optimizer for which to schedule the learning rate.\r\n num_warmup_steps (:obj:`int`):\r\n The number of steps for the warmup phase.\r\n num_training_steps (:obj:`int`):\r\n The total number of training steps.\r\n last_epoch (:obj:`int`, `optional`, defaults to -1):\r\n The index of the last epoch when resuming training.\r\n\r\n Return:\r\n :obj:`torch.optim.lr_scheduler.LambdaLR` with the appropriate schedule.\r\n \"\"\"\r\n\r\n def lr_lambda(current_step: int):\r\n if current_step < num_warmup_steps:\r\n return float(current_step) / float(max(1, num_warmup_steps))\r\n return max(\r\n 0.0, float(num_training_steps - current_step) / float(max(1, num_training_steps - num_warmup_steps))\r\n )\r\n\r\n return LambdaLR(optimizer, lr_lambda, last_epoch)\r\n\r\ndef get_optimizer(args, model):\r\n # Prepare optimizer and schedule (linear warmup and decay)\r\n no_decay = ['bias', 'LayerNorm.weight']\r\n optimizer_grouped_parameters = [\r\n {'params': [p for n, p in model.named_parameters() if not any(nd in n for nd in no_decay)], 'weight_decay': args.weight_decay},\r\n {'params': [p for n, p in model.named_parameters() if any(nd in n for nd in no_decay)], 'weight_decay': 0.0}\r\n ]\r\n optimizer = AdamW(optimizer_grouped_parameters, lr=args.learning_rate, eps=args.adam_epsilon)\r\n scheduler = get_linear_schedule_with_warmup(optimizer, num_warmup_steps=args.warmup_steps, num_training_steps=args.max_steps)\r\n # Add Horovod Distributed Optimizer\r\n #optimizer = hvd.DistributedOptimizer(optimizer, named_parameters=model.named_parameters())\r\n return optimizer, scheduler\r\n\r\ndef run_model(args, model, loss_funct, batch_data, device):\r\n input_ids, attention_mask, src_emb, target_emb, line_id = batch_data\r\n input_ids = input_ids.to(device)\r\n attention_mask = attention_mask.to(device)\r\n src_emb = src_emb.to(device)\r\n target_emb = target_emb.to(device)\r\n\r\n if args.transformer_pretrained_weights:\r\n predict_emb = model(input_ids, attention_mask, src_emb)\r\n else:\r\n predict_emb = model(src_emb)\r\n loss = loss_funct(predict_emb, target_emb)\r\n return loss\r\n\r\ndef evaluate_impl(args, data_loader, model, loss_funct, tb_writer=None, global_step=-1, device='cpu'):\r\n with torch.no_grad():\r\n losses = []\r\n n_examples = 0\r\n for batch_data in data_loader:\r\n n_examples += len(batch_data[0])\r\n loss = run_model(args, model, loss_funct, batch_data, device)\r\n losses.append(loss.item())\r\n avg_loss = np.mean(losses)\r\n logger.info('step: {}, val loss: {:.6f}, example count: {}'.format(global_step, avg_loss, n_examples))\r\n if tb_writer:\r\n tb_writer.add_scalar('valid_loss', avg_loss, global_step)\r\n return avg_loss\r\n\r\ndef save_model(args, model, tag=None):\r\n model_dir = args.model_dir if tag is None else os.path.join(args.model_dir, 'checkpoint-{}'.format(tag))\r\n if not os.path.exists(model_dir):\r\n os.makedirs(model_dir)\r\n model_to_save = model.module if hasattr(model, 'module') else model # Take care of distributed/parallel training\r\n torch.save(model_to_save, os.path.join(model_dir, 'pytorch_model.bin'))\r\n torch.save(args, os.path.join(model_dir, 'training_args.bin'))\r\n logger.info(\"Saving model checkpoint to %s\", model_dir)\r\n\r\ndef train(args):\r\n # Initialize Horovod\r\n #hvd.init()\r\n if torch.cuda.is_available():\r\n # Pin GPU to be used to process local rank (one GPU per process)\r\n #torch.cuda.set_device(hvd.local_rank())\r\n #device = torch.device(f\"cuda:{hvd.local_rank()}\")\r\n device = torch.device(f\"cuda:0\")\r\n else:\r\n device = torch.device('cpu')\r\n\r\n #if hvd.local_rank() == 0:\r\n if True:\r\n if not args.logging_file:\r\n args.logging_file = os.path.join(args.model_dir, 'log.txt')\r\n if not os.path.exists(args.model_dir):\r\n os.mkdir(args.model_dir)\r\n else:\r\n path = os.path.join(args.model_dir, \"events.out.tfevents.*\")\r\n os.system(f\"rm -rf {path}\")\r\n if os.path.exists(args.logging_file):\r\n os.remove(args.logging_file)\r\n\r\n fh = logging.FileHandler(args.logging_file, 'w', encoding='utf-8')\r\n fh.setFormatter(logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s'))\r\n logger.addHandler(fh)\r\n\r\n for param in dir(args):\r\n if not param.startswith(\"_\"):\r\n logger.info(f\"{param}={getattr(args, param)}\")\r\n\r\n logger.info(f'using device: {device}')\r\n\r\n train_dataset, train_loader = get_data_loader(args, args.data_path, mode='train', device=device)\r\n valid_dataset, valid_loader = get_data_loader(args, args.valid_data_path, mode='eval', device=device, drop_last=True)\r\n\r\n tb_writer = SummaryWriter(args.model_dir)\r\n\r\n if args.transformer_pretrained_weights:\r\n model = TransformerEncoder(args.transformer_pretrained_weights, dense_sizes=args.dense_sizes, dropout_rate=args.dropout_rate, use_src_emb=args.use_src_emb)\r\n else:\r\n input_size = int(args.dense_sizes.split(',')[-1])\r\n model = MLP(input_size=input_size, dense_sizes=args.dense_sizes, dropout_rate=args.dropout_rate)\r\n model = model.to(device)\r\n logger.info(model)\r\n n_params = tally_parameters(model)\r\n logger.info(f\"parameters count: {n_params}\")\r\n if args.transformer_pretrained_weights:\r\n n_params_transformer = tally_parameters(model.transformer_model)\r\n logger.info(f\"transformer parameters count: {n_params_transformer}\")\r\n\r\n #loss_funct = torch.nn.MSELoss()\r\n loss_funct = torch.nn.L1Loss()\r\n optimizer, scheduler = get_optimizer(args, model)\r\n\r\n global_step = 0\r\n train_loss = []\r\n start_time = time.time()\r\n for batch_data in train_loader:\r\n if global_step == args.max_steps:\r\n break\r\n optimizer.zero_grad()\r\n\r\n loss = run_model(args, model, loss_funct, batch_data, device)\r\n loss.backward()\r\n torch.nn.utils.clip_grad_norm_(model.parameters(), args.max_grad_norm)\r\n optimizer.step()\r\n if scheduler:\r\n scheduler.step() # Update learning rate schedule\r\n\r\n train_loss.append(loss.item())\r\n if global_step % args.log_steps == 0:\r\n avg_loss = np.mean(train_loss)\r\n logger.info('Train step {}: avg train loss: {:.6f} seconds: {:.3f}'.format(global_step, avg_loss, time.time()-start_time))\r\n if scheduler:\r\n tb_writer.add_scalar(\"lr\", scheduler.get_last_lr()[0], global_step)\r\n tb_writer.add_scalar('train_loss', avg_loss, global_step)\r\n train_loss = []\r\n start_time = time.time()\r\n\r\n if global_step % args.eval_steps == 0:# and hvd.local_rank() == 0:\r\n model = model.eval()\r\n evaluate_impl(args, valid_loader, model, loss_funct, tb_writer, global_step, device)\r\n model = model.train()\r\n\r\n if global_step % args.save_steps == 0:# and hvd.local_rank() == 0:\r\n logger.info(f'saving model to {args.model_dir}')\r\n save_model(args, model)\r\n \r\n global_step += 1\r\n\r\ndef inference(args):\r\n model_path = os.path.join(args.model_dir, 'pytorch_model.bin')\r\n if torch.cuda.is_available():\r\n device = torch.device(\"cuda:0\")\r\n model = torch.load(model_path)\r\n else:\r\n device = torch.device(\"cpu\")\r\n model = torch.load(model_path, map_location=lambda storage, loc: storage)\r\n model.eval()\r\n infer_loader = get_infer_data_loader(args, args.inference_input_path, device=device)\r\n\r\n with torch.no_grad():\r\n with open(args.inference_output_path, 'w', encoding='utf-8') as writer:\r\n counter = 0\r\n prev_counter = counter\r\n start = time.time()\r\n for batch_data in infer_loader:\r\n input_ids, attention_mask, src_emb, line_id = batch_data\r\n input_ids = input_ids.to(device)\r\n attention_mask = attention_mask.to(device)\r\n if args.use_src_emb:\r\n src_emb = src_emb.to(device)\r\n predict_emb = model(input_ids, attention_mask, src_emb)\r\n\r\n assert len(line_id) == len(predict_emb), f\"len(label) ({len(line_id)}) not equal to label(encodings) ({len(predict_emb)})\"\r\n for label, encoding in zip(line_id, predict_emb):\r\n encoding_str = ','.join(map(lambda x: '{:.6f}'.format(x), encoding))\r\n writer.write(f'{label}\\t{encoding_str}\\n')\r\n counter += len(line_id)\r\n if (counter - prev_counter) >= args.log_steps:\r\n end = time.time()\r\n speed = (counter - prev_counter) / (end - start + 1e-8)\r\n logger.info(f'finished: {counter}, speed: ' + '{:.2f}'.format(speed) + ' lines/sec')\r\n prev_counter = counter\r\n start = time.time()\r\n\r\ndef main():\r\n args = parse_arguments()\r\n if args.mode == 'train':\r\n train(args)\r\n elif args.mode == 'evaluate':\r\n raise NotImplementedError()\r\n elif args.mode == 'inference':\r\n inference(args)\r\n else:\r\n raise NotImplementedError()\r\n\r\nif __name__ == \"__main__\":\r\n main()\r\n"
},
{
"alpha_fraction": 0.5288254022598267,
"alphanum_fraction": 0.5348654389381409,
"avg_line_length": 48.30266189575195,
"blob_id": "97011f44e673846bf1c8776fc32d6a5564c02e78",
"content_id": "1b0987904e4510761640f051fb4f6cc2286ef205",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 20364,
"license_type": "no_license",
"max_line_length": 213,
"num_lines": 413,
"path": "/model/tokenmodel/run_token.py",
"repo_name": "SerenaQuinn/AdsGNN",
"src_encoding": "UTF-8",
"text": "import torch\nimport torch.optim as optim\nimport utils\nimport os\nfrom models.topo_modeling import TopoGramForNeighborPredict\nfrom models.bi_topo_modeling import BiTopoGramForNeighborPredict\nfrom models.configuration_tnlrv3 import TuringNLRv3Config\nimport copy\n\nfrom torch.nn.parallel import DistributedDataParallel as DDP\nimport torch.distributed as dist\n\nimport time\nimport logging\n\nfrom data_handler_4_graph_only_title import DatasetForMatching, DataCollatorForMatching,SingleProcessDataLoaderForMatching,MultiProcessDataLoaderForMatching\nfrom transformers import BertTokenizerFast\n\nfrom run_retrive import compute_acc, compute_retrive_acc, setup, cleanup, warmup_linear\n\ndef load_bert(args):\n config = TuringNLRv3Config.from_pretrained(\n args.config_name if args.config_name else args.model_name_or_path,\n output_hidden_states=True)\n config.neighbor_type = args.neighbor_type\n config.mapping_graph = 1 if args.mapping_graph else 0\n config.graph_transform = 1 if args.return_last_station_emb else 0\n model = TopoGramForNeighborPredict.from_pretrained(args.model_name_or_path,\n from_tf=bool('.ckpt' in args.model_name_or_path),\n config=config)\n # model = BiTopoGramForNeighborPredict.from_pretrained(args.model_name_or_path,\n # from_tf=bool('.ckpt' in args.model_name_or_path),\n # config=config)\n return model\n\ndef train(local_rank, args, global_prefetch_step, end):\n\n utils.setuplogging()\n os.environ[\"RANK\"] = str(local_rank)\n setup(local_rank, args.world_size)\n device = torch.device(\"cuda\", local_rank)\n if args.fp16:\n from torch.cuda.amp import autocast\n scaler = torch.cuda.amp.GradScaler()\n\n model = load_bert(args)\n logging.info('loading model: {}'.format(args.model_type))\n model = model.to(device)\n if args.world_size > 1:\n ddp_model = DDP(model,device_ids=[local_rank],output_device=local_rank,find_unused_parameters=True)\n else:\n ddp_model = model\n\n if args.warmup_lr:\n optimizer = optim.Adam([{'params': ddp_model.parameters(), 'lr': args.pretrain_lr*warmup_linear(args,0)}])\n else:\n optimizer = optim.Adam([{'params': ddp_model.parameters(), 'lr': args.pretrain_lr}])\n\n tokenizer = BertTokenizerFast.from_pretrained(\"bert-base-uncased\")\n data_collator = DataCollatorForMatching(tokenizer=tokenizer,mlm=args.mlm_loss,neighbor_num=args.neighbor_num,neighbor_mask=args.neighbor_mask,block_size=args.block_size)\n loss = 0.0\n global_step = 0\n best_acc=0.0\n best_model=copy.deepcopy(model)\n for ep in range(args.epochs):\n start_time = time.time()\n ddp_model.train()\n dataset = DatasetForMatching(tokenizer=tokenizer,file_path=args.train_data_path,\n neighbor_num=args.neighbor_num)\n dataloader = MultiProcessDataLoaderForMatching(dataset,\n batch_size=args.train_batch_size,\n collate_fn=data_collator,\n local_rank=local_rank,\n world_size=args.world_size,\n prefetch_step=global_prefetch_step,\n end=end)\n for step, batch in enumerate(dataloader):\n\n if args.enable_gpu:\n for k,v in batch.items():\n if v is not None:\n batch[k] = v.cuda(non_blocking=True)\n\n input_id_query = batch['input_id_query']\n attention_masks_query = batch['attention_masks_query']\n masked_lm_labels_query = batch['masked_lm_labels_query']\n mask_query = batch['mask_query']\n input_id_key = batch['input_id_key']\n attention_masks_key = batch['attention_masks_key']\n masked_lm_labels_key = batch['masked_lm_labels_key']\n mask_key = batch['mask_key']\n if args.fp16:\n with autocast():\n batch_loss = ddp_model(\n input_id_query,\n attention_masks_query,\n masked_lm_labels_query,\n mask_query,\n input_id_key,\n attention_masks_key,\n masked_lm_labels_key,\n mask_key,\n neighbor_num=args.neighbor_num,\n mask_self_in_graph=args.self_mask,\n mlm_loss=args.mlm_loss,\n return_last_station_emb=args.return_last_station_emb)\n else:\n batch_loss = ddp_model(\n input_id_query,\n attention_masks_query,\n masked_lm_labels_query,\n mask_query,\n input_id_key,\n attention_masks_key,\n masked_lm_labels_key,\n mask_key,\n neighbor_num=args.neighbor_num,\n mask_self_in_graph=args.self_mask,\n mlm_loss=args.mlm_loss,\n return_last_station_emb=args.return_last_station_emb)\n loss += batch_loss.item()\n optimizer.zero_grad()\n if args.fp16:\n scaler.scale(batch_loss).backward()\n scaler.step(optimizer)\n scaler.update()\n else:\n batch_loss.backward()\n optimizer.step()\n\n global_step+=1\n if args.warmup_lr:\n optimizer.param_groups[0]['lr'] = args.pretrain_lr*warmup_linear(args,global_step)\n\n if local_rank == 0 and global_step % args.log_steps == 0:\n logging.info(\n '[{}] cost_time:{} step:{}, lr:{}, train_loss: {:.5f}'.format(\n local_rank, time.time()-start_time, global_step, optimizer.param_groups[0]['lr'],loss / args.log_steps))\n loss=0.0\n\n # save model minibatch\n if local_rank == 0 and global_step % args.save_steps == 0:\n ckpt_path = os.path.join(args.model_dir, f'{args.savename}-epoch-{ep}-{global_step}.pt')\n torch.save(\n {\n 'model_state_dict': model.state_dict(),\n 'optimizer': optimizer.state_dict()\n }, ckpt_path)\n logging.info(f\"Model saved to {ckpt_path}\")\n\n dist.barrier()\n logging.info(\"train time:{}\".format(time.time() - start_time))\n\n # save model last of epoch\n if local_rank == 0:\n ckpt_path = os.path.join(args.model_dir, '{}-epoch-{}.pt'.format(args.savename,ep+1))\n torch.save(\n {\n 'model_state_dict': model.state_dict(),\n 'optimizer': optimizer.state_dict()\n }, ckpt_path)\n logging.info(f\"Model saved to {ckpt_path}\")\n\n logging.info(\"Star testing for epoch-{}\".format(ep+1))\n acc=test_single_process(model,args,\"valid\")\n logging.info(\"test time:{}\".format(time.time() - start_time))\n if acc>best_acc:\n best_model=copy.deepcopy(model)\n best_acc=acc\n dist.barrier()\n\n if local_rank==0:\n start_time=time.time()\n ckpt_path = os.path.join(args.model_dir, '{}-best.pt'.format(args.savename))\n torch.save(\n {\n 'model_state_dict': best_model.state_dict(),\n 'optimizer': optimizer.state_dict()\n }, ckpt_path)\n logging.info(f\"Model saved to {ckpt_path}\")\n logging.info(\"Star testing for best\")\n acc = test_single_process(best_model, args,\"test\")\n logging.info(\"test time:{}\".format(time.time() - start_time))\n\n cleanup()\n\n\ndef test_single_process(model,args,mode):\n assert mode in {\"valid\",\"test\"}\n model.eval()\n with torch.no_grad():\n\n tokenizer = BertTokenizerFast.from_pretrained(\"bert-base-uncased\")\n data_collator = DataCollatorForMatching(tokenizer=tokenizer, mlm=args.mlm_loss, neighbor_num=args.neighbor_num,\n neighbor_mask=args.neighbor_mask, block_size=args.block_size)\n if mode==\"valid\":\n dataset = DatasetForMatching(tokenizer=tokenizer, file_path=args.valid_data_path,\n neighbor_num=args.neighbor_num)\n dataloader = SingleProcessDataLoaderForMatching(dataset,batch_size=args.valid_batch_size,collate_fn=data_collator)\n elif mode==\"test\":\n dataset = DatasetForMatching(tokenizer=tokenizer, file_path=args.test_data_path,\n neighbor_num=args.neighbor_num)\n dataloader = SingleProcessDataLoaderForMatching(dataset, batch_size=args.test_batch_size,\n collate_fn=data_collator)\n\n mlm_acc = [0, 0]\n retrive_acc = [0, 0]\n for step, batch in enumerate(dataloader):\n if args.enable_gpu:\n for k, v in batch.items():\n if v is not None:\n batch[k] = v.cuda(non_blocking=True)\n\n input_ids_query = batch['input_id_query']\n attention_masks_query = batch['attention_masks_query']\n masked_lm_labels_query = batch['masked_lm_labels_query']\n mask_query = batch['mask_query']\n input_ids_key = batch['input_id_key']\n attention_masks_key = batch['attention_masks_key']\n masked_lm_labels_key = batch['masked_lm_labels_key']\n mask_key = batch['mask_key']\n\n all_nodes_num = mask_query.shape[0]\n batch_size = all_nodes_num // (args.neighbor_num + 1)\n neighbor_mask_query = mask_query.view(batch_size, (args.neighbor_num + 1))\n neighbor_mask_key = mask_key.view(batch_size, (args.neighbor_num + 1))\n\n hidden_states_query = model.bert(input_ids_query, attention_masks_query,\n neighbor_mask=neighbor_mask_query,\n mask_self_in_graph=args.self_mask,\n return_last_station_emb=args.return_last_station_emb\n )\n hidden_states_key = model.bert(input_ids_key, attention_masks_key,\n neighbor_mask=neighbor_mask_key,\n mask_self_in_graph=args.self_mask,\n return_last_station_emb=args.return_last_station_emb\n )\n last_hidden_states_query = hidden_states_query[0]\n last_hidden_states_key = hidden_states_key[0]\n\n if args.neighbor_type != 0:\n # delete the station_placeholder hidden_state:(N,1+L,D)->(N,L,D)\n last_hidden_states_query = last_hidden_states_query[:, 1:]\n last_hidden_states_key = last_hidden_states_key[:, 1:]\n\n # hidden_state:(N,L,D)->(B,L,D)\n query = last_hidden_states_query[::(args.neighbor_num + 1)]\n key = last_hidden_states_key[::(args.neighbor_num + 1)]\n if masked_lm_labels_query is not None:\n mlm_scores = model.cls.predictions(query, model.bert.embeddings.word_embeddings.weight) # N L V\n hit_num, all_num = compute_acc(mlm_scores, masked_lm_labels_query)\n mlm_acc[0] += hit_num.data\n mlm_acc[1] += all_num.data\n\n if masked_lm_labels_key is not None:\n mlm_scores = model.cls.predictions(key, model.bert.embeddings.word_embeddings.weight) # N L V\n hit_num, all_num = compute_acc(mlm_scores, masked_lm_labels_key)\n mlm_acc[0] += hit_num.data\n mlm_acc[1] += all_num.data\n\n mask_query = mask_query[::(args.neighbor_num + 1)]\n mask_key = mask_key[::(args.neighbor_num + 1)]\n\n if args.return_last_station_emb:\n last_neighbor_hidden_states_query = hidden_states_query[-1]\n last_neighbor_hidden_states_key = hidden_states_key[-1]\n query = torch.cat([query[:, 0], last_neighbor_hidden_states_query], dim=-1)\n query = model.graph_transform(query)\n key = torch.cat([key[:, 0], last_neighbor_hidden_states_key], dim=-1)\n key = model.graph_transform(key)\n else:\n query = query[:, 0]\n key = key[:, 0]\n\n # hit_num, all_num = compute_retrive_acc(query, key, mask_q=mask_query, mask_k=mask_key, Q=tokenizer.batch_decode(\n # input_ids_query[::(args.neighbor_num + 1)].cpu().numpy().tolist(), skip_special_tokens=True),\n # K=tokenizer.batch_decode(\n # input_ids_key[::(args.neighbor_num + 1)].cpu().numpy().tolist(),\n # skip_special_tokens=True))\n hit_num, all_num = compute_retrive_acc(query, key, mask_q=mask_query, mask_k=mask_key)\n retrive_acc[0] += hit_num.data\n retrive_acc[1] += all_num.data\n\n if args.mlm_loss:\n logging.info('Final-- mlm_acc:{}, qk_acc:{}'.format((mlm_acc[0] / mlm_acc[1]).data,(retrive_acc[0] / retrive_acc[1]).data))\n else:\n logging.info('Final-- qk_acc:{}'.format((retrive_acc[0] / retrive_acc[1]).data))\n return (retrive_acc[0] / retrive_acc[1]).data\n\n\n\n# def test(local_rank, args, global_prefetch_step, end):\n#\n# utils.setuplogging()\n# os.environ[\"RANK\"] = str(local_rank)\n# setup(local_rank, args.world_size)\n#\n# device = torch.device(\"cuda\", local_rank)\n#\n# model = load_bert(args)\n# logging.info('loading model: {}'.format(args.model_type))\n# model = model.to(device)\n#\n# checkpoint = torch.load(args.load_ckpt_name)\n# model.load_state_dict(checkpoint['model_state_dict'])\n# logging.info('load ckpt:{}'.format(args.load_ckpt_name))\n#\n# if args.world_size > 1:\n# ddp_model = DDP(model,device_ids=[local_rank],output_device=local_rank,find_unused_parameters=True)\n# else:\n# ddp_model = model\n#\n# ddp_model.eval()\n# torch.set_grad_enabled(False)\n#\n# tokenizer = BertTokenizerFast.from_pretrained(\"bert-base-uncased\")\n# dataset = DatasetForSentencePairPrediction(tokenizer=tokenizer, file_path=args.train_data_path,\n# neighbor_num=args.neighbor_num)\n# data_collator = DataCollatorForSentencePairPrediction(tokenizer=tokenizer, block_size=args.block_size,mlm=False)\n# dataloader = DataLoaderForSentencePairPrediction(dataset,\n# batch_size=args.batch_size,\n# collate_fn=data_collator,\n# local_rank=local_rank,\n# world_size=args.world_size,\n# prefetch_step=global_prefetch_step,\n# end=end)\n#\n# mlm_acc = [0,0]\n# retrive_acc = [0,0]\n# for step, batch in enumerate(dataloader):\n# if args.enable_gpu:\n# for k, v in batch.items():\n# if v is not None:\n# batch[k] = v.cuda(non_blocking=True)\n#\n# input_ids_query = batch['input_id_query']\n# attention_masks_query = batch['attention_masks_query']\n# masked_lm_labels_query = batch['masked_lm_labels_query']\n# mask_query = batch['mask_query']\n# input_ids_key = batch['input_id_key']\n# attention_masks_key = batch['attention_masks_key']\n# masked_lm_labels_key = batch['masked_lm_labels_key']\n# mask_key = batch['mask_key']\n#\n# all_nodes_num = mask_query.shape[0]\n# batch_size = all_nodes_num // (args.neighbor_num + 1)\n# neighbor_mask_query = mask_query.view(batch_size, (args.neighbor_num + 1))\n# neighbor_mask_key = mask_key.view(batch_size, (args.neighbor_num + 1))\n#\n# hidden_states_query = ddp_model.bert(input_ids_query, attention_masks_query,\n# neighbor_mask=neighbor_mask_query,\n# mask_self_in_graph=args.self_mask,\n# return_last_station_emb=args.return_last_station_emb\n# )\n# hidden_states_key = ddp_model.bert(input_ids_key, attention_masks_key,\n# neighbor_mask=neighbor_mask_key,\n# mask_self_in_graph=args.self_mask,\n# return_last_station_emb=args.return_last_station_emb\n# )\n# last_hidden_states_query = hidden_states_query[0]\n# last_hidden_states_key = hidden_states_key[0]\n#\n# if args.neighbor_type != 0 :\n# # delete the station_placeholder hidden_state:(N,1+L,D)->(N,L,D)\n# last_hidden_states_query = last_hidden_states_query[:, 1:]\n# last_hidden_states_key = last_hidden_states_key[:, 1:]\n#\n# # hidden_state:(N,L,D)->(B,L,D)\n# query = last_hidden_states_query[::(args.neighbor_num + 1)]\n# key = last_hidden_states_key[::(args.neighbor_num + 1)]\n#\n# mlm_scores = ddp_model.cls.predictions(query, ddp_model.bert.embeddings.word_embeddings.weight) #N L V\n# hit_num, all_num = compute_acc(mlm_scores,masked_lm_labels_query)\n# mlm_acc[0] += hit_num.data\n# mlm_acc[1] += all_num.data\n#\n# mlm_scores = ddp_model.cls.predictions(key, ddp_model.bert.embeddings.word_embeddings.weight) #N L V\n# hit_num, all_num = compute_acc(mlm_scores,masked_lm_labels_key)\n# mlm_acc[0] += hit_num.data\n# mlm_acc[1] += all_num.data\n#\n# mask_query = mask_query[::(args.neighbor_num + 1)]\n# mask_key = mask_key[::(args.neighbor_num + 1)]\n#\n# if args.return_last_station_emb:\n# last_neighbor_hidden_states_query = hidden_states_query[-1]\n# last_neighbor_hidden_states_key = hidden_states_key[-1]\n# query = torch.cat([query[:, 0], last_neighbor_hidden_states_query], dim=-1)\n# query = ddp_model.graph_transform(query)\n# key = torch.cat([key[:, 0], last_neighbor_hidden_states_key], dim=-1)\n# key = ddp_model.graph_transform(key)\n#\n# else:\n# query = query[:,0]\n# key = key[:,0]\n#\n# hit_num, all_num = compute_retrive_acc(query, key, mask_q=mask_query, mask_k=mask_key,Q=tokenizer.batch_decode(input_ids_query[::(args.neighbor_num + 1)].cpu().numpy().tolist(),skip_special_tokens=True),\n# K=tokenizer.batch_decode(input_ids_key[::(args.neighbor_num + 1)].cpu().numpy().tolist(),skip_special_tokens=True))\n# # hit_num, all_num = compute_retrive_acc(query, key, mask_q=mask_query, mask_k=mask_key)\n# retrive_acc[0] += hit_num.data\n# retrive_acc[1] += all_num.data\n#\n# if step%args.log_steps == 0:\n# logging.info('[{}] step:{}, mlm_acc:{}, qk_acc:{}'.format(local_rank,step,\n# (mlm_acc[0]/mlm_acc[1]).data, (retrive_acc[0]/retrive_acc[1]).data\n# ))\n# # logging.info('[{}] step:{}, qk_acc:{}'.format(local_rank, step, (retrive_acc[0] / retrive_acc[1]).data))\n#\n# logging.info('Final-- [{}] mlm_acc:{}, qk_acc:{}'.format(local_rank,\n# (mlm_acc[0] / mlm_acc[1]).data, (retrive_acc[0] / retrive_acc[1]).data\n# ))\n#\n# cleanup()\n\n\n"
},
{
"alpha_fraction": 0.7560975551605225,
"alphanum_fraction": 0.7560975551605225,
"avg_line_length": 40,
"blob_id": "6f36198b299d2aae331c1f1ea72091089f860141",
"content_id": "5ad94a4506d4a0093b30d5ba800f6ad6784c880d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 41,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 1,
"path": "/data/readme.md",
"repo_name": "SerenaQuinn/AdsGNN",
"src_encoding": "UTF-8",
"text": "slice.txt: a slice of real on-house data\n"
}
] | 9 |
josemartins2121/AI_Tetris | https://github.com/josemartins2121/AI_Tetris | 555df3aacf2179dfe28716e13c7dec79d34f021b | c3c9fb8250c94e611ae1db75284f1e05cbf9ff44 | 64c9fcf9ee122576b78431ac4ac5bd520067a40b | refs/heads/master | 2022-12-16T03:04:08.634850 | 2020-09-09T15:55:59 | 2020-09-09T15:55:59 | 292,520,573 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.46658650040626526,
"alphanum_fraction": 0.4973449409008026,
"avg_line_length": 27.435897827148438,
"blob_id": "ad27a4e1a307ff590169c319a8689fafb954468c",
"content_id": "675f6c94fa48701b974ffe908d3d7ec73a0cd502",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9981,
"license_type": "permissive",
"max_line_length": 143,
"num_lines": 351,
"path": "/game.py",
"repo_name": "josemartins2121/AI_Tetris",
"src_encoding": "UTF-8",
"text": "import pygame\nimport sys\nimport random\nfrom time import sleep,time\nS = [['.....',\n '.....',\n '..00.',\n '.00..',\n '.....'],\n ['.....',\n '..0..',\n '..00.',\n '...0.',\n '.....']]\n\nZ = [['.....',\n '.....',\n '.00..',\n '..00.',\n '.....'],\n ['.....',\n '..0..',\n '.00..',\n '.0...',\n '.....']]\n\nI = [['..0..',\n '..0..',\n '..0..',\n '..0..',\n '.....'],\n ['.....',\n '0000.',\n '.....',\n '.....',\n '.....']]\n\nO = [['.....',\n '.....',\n '.00..',\n '.00..',\n '.....']]\n\nJ = [['.....',\n '.0...',\n '.000.',\n '.....',\n '.....'],\n ['.....',\n '..00.',\n '..0..',\n '..0..',\n '.....'],\n ['.....',\n '.....',\n '.000.',\n '...0.',\n '.....'],\n ['.....',\n '..0..',\n '..0..',\n '.00..',\n '.....']]\n\nL = [['.....',\n '...0.',\n '.000.',\n '.....',\n '.....'],\n ['.....',\n '..0..',\n '..0..',\n '..00.',\n '.....'],\n ['.....',\n '.....',\n '.000.',\n '.0...',\n '.....'],\n ['.....',\n '.00..',\n '..0..',\n '..0..',\n '.....']]\n\nT = [['.....',\n '..0..',\n '.000.',\n '.....',\n '.....'],\n ['.....',\n '..0..',\n '..00.',\n '..0..',\n '.....'],\n ['.....',\n '.....',\n '.000.',\n '..0..',\n '.....'],\n ['.....',\n '..0..',\n '.00..',\n '..0..',\n '.....']]\n\nshapes = [S, Z, I, O, J, L, T]\n\n\nsize = width, height = 400, 400\nplay_height = 340\nplay_width = 170\ngap = 30\nsize_piece = 17\n\n# colors\nblack = 88, 105, 148\nblue_bg = 180, 196, 174\n\ncolors = [(55,63,81), (212, 81, 19), (249, 160, 63),\n (93,134,70),]\n \n\n\npygame.init()\nclock = pygame.time.Clock()\nscreen = pygame.display.set_mode(size)\n\nbackground = pygame.Surface(size)\n\nclass piece:\n def __init__(self, x, y, shape, color, orientation):\n self.x = x\n self.y = y\n self.shape = shape\n self.color = color\n self.orientation = orientation\n def fall(self):\n self.y += size_piece\n if not pos_valid(self,locked_positions):\n self.y -= size_piece\n def free_fall(self):\n n=0\n while 1:\n self.y += size_piece\n if not pos_valid(self,locked_positions):\n self.y -= size_piece\n break\n n+=1\n return n\n def change_orientation(self):\n previous = self.orientation\n self.orientation = (self.orientation + 1) % len(self.shape)\n if not pos_valid(self,locked_positions):\n self.orientation = previous\n\n\ndef get_piece():\n shape = random.choice(shapes)\n return piece(gap+size_piece*5, gap+2*size_piece, shape, colors[random.randint(0, len(colors)-1)], random.randint(0,len(shape)-1))\n\n\ndef print_shape(piece,x,y ):\n for lines_index,lines in enumerate(piece.shape[piece.orientation]):\n for point_index,point in enumerate(lines):\n if point == '0':\n pygame.draw.rect(background,piece.color, (x+(point_index-2)*size_piece,y+(lines_index-2)*size_piece,size_piece,size_piece))\n\ndef pos_valid(piece,locked_positions):\n for lines_index,lines in enumerate(piece.shape[piece.orientation]):\n for point_index,point in enumerate(lines):\n if point == '0':\n curr_point_x = piece.x+(point_index-2)*size_piece\n curr_point_y = piece.y+(lines_index-2)*size_piece\n if gap + play_width< curr_point_x+size_piece or gap+play_height < curr_point_y+size_piece or curr_point_x + size_piece <= gap :\n return False\n if locked_positions[int((curr_point_y-gap)/size_piece)][int((curr_point_x-gap)/size_piece)] != (0,0,0):\n return False\n return True\n\ndef fallen_piece(piece,locked_positions):\n\n for lines_index,lines in enumerate(piece.shape[piece.orientation]):\n for point_index,point in enumerate(lines):\n if point == '0':\n curr_point_x = piece.x+(point_index-2)*size_piece\n curr_point_y = piece.y+(lines_index-2)*size_piece\n if curr_point_y+size_piece == gap+play_height:\n return True\n elif locked_positions[int((curr_point_y-gap)/size_piece)+1][int((curr_point_x-gap)/size_piece)] != (0,0,0):\n return True\n return False\n\ndef add_locked(piece,locked_positions):\n for lines_index,lines in enumerate(\n piece.shape[piece.orientation]):\n for point_index,point in enumerate(lines):\n if point == '0':\n curr_point_x = piece.x+(point_index-2)*size_piece\n curr_point_y = piece.y+(lines_index-2)*size_piece\n locked_positions[int((curr_point_y-gap)/size_piece)][int((curr_point_x-gap)/size_piece)]=piece.color\n n_elem[int((curr_point_y-gap)/size_piece)]+=1\n\ndef print_locked(locked_positions): \n for y in range(20):\n for x in range(10):\n if locked_positions[y][x] != (0,0,0):\n pygame.draw.rect(background,locked_positions[y][x],(x*size_piece+gap,y*size_piece+gap,size_piece,size_piece))\n\ndef check_lines(n_elem):\n for y in range(20):\n if n_elem[y] == 10:\n return y\n return -1\n\ndef clear_line(locked_positions,line,n_elem):\n n_elem[line] = 0\n for x in range(10):\n locked_positions[line][x]=(0,0,0)\n for y in reversed(range(line)):\n for x in range(10):\n if locked_positions[y][x] != (0,0,0):\n n_elem[y] = n_elem[y]-1\n n_elem[y+1] += 1 \n previous = locked_positions[y][x]\n locked_positions[y][x]= (0,0,0)\n locked_positions[y+1][x] = previous \n\ndef show_score(total_points,level):\n scoretext = myfont.render(\"Points: \" + str(total_points), 1, (212, 81, 19))\n leveltext = myfont.render(\"Level: \" + str(level),1,(212, 81, 19))\n scorebox = scoretext.get_rect(center=(gap*2+play_width+75,gap+35))\n levelbox = scoretext.get_rect(center=(gap*2+play_width+75,2*gap+70+35))\n screen.blit(leveltext,levelbox)\n screen.blit(scoretext, scorebox)\n\nnext_piece = get_piece()\natual_piece = get_piece()\nstart_time = time()\nstart_time_level = time()\nstart_time_hard_drop = 0\nlocked_positions = [[(0,0,0) for _ in range(10) ]for _ in range(20)]\nn_elem = [0 for _ in range (20)]\ntotal_points = 0\nmyfont = pygame.font.SysFont(\"Arial\",20)\nhard_drop_mode = False\nvelocity = 0.5\npause = False\npause_start = 0\npause_end = 0\npontuation = [40,100,300,1200]\n\ndef add_points_lines(n,level):\n total=0\n for j in reversed(range(1,5)):\n total += int(n/j)*pontuation[j-1]*(level+1)\n n = n % j\n return total\n\nlevel = 0\nwhile 1:\n\n for event in pygame.event.get():\n if event.type == pygame.QUIT:\n sys.exit()\n if event.type == pygame.KEYDOWN:\n if event.key == pygame.K_SPACE:\n atual_piece = get_piece()\n if not pause: \n if event.key == pygame.K_RIGHT:\n atual_piece.x += size_piece \n #print(pos_valid(atual_piece))\n if not pos_valid(atual_piece,locked_positions):\n atual_piece.x -= size_piece\n if event.key == pygame.K_LEFT:\n atual_piece.x -= size_piece \n #print(pos_valid(atual_piece))\n if not pos_valid(atual_piece,locked_positions):\n atual_piece.x += size_piece \n if event.key == pygame.K_DOWN:\n total_points += atual_piece.free_fall() \n start_time_hard_drop = time()\n hard_drop_mode = True\n if event.key == pygame.K_UP:\n atual_piece.change_orientation()\n if event.key == pygame.K_p:\n if not pause:\n pause_start = time()\n else :\n pause_end = time() \n pause = not pause\n \n\n curr_time = time()\n if velocity > 0.1:\n velocity = 0.5+(level*(-0.02))\n\n if curr_time - start_time > velocity and not pause:\n #print(curr_time-start_time) \n start_time = time()\n atual_piece.fall()\n\n if curr_time - start_time_level-(pause_end-pause_start) > 15 and not pause:\n start_time_level = time()\n level += 1\n\n if curr_time - start_time_hard_drop > 0.25:\n hard_drop_mode = False\n\n #print(hard_drop_mode)\n #print(fallen_piece(atual_piece,locked_positions))\n if not hard_drop_mode:\n if fallen_piece(atual_piece,locked_positions):\n add_locked(atual_piece,locked_positions)\n atual_piece = next_piece\n next_piece = get_piece()\n if not pos_valid(atual_piece,locked_positions):\n sys.exit()\n \n\n background.fill(black)\n pygame.draw.rect(background, (blue_bg), (gap,gap,play_width,play_height))\n pygame.draw.rect(background, (blue_bg), (play_width+2*gap,gap,150,70))\n pygame.draw.rect(background, (blue_bg), (play_width+2*gap,2*gap+70,150,70))\n \n cleared_lines = 0\n while 1:\n line = check_lines(n_elem)\n if line == -1:\n break\n clear_line(locked_positions,line,n_elem)\n cleared_lines += 1\n\n if cleared_lines != 0:\n total_points += add_points_lines(cleared_lines,level)\n\n #print(n_elem)\n print_shape(atual_piece,atual_piece.x,atual_piece.y)\n print_shape(next_piece,2*gap+play_width+75-10,2*gap+200)\n print_locked(locked_positions)\n\n \"\"\" print(atual_piece.x)\n print(atual_piece.y)\n print(atual_piece.shape.index)\n print(atual_piece.color)\n print(atual_piece.orientation) \"\"\"\n #print(total_points)\n \n screen.blit(background,(0,0))\n show_score(int(total_points),level)\n pygame.display.flip()\n"
},
{
"alpha_fraction": 0.7575757503509521,
"alphanum_fraction": 0.7575757503509521,
"avg_line_length": 15.5,
"blob_id": "453fd51f9aa5d2ff8509c3e5bba5920531e08a61",
"content_id": "5daa22579d268821c1d6ae21cec4a86fd01efb23",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 33,
"license_type": "permissive",
"max_line_length": 20,
"num_lines": 2,
"path": "/README.md",
"repo_name": "josemartins2121/AI_Tetris",
"src_encoding": "UTF-8",
"text": "# AI_Tetris\nDevelop AI to tetris\n"
}
] | 2 |
younusraza909/MachineLearning_DataScience | https://github.com/younusraza909/MachineLearning_DataScience | 365fcf494f8d69803b268eaa49329b5e9a658517 | 6975ed85a12890b230d907736245bfe34fc1e4ed | 5e67a55f53942a04f928464504ff93eff0868f56 | refs/heads/master | 2020-12-20T06:44:27.388917 | 2020-03-05T04:44:40 | 2020-03-05T04:44:40 | 235,991,798 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7001044750213623,
"alphanum_fraction": 0.7230929732322693,
"avg_line_length": 20.244443893432617,
"blob_id": "a043b183dfbaa10a16a3bcf20e8b3bb13559917e",
"content_id": "bdc072e8483dc403c50649518caa901d6004f8f7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 957,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 45,
"path": "/Regression/Decision Tree Regression/Decision Tree Regression.py",
"repo_name": "younusraza909/MachineLearning_DataScience",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 28 09:47:44 2020\n\n@author: Raza\n\"\"\"\n\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n#Loading Data Set\ndata=pd.read_csv(\"DTR.csv\")\n\n#Splitting Data \nX=data.iloc[:,0:1].values\nY=data.iloc[:,1].values\n\n#Regression\nfrom sklearn.tree import DecisionTreeRegressor\nDTR_reg=DecisionTreeRegressor(random_state=0)\nDTR_reg.fit(X,Y)\n\n#Visualization\nplt.scatter(X,Y,color=\"red\")\nplt.plot(X,DTR_reg.predict(X),color=\"blue\")\nplt.title(\" DTR MODEL Position Vs Salary\")\nplt.xlabel(\"Positon Of Employee\")\nplt.ylabel(\"Salary\")\nplt.show()\n\n#Changing a littile bit to more prominently visualize data\nx_grid=np.arange(min(X),max(X),0.1)\nx_grid=x_grid.reshape(len(x_grid),1)\nplt.scatter(X,Y,color=\"red\")\nplt.plot(x_grid,DTR_reg.predict(x_grid),color=\"blue\")\nplt.title(\" DTR MODEL Position Vs Salary\")\nplt.xlabel(\"Positon Of Employee\")\nplt.ylabel(\"Salary\")\nplt.show()\n\n\n\n#Prediction\nDTR_reg.predict([[6.5]])\n\n"
},
{
"alpha_fraction": 0.584055483341217,
"alphanum_fraction": 0.6351819634437561,
"avg_line_length": 30.216217041015625,
"blob_id": "1890ba84c5d885b51f94a1b3519f7c0eb5d1319e",
"content_id": "7ef98e82f59f4be6301df22fa5970501e3dcd6f6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1154,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 37,
"path": "/Clustering Unseprvised/Hierarchical Clustering/Heirarchichal.py",
"repo_name": "younusraza909/MachineLearning_DataScience",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Mar 4 15:24:32 2020\n\n@author: Raza\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndataset = pd.read_csv('HR.csv')\nX = dataset.iloc[:, [1, 2]].values\n\nimport scipy.cluster.hierarchy as sch\ndendrogram = sch.dendrogram(sch.linkage(X, method='ward'))\nplt.title('Dendogram')\nplt.xlabel('Customer')\nplt.ylabel('Distances')\nplt.show();\n\nfrom sklearn.cluster import AgglomerativeClustering\nhc = AgglomerativeClustering(n_clusters = 5, affinity ='euclidean', linkage = 'ward' )\ny_hc=hc.fit_predict(X)\n\n\n# Visualising the clusters\nplt.scatter(X[y_hc == 0, 0], X[y_hc == 0, 1], s = 100, c = 'red', label = 'Cluster 1')\nplt.scatter(X[y_hc == 1, 0], X[y_hc == 1, 1], s = 100, c = 'blue', label = 'Cluster 2')\nplt.scatter(X[y_hc == 2, 0], X[y_hc == 2, 1], s = 100, c = 'green', label = 'Cluster 3')\nplt.scatter(X[y_hc == 3, 0], X[y_hc == 3, 1], s = 100, c = 'cyan', label = 'Cluster 4')\nplt.scatter(X[y_hc == 4, 0], X[y_hc == 4, 1], s = 100, c = 'black', label = 'Cluster 5')\n\nplt.title('Clusters of customers')\nplt.xlabel('Annual Income (k$)')\nplt.ylabel('Spending Score (1-100)')\nplt.legend()"
},
{
"alpha_fraction": 0.7018442749977112,
"alphanum_fraction": 0.7264344096183777,
"avg_line_length": 21.159090042114258,
"blob_id": "deec6dac8cb27145899e97e1629fe8493d7d9647",
"content_id": "78d67837163d50d0ac55531db4199efd96cf7d60",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 976,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 44,
"path": "/Regression/Random Forest Regression/Random Forest Regressor.py",
"repo_name": "younusraza909/MachineLearning_DataScience",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 28 10:35:22 2020\n\n@author: Raza\n\"\"\"\n\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n#Loading Data Set\ndata=pd.read_csv(\"RFR.csv\")\n\n#Splitting Data \nX=data.iloc[:,0:1].values\nY=data.iloc[:,1].values\n\n#Regression\nfrom sklearn.ensemble import RandomForestRegressor\nRFR_reg=RandomForestRegressor(random_state=0,n_estimators=10)\nRFR_reg.fit(X,Y)\n\n#Visualization\nplt.scatter(X,Y,color=\"red\")\nplt.plot(X,RFR_reg.predict(X),color=\"blue\")\nplt.title(\" RFR MODEL Position Vs Salary\")\nplt.xlabel(\"Positon Of Employee\")\nplt.ylabel(\"Salary\")\nplt.show()\n\n#Changing a littile bit to more prominently visualize data\nx_grid=np.arange(min(X),max(X),0.1)\nx_grid=x_grid.reshape(len(x_grid),1)\nplt.scatter(X,Y,color=\"red\")\nplt.plot(x_grid,RFR_reg.predict(x_grid),color=\"blue\")\nplt.title(\" RFR MODEL Position Vs Salary\")\nplt.xlabel(\"Positon Of Employee\")\nplt.ylabel(\"Salary\")\nplt.show()\n\n\n\n#Prediction\nRFR_reg.predict([[6.5]])\n\n"
},
{
"alpha_fraction": 0.742323100566864,
"alphanum_fraction": 0.7543390989303589,
"avg_line_length": 22.421875,
"blob_id": "e293e85321ce1a51c2c8fda9d2a62221e4288e39",
"content_id": "852915efac310e35eb27623e554dfc84286dcfd5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1498,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 64,
"path": "/Regression/Regression Evaltion Metrics/Regression Evalution Metrics.py",
"repo_name": "younusraza909/MachineLearning_DataScience",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 25 14:05:59 2020\n\n@author: Raza\n\"\"\"\n\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport pandas as pd\n\ndata=pd.read_csv(\"Salary_DataSet.csv\")\n\n#Spliting Data Into X And Y\n\nX=data.iloc[:,:-1].values\nY=data.iloc[:,1].values\n\n#Spliting data into training and testing\nfrom sklearn.model_selection import train_test_split\nX_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.3,random_state=0) \n\n#REGRESSION\nfrom sklearn.linear_model import LinearRegression\nreg=LinearRegression()\nreg.fit(X_train,Y_train)\n\ny_predict=reg.predict(X_test)\n\n#Plotting the graph Train Data\nplt.scatter(X_train,Y_train,color=\"red\")\nplt.plot(X_train,reg.predict(X_train),color=\"blue\")\nplt.title(\"Salary Vs Experience\")\nplt.xlabel(\"Experience\")\nplt.ylabel(\"Salary\")\nplt.show()\n\n\n#Plotting the graph Test Data\nplt.scatter(X_test,Y_test,color=\"red\")\nplt.plot(X_test,reg.predict(X_test),color=\"blue\")\nplt.title(\"Salary Vs Experience\")\nplt.xlabel(\"Experience\")\nplt.ylabel(\"Salary\")\nplt.show()\n\n####Working For Error\nfrom sklearn.metrics import mean_absolute_error\nMAE=mean_absolute_error(Y_test,y_predict) \nprint(MAE)\n\nfrom sklearn.metrics import mean_squared_error\nMSE=mean_squared_error(Y_test,y_predict) \nprint(MSE)\n\nfrom math import sqrt\nfrom sklearn.metrics import mean_squared_error\nRMSE=sqrt(mean_squared_error(Y_test,y_predict)) \nprint(RMSE)\n\n\nfrom sklearn.metrics import mean_squared_log_error\nRMSLE=sqrt(mean_squared_log_error(Y_test,y_predict)) \nprint(RMSLE)"
},
{
"alpha_fraction": 0.714031994342804,
"alphanum_fraction": 0.7460035681724548,
"avg_line_length": 23.521739959716797,
"blob_id": "e10c00302e25fc273a40322346d95c48a0e8a2b8",
"content_id": "e7871d73c548ecd3f0ce4b2e403eca08704f0ece",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 563,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 23,
"path": "/Regression/MultiVariabel Linear Regression/MultiVariable Regression.py",
"repo_name": "younusraza909/MachineLearning_DataScience",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Sat Jan 25 14:51:16 2020\n\n@author: Raza\n\"\"\"\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\ndata=pd.read_csv(\"M_Regression.csv\")\nX=data.iloc[:,:-1].values\nY=data.iloc[:,3].values\n\n#splitting data in Train Test\nfrom sklearn.model_selection import train_test_split \nX_train,X_test,Y_train,Y_test=train_test_split(X,Y,test_size=0.3,random_state=0) \n\n#MultiVariable Regression\nfrom sklearn.linear_model import LinearRegression\nreg=LinearRegression()\nreg.fit(X_train,Y_train)\ny_predict=reg.predict(X_test)"
},
{
"alpha_fraction": 0.7419669032096863,
"alphanum_fraction": 0.7536514401435852,
"avg_line_length": 22.88372039794922,
"blob_id": "338d98c90c28bca243d7add5219ee7ea3a0fd046",
"content_id": "7c600e5676257486408966eb6d44a8c641649278",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1027,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 43,
"path": "/Regression/Support Vector NonLinear Regression/SVR.py",
"repo_name": "younusraza909/MachineLearning_DataScience",
"src_encoding": "UTF-8",
"text": "\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n#Loading Data Set\ndata=pd.read_csv(\"Poly_dataSet.csv\")\n\n#Splitting Data \nX=data.iloc[:,0:1].values\nY=data.iloc[:,1].values\n\n#Regression\nfrom sklearn.linear_model import LinearRegression\nlin_reg=LinearRegression()\nlin_reg.fit(X,Y)\n\nfrom sklearn.preprocessing import PolynomialFeatures\npoly_reg=PolynomialFeatures(degree=2)\nX_poly=poly_reg.fit_transform(X)\npoly_reg.fit(X_poly,Y)\nlin_reg_2=LinearRegression()\nlin_reg_2.fit(X_poly,Y)\n\n#Visualization\nplt.scatter(X,Y,color=\"red\")\nplt.plot(X,lin_reg.predict(X),color=\"blue\")\nplt.title(\" Polynomial Regression Salary Vs Experience\")\nplt.xlabel(\"Positon Of Employee\")\nplt.ylabel(\"Salary\")\nplt.show()\n\n\n#Plotting the graph Test Data\nplt.scatter(X,Y,color=\"red\")\nplt.plot(X,lin_reg_2.predict(X_poly),color=\"blue\")\nplt.title(\"Polynomial Salary Vs Experience\")\nplt.xlabel(\"Positon Of Employee\")\nplt.ylabel(\"Salary\")\nplt.show()\n\n#Prediction\nlin_reg.predict([[6.5]])\n\nlin_reg_2.predict(poly_reg.fit_transform([[6.5]]))"
},
{
"alpha_fraction": 0.7390000224113464,
"alphanum_fraction": 0.7549999952316284,
"avg_line_length": 25.972972869873047,
"blob_id": "3889d02b349f34f156f3b079e577274876173db7",
"content_id": "845fea71d5d94a9f6ed223d6dcf790b11b9a2a11",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1000,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 37,
"path": "/Data PreProcessing/Preprocessing.py",
"repo_name": "younusraza909/MachineLearning_DataScience",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n\"\"\"\nSpyder Editor\n\nThis is a temporary script file.\n\"\"\"\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\n\ndata=pd.read_csv(\"DataSet.csv\")\nX=data.iloc[:,:-1].values\nY=data.iloc[:,3].values\n\n#For Handling Missing Values\nfrom sklearn.preprocessing import Imputer\nimputer=Imputer(missing_values=\"NaN\",strategy=\"mean\",axis=0)\nimputer=imputer.fit(X[:,1:3])\nX[:,1:3]=imputer.transform(X[:,1:3])\n\n#For dummy Variable For X\nfrom sklearn.preprocessing import OneHotEncoder,LabelEncoder\nlabelEncoder_x=LabelEncoder()\nX[:,0]=labelEncoder_x.fit_transform(X[:,0])\nonehot_x=OneHotEncoder(categorical_features=[0])\nX=onehot_x.fit_transform(X).toarray()\n\n#train Test Split\nfrom sklearn.model_selection import train_test_split\nX_train,X_test,Y_train,Y_Test=train_test_split(X,Y,test_size=0.2,random_state=0)\n\n#Standarized_X\nfrom sklearn.preprocessing import StandardScaler\nstc_x=StandardScaler()\nX_train=stc_x.fit_transform(X_train)\nX_test=stc_x.fit_transform(X_test)\n\n\n"
}
] | 7 |
saiteja93/Data-structures- | https://github.com/saiteja93/Data-structures- | d6c7824bc7a3150c4e5bc487b28e9a8e813b0dbb | 575f4a68589c077d1efeee0e9f077e64ba1e68c1 | c8559b3c338d044d25e02023ccf27245c8f5fe27 | refs/heads/master | 2020-03-18T07:45:20.126885 | 2018-05-24T18:39:14 | 2018-05-24T18:39:14 | 134,471,359 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5508021116256714,
"alphanum_fraction": 0.5784313678741455,
"avg_line_length": 33,
"blob_id": "0eb4764e7270a4a9f957bf26f784a1c6ee8ae92a",
"content_id": "44ed9b29690e45dff9e852fa25c4a6470141f9ed",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1122,
"license_type": "no_license",
"max_line_length": 261,
"num_lines": 33,
"path": "/Coin Change.py",
"repo_name": "saiteja93/Data-structures-",
"src_encoding": "UTF-8",
"text": "\"\"\"\nYou are given coins of different denominations and a total amount of money amount. Write a function to compute the fewest number of coins that you need to make up that amount. If that amount of money cannot be made up by any combination of the coins, return -1.\n\nExample 1:\n\nInput: coins = [1, 2, 5], amount = 11\nOutput: 3\nExplanation: 11 = 5 + 5 + 1\nExample 2:\n\nInput: coins = [2], amount = 3\nOutput: -1\nNote:\nYou may assume that you have an infinite number of each kind of coin.\n\"\"\"\n\ndef coinChange(self, coins, amount):\n minCoins = [0]*(amount+1)\n if amount ==0: return 0\n if all(i> amount for i in coins): return -1\n if len(coins) == 1:\n if amount % coins[0] == 0: return amount/coins[0]\n else: return -1\n for i in range(1,amount+1):\n minCoins[i] = float(\"inf\")\n for m in coins:\n if m<= i:\n total = minCoins[i-m] + 1\n if total <= minCoins[i]:\n minCoins[i] = total\n\n if minCoins[amount] == float(\"inf\"): return -1\n else: return minCoins[amount]\n"
},
{
"alpha_fraction": 0.6438775658607483,
"alphanum_fraction": 0.6494898200035095,
"avg_line_length": 51.97297286987305,
"blob_id": "8f49e0feb0da6f51b7fc3d86cf97a874fd7e2f66",
"content_id": "03eb74ac04c1f28213f5fa435b02333c7e32d715",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1960,
"license_type": "no_license",
"max_line_length": 511,
"num_lines": 37,
"path": "/Longest Substring Without Repeating Characters.py",
"repo_name": "saiteja93/Data-structures-",
"src_encoding": "UTF-8",
"text": "\"\"\"\nGiven a string, find the length of the longest substring without repeating characters.\n\nExamples:\n\nGiven \"abcabcbb\", the answer is \"abc\", which the length is 3.\n\nGiven \"bbbbb\", the answer is \"b\", with the length of 1.\n\nGiven \"pwwkew\", the answer is \"wke\", with the length of 3. Note that the answer must be a substring, \"pwke\" is a subsequence and not a substring.\n\n\"\"\"\n\"\"\"\n The idea is to scan the string from left to right, keep track of the maximum length Non-Repeating Character Substring (NRCS) seen so far. Let the maximum length be max_len. When we traverse the string, we also keep track of length of the current NRCS using cur_len variable. For every new character, we look for it in already processed part of the string (A temp array called visited[] is used for this purpose). If it is not present, then we increase the cur_len by 1. If present, then there are two cases:\n\na) The previous instance of character is not part of current NRCS (The NRCS which is under process). In this case, we need to simply increase cur_len by 1.\nb) If the previous instance is part of the current NRCS, then our current NRCS changes. It becomes the substring staring from the next character of previous instance to currently scanned character. We also need to compare cur_len and max_len, before changing current NRCS (or changing cur_len).\n\n\"\"\"\n\nclass Solution(object):\n def lengthOfLongestSubstring(self, s):\n dic, start, maxlen = {}, 0, 0\n for a, b in enumerate(s):\n if b not in dic:\n #print a,start\n maxlen = max(maxlen, a - start + 1 )\n else:\n if dic[b] < start:\n #print a,start, \"less\"\n maxlen = max(maxlen, a - start + 1 )\n else:\n start = dic[b]+1\n #print a,start, \"greater\"\n maxlen = max(maxlen, a - start + 1 )\n dic[b] = a\n return maxlen\n"
},
{
"alpha_fraction": 0.6533847451210022,
"alphanum_fraction": 0.6610968112945557,
"avg_line_length": 46.448978424072266,
"blob_id": "f4fccd2ed75ef0618f72bb70db50758aa948916b",
"content_id": "9de3220b69e229da9ab88193f8f72a6dcbf48f45",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2334,
"license_type": "no_license",
"max_line_length": 283,
"num_lines": 49,
"path": "/Substring with Concatenation of All Words.py",
"repo_name": "saiteja93/Data-structures-",
"src_encoding": "UTF-8",
"text": "\"\"\"\nYou are given a string, s, and a list of words, words, that are all of the same length. Find all starting indices of substring(s) in s that is a concatenation of each word in words exactly once and without any intervening characters.\n\nExample 1:\n\nInput:\n s = \"barfoothefoobarman\",\n words = [\"foo\",\"bar\"]\nOutput: [0,9]\nExplanation: Substrings starting at index 0 and 9 are \"barfoor\" and \"foobar\" respectively.\nThe output order does not matter, returning [9,0] is fine too.\n\n\"\"\"\n\nfrom collections import Counter, defaultdict\nclass Solution(object):\n def test(self, sub_str, word_len, ctr):\n i, seen = 0, defaultdict(int)\n while i < len(sub_str):\n next_word = sub_str[i:i+word_len]\n if next_word not in ctr or seen[next_word] == ctr[next_word]:\n return False\n seen[next_word], i = seen[next_word] + 1, i+word_len\n return True\n\n def findSubstring(self, s, words):\n \"\"\"\n :type s: str\n :type words: List[str]\n :rtype: List[int]\n \"\"\"\n start, end, result = 0, len(words)*len(words[0])-1, []\n ctr = Counter(words)\n while end < len(s):\n if self.test(s[start:end+1], len(words[0]), ctr):\n result.append(start)\n start, end = start+1, end+1\n return result\n\n# Say length of each word is wl and we have wc words. total_len of substring = wl * wc\n# Two pointer sliding window solution. Initialize a window [start, end] = [0, total_len-1]\n# Now we slide through s and capture every substring. We then test if this substring is valid and meets our conditions.\n# We prepare a frequency map of input words. We call it ctr.\n# We initialize a dictionary called seen.\n# Now we pick every word (called next_word) sequentially in our window. Note there will be only wc words each of length wl.\n# If next_word is not in ctr then we know the window is invalid. If it is, but the frequency in seen is already equal to the frequency in ctr, then we know we have an extra occurence of this word in the window and the window is invalid. Otherwise, we increment its frequency in seen.\n# If every word in this window is valid, then the entire window is valid.\n# Time complexity: (len(s) - wl * wc) * wc or number_of_windows * words_per_window\n# Space complexity: O(wc) + O(wc)\n \n"
},
{
"alpha_fraction": 0.5392938256263733,
"alphanum_fraction": 0.5432801842689514,
"avg_line_length": 37.173912048339844,
"blob_id": "3f55555f4af8f116becda3dcc1da94f21b7a0b17",
"content_id": "3ee0d0fb777cd23fb4249b0335df597726b9e3d9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1764,
"license_type": "no_license",
"max_line_length": 343,
"num_lines": 46,
"path": "/Minimum Window Substring.py",
"repo_name": "saiteja93/Data-structures-",
"src_encoding": "UTF-8",
"text": "\"\"\"\nGiven a string S and a string T, find the minimum window in S which will contain all the characters in T in complexity O(n).\n\nExample:\n\nInput: S = \"ADOBECODEBANC\", T = \"ABC\"\nOutput: \"BANC\"\nNote:\n\nIf there is no such window in S that covers all characters in T, return the empty string \"\".\nIf there is such window, you are guaranteed that there will always be only one unique minimum window in S.\n\"\"\"\nclass Solution(object):\n def minWindow(self, s, t):\n \"\"\"\n :type s: str\n :type t: str\n :rtype: str\n \"\"\"\n # @return a string\n def minWindow(self, S, T):\n indices = {}\n for char in T:\n indices[char] = []\n miss = list(T)\n start = 0\n end = len(S)\n for i in range(len(S)):\n if S[i] in T:\n if S[i] not in miss and indices[S[i]] != []:\n indices[S[i]].pop(0)\n elif S[i] in miss:\n miss.remove(S[i])\n indices[S[i]].append(i)\n print indices\n if miss == []:\n maximum = max([x[-1] for x in indices.values()])\n minimum = min([x[-1] for x in indices.values()])\n if maximum-minimum+1 < end-start+1:\n start = minimum\n end = maximum\n if miss != []:\n return \"\"\n else:\n return S[start:end+1]\n # Basically I kept a dictionary to record the index of each character of T. Each time I found a window, (when miss == []), I checked the length of this window by subtracting the maximum index and the minimum index of the characters. If this window is the smallest one so far, I record its beginning and ending index as “start” and “end.”\n"
},
{
"alpha_fraction": 0.5743243098258972,
"alphanum_fraction": 0.607545018196106,
"avg_line_length": 38.46666717529297,
"blob_id": "d4de8baedfdbb6602dd197e0ccc21081374056ca",
"content_id": "c98bb72a3152e61f56382935526bdf251d640bbd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1776,
"license_type": "no_license",
"max_line_length": 336,
"num_lines": 45,
"path": "/house_robber.py",
"repo_name": "saiteja93/Data-structures-",
"src_encoding": "UTF-8",
"text": "\"\"\"\n\nYou are a professional robber planning to rob houses along a street. Each house has a certain amount of money stashed, the only constraint stopping you from robbing each of them is that adjacent houses have security system connected and it will automatically contact the police if two adjacent houses were broken into on the same night.\n\nGiven a list of non-negative integers representing the amount of money of each house, determine the maximum amount of money you can rob tonight without alerting the police.\n\nExample 1:\n\nInput: [1,2,3,1]\nOutput: 4\nExplanation: Rob house 1 (money = 1) and then rob house 3 (money = 3).\n Total amount you can rob = 1 + 3 = 4.\nExample 2:\n\nInput: [2,7,9,3,1]\nOutput: 12\nExplanation: Rob house 1 (money = 2), rob house 3 (money = 9) and rob house 5 (money = 1).\n Total amount you can rob = 2 + 9 + 1 = 12.\n\"\"\"\n\ndef rob(self, nums):\n \"\"\"\n :type nums: List[int]\n :rtype: int\n \"\"\"\n \"\"\"\n Let rob(n) be the maximum value that can be stolen given the houses nums[0:n].\n\n Base cases:\n rob(0) = nums[0] rob the first house.\n rob(1) = max(nums[0], nums[1]) either rob the first house or second house.\n\n Recursive relation:\n rob(n) = max(nums[n] + rob(n-2), rob(n-1)) for a house, we can either rob it or don't rob it, so nums[n] + rob(n-2) is robbing it, rob(n-1) is not robbing it.\n \"\"\"\n if len(nums) == 0: return 0\n if len(nums) == 1: return nums[0]\n if len(nums) == 2: return max(nums[0], nums[1])\n rob = [0]*len(nums)\n rob[0] = nums[0]\n rob[1] = max(nums[0], nums[1])\n for i in xrange(2,len(nums)):\n rob[i] = max(nums[i] + rob[i-2], rob[i-1])\n\n return rob[-1]\n"
}
] | 5 |
vghnassia/td1---exo3 | https://github.com/vghnassia/td1---exo3 | 423b305505ef260da2d578e960fe023b3fcd42d3 | 413fe666aec6757319d3a4369f758cfc539c36ce | 5cb07e1c36631f9c2a845dbdd764955c038373d6 | refs/heads/master | 2022-11-20T07:01:43.840583 | 2020-07-09T05:38:15 | 2020-07-09T05:38:15 | 278,272,902 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5958333611488342,
"alphanum_fraction": 0.6208333373069763,
"avg_line_length": 16.14285659790039,
"blob_id": "8b49395f4c53aa34e95627c1295b751d888d7f29",
"content_id": "4350863b25c82a511e01afceae5779655d7fa24d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 240,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 14,
"path": "/main.py",
"repo_name": "vghnassia/td1---exo3",
"src_encoding": "UTF-8",
"text": "def on_button_pressed_a():\n global nb\n nb += 1\ninput.on_button_pressed(Button.A, on_button_pressed_a)\n\nnb = 1\nwhile True:\n basic.show_number(nb)\n if nb > 10:\n nb = 10\n\ndef on_forever():\n pass\nbasic.forever(on_forever)\n"
}
] | 1 |
shubhendutiwari/P_BasicLearning | https://github.com/shubhendutiwari/P_BasicLearning | 7d1aaa4ebb86161ae9c4ea4621118b8965f0ba1f | f5d0bd8e81ed4d1af213d86d9c908c24b916d6a6 | 667ea7323e99dc9443b67ebdc44603beb0a12d2a | refs/heads/master | 2020-06-24T08:24:52.856629 | 2019-08-06T02:37:10 | 2019-08-06T02:37:10 | 198,912,774 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6486486196517944,
"alphanum_fraction": 0.6732186675071716,
"avg_line_length": 24.4375,
"blob_id": "eda036e5cea8fb05b0b0d7bc163c6d748aa0ee6d",
"content_id": "5417d47a722a6a138e41099f21c18f87f5be33e5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 407,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 16,
"path": "/MaxValue.py",
"repo_name": "shubhendutiwari/P_BasicLearning",
"src_encoding": "UTF-8",
"text": "\"\"\"Define a function max()that takes two numbers as arguments and\n returns the largest of them. Use the if-then-else construct available in Python\"\"\"\n\nvalue1: int = int(input(\"Enter First number\"))\n\nvalue2: int = int(input(\"Enter Second number\"))\n\n\ndef max_value(val1, val2):\n if val1 > val2:\n return val1\n else:\n return val2\n\n\nprint(str(max_value(value1, value2)) + \" : is max value\")\n"
},
{
"alpha_fraction": 0.5857987999916077,
"alphanum_fraction": 0.610946774482727,
"avg_line_length": 28.39130401611328,
"blob_id": "ad003d85eece847682dd54fd3ce44f366783ec58",
"content_id": "ae4cf85404d285ae3d8e8f313e2c8856c92741d2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 676,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 23,
"path": "/SumMultiply.py",
"repo_name": "shubhendutiwari/P_BasicLearning",
"src_encoding": "UTF-8",
"text": "\"\"\"Define a function sum() and a function multiply() that sums and multiplies(respectively) all the numbers in a list \nof numbers. For example, sum([1, 2, 3, 4, 5]) should return 15, and multiply([1, 2, 3, 4]) should return 24\"\"\"\n\ndef sums(lsts):\n count =0\n for x in lsts:\n count = count+x\n return count\n \ndef multiply(lsts):\n mult = 1\n for x in lsts:\n mult=mult*x \n return mult\n\nlst=[]\nn = int(input(\"Enter number of element you want to enter : \"))\nfor i in range (0,n):\n print(\"Enter : \"+ str(i+1)+\" element\")\n ele = int(input())\n lst.append(ele)\n \nprint(\"Sum is : \"+str(sums(lst))+\"& multiplication is : \"+str(multiply(lst)))\n"
},
{
"alpha_fraction": 0.6342710852622986,
"alphanum_fraction": 0.6368286609649658,
"avg_line_length": 29.076923370361328,
"blob_id": "1a1874a08d107e2ffdcf1714799548fab26033ef",
"content_id": "c75da16becb2a87d02664ba8460ab618adbe2703",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 391,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 13,
"path": "/checkVowel.py",
"repo_name": "shubhendutiwari/P_BasicLearning",
"src_encoding": "UTF-8",
"text": "\"\"\" Write a function that takes a character (i.e. a string of length 1)\nand returns True if it is a vowel, False otherwise\"\"\"\n\ndef checkVowel(checkChar):\n check=checkChar.lower()\n print(check)\n if check ==\"a\" or check ==\"e\" or check ==\"i\" or check ==\"o\" or check == \"u\":\n return True\n else:\n return False\n\nchar = input(\"Enter character : \")\nprint(checkVowel(char))\n"
},
{
"alpha_fraction": 0.7022696733474731,
"alphanum_fraction": 0.7049399018287659,
"avg_line_length": 34.66666793823242,
"blob_id": "d39784b403a60819e284954970b61ecfb52f6c3c",
"content_id": "805630e13029575c8bd38baa7bac116645cf629c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 749,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 21,
"path": "/SpellingCorrection.py",
"repo_name": "shubhendutiwari/P_BasicLearning",
"src_encoding": "UTF-8",
"text": "\"\"\" Define a simple \"spelling correction\" function correct() that takes a string and sees to it that\n1) two or more occurrences of the space character is compressed into one, and\n2) inserts an extra space after a period if the period is directly followed by a letter.\nE.g. correct(\"This is very funny and cool.Indeed!\") should return \"This is very funny and cool. Indeed!\".\"\"\"\n\nimport re\n\n\ndef correct(inputString):\n #Removing extra spaces\n correctedString = re.sub('\\ +', ' ', inputString)\n\n #Putting extra space after period\n correctedString = re.sub('\\.', '. ', correctedString)\n\n print(correctedString)\n\n\ninputString = \"This is very funny and cool.Indeed!. But you should.try this also\"\n\ncorrect (inputString)\n"
},
{
"alpha_fraction": 0.6666666865348816,
"alphanum_fraction": 0.6797385811805725,
"avg_line_length": 24.5,
"blob_id": "a63a0509e33d4b8505721da652216fee68c9d955",
"content_id": "9346050904138dfffaef85a7a88af556fa888a9b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 306,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 12,
"path": "/Palindrome.py",
"repo_name": "shubhendutiwari/P_BasicLearning",
"src_encoding": "UTF-8",
"text": "\"\"\"Define a function is_palindrome() that recognizes palindromes\"\"\"\n\n\ndef is_palindrome(string1):\n if string1[::-1] == string1:\n return \"This is palindrome\"\n else:\n return \"This is not palindrome\"\n\nstring = input(\"Enter string for checking palindrome : \")\n\nprint(is_palindrome(string))\n"
},
{
"alpha_fraction": 0.6225165724754333,
"alphanum_fraction": 0.6324503421783447,
"avg_line_length": 24.25,
"blob_id": "a095b4e6bad70251beedd044f5a1339160305fdc",
"content_id": "283fb84e7844abfd42dc03ff54b40abef34a161e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 302,
"license_type": "no_license",
"max_line_length": 66,
"num_lines": 12,
"path": "/DigitalRoot.py",
"repo_name": "shubhendutiwari/P_BasicLearning",
"src_encoding": "UTF-8",
"text": "\"\"\"Write a python function to find the digital root of a number\"\"\"\n\ndigit = input(\"Enter the digit for digital root : \")\ndigit_root = 0\nwhile len(digit) != 1:\n digit_root = 0\n for x in digit:\n digit_root = digit_root + int(x)\n\n digit = str(digit_root)\n\nprint(\"Digit root is : \" + digit)"
},
{
"alpha_fraction": 0.6431818008422852,
"alphanum_fraction": 0.6659091114997864,
"avg_line_length": 35.58333206176758,
"blob_id": "0daf1f445a4483452c734ab7745267ada4df17fe",
"content_id": "e34ca5f34b07392bbfa97e691e2f0abe20ede072",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 440,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 12,
"path": "/isogram.py",
"repo_name": "shubhendutiwari/P_BasicLearning",
"src_encoding": "UTF-8",
"text": "\"\"\"3)\tAn isogram (also known as a \"nonpattern word\") is a logological term for a word or phrase without a repeating letter.\n Write a python function to test, if a given word (passed as an argument) is an perfect isogram.\"\"\"\n\nstr1: str = input (\"Enter word: \")\n\nstr1: str = str1.lower()\nfor word in str1:\n if str1.count(word) >1:\n print(str1 + \" :is not a perfect isogram\")\n exit(0)\n\nprint(str1 + \" :is a perfect isogram\")\n\n"
},
{
"alpha_fraction": 0.625806450843811,
"alphanum_fraction": 0.6283870935440063,
"avg_line_length": 30,
"blob_id": "8cd55a4b956cafe69e5b3b06c0990d933aab65b2",
"content_id": "d13ae8eb5f25428908ceaa95bcde9ca30a6ed07a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 777,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 25,
"path": "/AnagramCheck.py",
"repo_name": "shubhendutiwari/P_BasicLearning",
"src_encoding": "UTF-8",
"text": "\"\"\"Write a function which accepts a word and a list of words. Return the anagramsof that word from the given list\n(as a list or return empty list if not found) Like print(my_anagram(\"ant\", [\"tan\", \"stand\", \"at\"])) prints [‘tan]\"\"\"\n\nfrom collections import Counter\n\ndef anagram(ana_checks, lsts):\n ana_lst=[]\n for word in lsts:\n if Counter(ana_checks)==Counter(word):\n ana_lst.append(word)\n else:\n continue\n \n return ana_lst\n \nlst = []\n\nn=int(input(\"Enter number of element you want to enter in List : \"))\nfor i in range (0,n):\n print(\"Enter : \" +str(i+1)+ \" word\")\n word = input()\n lst.append(word)\n\nana_check=input(\"Enter the word for anagram check : \")\nprint(\"Result of anagram check : \"+str((ana_check, lst)))\n"
},
{
"alpha_fraction": 0.6305969953536987,
"alphanum_fraction": 0.64552241563797,
"avg_line_length": 23.363636016845703,
"blob_id": "3a8b474cb1db9e012e752545d3145b4ac15c1a5f",
"content_id": "8effbfc8150a69ddcebd5e9b4a79a8696c9b5041",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 268,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 11,
"path": "/StringLenFunction.py",
"repo_name": "shubhendutiwari/P_BasicLearning",
"src_encoding": "UTF-8",
"text": "\"\"\"Define your own function that computes the length of a given list or string.\"\"\"\n\ndef strLen(word):\n count = 0\n for x in word:\n count = count+1\n return count\n\nstr1 = input(\"Enter the string : \")\n\nprint(\"Size of input string is : \"+str(strLen(str1)))\n"
},
{
"alpha_fraction": 0.6808943152427673,
"alphanum_fraction": 0.6808943152427673,
"avg_line_length": 24.947368621826172,
"blob_id": "91a4cdf1c260965e5c6491cc06d4d3a32de4191c",
"content_id": "e47d3a5c9ced09055843d6f613bfdf4ecdd464fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 492,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 19,
"path": "/StringPermutation.py",
"repo_name": "shubhendutiwari/P_BasicLearning",
"src_encoding": "UTF-8",
"text": "\"\"\"\tWrite a function which accepts a string and returns a list of all possible permutations of the given string in python. \"\"\"\n\nfrom itertools import permutations\n\n\ndef allPermutations(str):\n # Get all permutations of string 'ABC'\n permList = permutations (str)\n\n # print all permutations\n for perm in list(permList):\n print(''.join (perm))\n\n # Driver program\n\n\nif __name__ == \"__main__\":\n string = input(\"Enter string for permutation : \")\n allPermutations(string)"
},
{
"alpha_fraction": 0.6092544794082642,
"alphanum_fraction": 0.637532114982605,
"avg_line_length": 24.933332443237305,
"blob_id": "05b299d5e22b291d55a0af43edc55b84f7db73e8",
"content_id": "829b69dd5acd5f749e30eac919db568960d986a3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 389,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 15,
"path": "/Reverse.py",
"repo_name": "shubhendutiwari/P_BasicLearning",
"src_encoding": "UTF-8",
"text": "\"\"\"Define a function reverse() that computes the reversal of a string. \"\"\"\n\n\ndef reverse(string1):\n print(string1)\n length = len(string1) - 1\n string2 = \"\"\n while length >= 0:\n string2 = string2 + string1[length]\n length = length - 1\n return string2\n\n\nstring = input(\"Enter the string for reversal : \")\nprint(\"Reverse for this string is : \" + reverse(string))\n"
},
{
"alpha_fraction": 0.5821325778961182,
"alphanum_fraction": 0.5936599373817444,
"avg_line_length": 22.200000762939453,
"blob_id": "04cc41d2c597352c19cf04014de052652165ed00",
"content_id": "87c85675625ccbfec023d15952af8c3eb234405f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 347,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 15,
"path": "/PerfectNumber.py",
"repo_name": "shubhendutiwari/P_BasicLearning",
"src_encoding": "UTF-8",
"text": "\"\"\"Write a python function to test, if a given number (passed as argument) is a perfect number \"\"\"\n\nval: int = int(input(\"Enter the value\"))\ns: int = 0\n\nfor x in range(1, val-1):\n if val % x == 0:\n s += x\n else:\n continue\n\nif s == val:\n print(str(val)+\" is perfect number\")\nelse:\n print(str(val)+\" is not perfect number\")"
},
{
"alpha_fraction": 0.6088840961456299,
"alphanum_fraction": 0.6164680123329163,
"avg_line_length": 23.945945739746094,
"blob_id": "66e22e05f85139a0d97936c6e5f78c7b35767289",
"content_id": "048c4362ac2db44bd198f9537fa3dc1da8c7ccb5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 923,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 37,
"path": "/ListImplementation.py",
"repo_name": "shubhendutiwari/P_BasicLearning",
"src_encoding": "UTF-8",
"text": "''' List Implementation\n def elementwise_greater_than(mylist, threshold):\n Return a list with the same length as mylist, where the value at index i is \n True if L[i] is greater than threshold, and False otherwise.\n >>> elementwise_greater_than([1, 2, 3, 4], 2)\n [False, False, True, True]\n'''\n\n\ndef elementwise_greater_than(mylist, threshold):\n\n lst_out = []\n for x in mylist:\n if x > threshold:\n lst_out.append(\"true\")\n elif x< threshold:\n lst_out.append(\"False\")\n else:\n lst_out.append(\"equal\")\n return lst_out\n\n\n\n#empty list\nlst =[]\n\n#number of element in list\nn= int(input(\"Enter the no of element : \"))\n\nfor i in range(0,n):\n print(\"Enter \"+str(i+1)+\" element\")\n ele = int(input())\n lst.append(ele)\n\nthreshold_value = int(input(\"Enter threshold_value : \"))\n\nprint(\"Output : \"+elementwise_greater_than(lst, threshold_value))\n"
}
] | 13 |
dashahe/algorithm | https://github.com/dashahe/algorithm | daad841da98ca72f41fe28d415760516feb40bc2 | d814134ee6974efae24203b670f5b6e98d60a606 | 07f654d86de4dfd3347eae3e88fc96570c60b6db | refs/heads/master | 2022-06-30T13:53:52.151624 | 2018-03-31T02:55:02 | 2018-03-31T02:55:02 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6778042912483215,
"alphanum_fraction": 0.6778042912483215,
"avg_line_length": 26.933332443237305,
"blob_id": "a13be973e20234cd4cbad8ac93ac094a4946ca02",
"content_id": "170255d238b5c96134a6bfa18434410304f9264b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 838,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 30,
"path": "/Sort_cpp/Sort.h",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <vector>\nusing namespace std;\n\ntemplate <typename T>\nclass Sort\n{\npublic:\n\tvoid selecteSort(vector<T> &vec);\n\tvoid shellSort(vector<T> &vec);\n\tvoid insertSort(vector<T> &vec);\n\tvoid mergeSort(vector<T> &vec);\n\tvoid quickSort(vector<T> &vec);\n\tvoid heapSort(vector<T> &vec);\n\tbool isSorted(vector<T> &vec);\n\nprivate:\n\tvoid mergeSort(vector<T> &vec, int lo, int hi);\n\tvoid merge(vector<T> &vec, int lo, int mi, int hi);\n\tvoid quickSortThreeWay(vector<T> &vec, int lo, int hi);\n\tvoid quickSort(vector<T> &vec, int lo, int hi);\n\tint partition(vector<T> &vec, int lo, int hi);\n\tvoid exch(vector<T> &vec, int i, int j);\n\tbool less(vector<T> &vec, int i, int j);\n\tint compare(vector<T> &vec, int i, int j);\n\tvoid sink(vector<T> &vec, int i, int n);\n\tvoid swim(vector<T> &vec, int i);\nprivate:\n\tvector<T> vecCopy;\n};\n"
},
{
"alpha_fraction": 0.495587557554245,
"alphanum_fraction": 0.4974454343318939,
"avg_line_length": 24.32941246032715,
"blob_id": "fd66189099551df28d50715520753724e39b1fd5",
"content_id": "66ef1b5855e0f3ad2c759b354be718d85f3d0b79",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2339,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 85,
"path": "/notes/LeetCode笔记.md",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "# LeetCode笔记\n\n### 查找两个节点的最低公共节点\n\n TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)\n {\n while(true)\n {\n if(root->val < p->val && root->val < q->val)\n return lowestCommonAncestor(root->right, p, q);\n else if(root->val > p->val && root->val > q->val)\n return lowestCommonAncestor(root->left, p, q);\n else\n return root;\n }\n }\n\n TreeNode* lowestCommonAncestor(TreeNode* root, TreeNode* p, TreeNode* q)\n {\n if(root == nullptr || root == q || root == p) return root;\n TreeNode* left = lowestCommonAncestor(root->right, p, q);\n TreeNode* right = lowestCommonAncestor(root->left, p, q);\n if(left && right) return root;\n if(left == nullptr) return right;\n if(right == nullptr) return left;\n }\n\n### 位操作\n\n int hammingDistance(int x, int y) {\n int cnt = 0;\n int n = x^y;\n while(n)\n {\n ++cnt;\n n &= n-1;\n }\n return cnt;\n }\n\n> 利用 n & n-1 可以得到删除最低位1后的数字\n\n \n\n### 判断链表是否回文\n\n bool isPalindrome(ListNode* head) {\n if(head == nullptr || head->next == nullptr) return true;\n if(head->next->next == nullptr) return head->next->val == head->val;\n ListNode* fast = head;\n ListNode* slow = head;\n while(fast->next != nullptr && fast->next->next != nullptr)\n {\n fast = fast->next->next;\n slow = slow->next;\n }\n \n slow->next = reverseList(slow->next);\n slow = slow->next;\n while(slow != nullptr && head != nullptr)\n {\n if(slow->val != head->val) return false;\n slow = slow->next;\n head = head->next;\n }\n return true;\n }\n \n ListNode* reverseList(ListNode* head)\n {\n ListNode* pre = nullptr;\n while(head)\n {\n ListNode* next = head->next;\n head->next = pre;\n pre = head;\n head = next;\n }\n return pre;\n }\n\n\n就是利用 fast 和 slow 两个游标,利用步长的差异找到链表的中点,一分为二,翻转其中的一个链表,然后遍历比对查看是否回文\n\n###\n"
},
{
"alpha_fraction": 0.5721231698989868,
"alphanum_fraction": 0.5769854187965393,
"avg_line_length": 14.425000190734863,
"blob_id": "a7cbca7267c2af302cfa6cff9a76e4e242fa4599",
"content_id": "da6c588c569f082b73a5714fa8469539f0ef19a0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 617,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 40,
"path": "/EdgeWeightedGraph/Kruskal.h",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include \"EdgeWeightedGraph.h\"\n#include \"../UF_cpp/weighted_union_find.h\"\n\nclass KruskalMST\n{\npublic:\n\tKruskalMST(EdgeWeightedGraph G)\n\t{\n\t\tpriority_queue<Edge> pq;\n\t\tfor(Edge e: G.edges())\n\t\t\tpq.push(e);\n\t\tweighted_union_find uf(G.V());\n\t\twhile(!pq.empty() && mst.size() < G.V()-1)\n\t\t{\n\t\t\tEdge e = pq.top();\n\t\t\tpq.pop();\n\t\t\tint v = e.either(), w = e.other(v);\n\t\t\tif(uf.connected(v, w))\n\t\t\t\tcontinue;\n\t\t\tuf._union(w, v);\n\t\t\tmst.push_back(e);\n\t\t}\n\t}\n\n\tvector<Edge> edges()\n\t{\n\t\treturn mst;\n\t}\n\n\tdouble weight()\n\t{\n\t\tdouble w = 0.0;\n\t\tfor(auto x: mst)\n\t\t\tw += x.weight();\n\t\treturn w;\n\t}\n\nprivate:\n\tvector<Edge> mst;\n};\n"
},
{
"alpha_fraction": 0.49473685026168823,
"alphanum_fraction": 0.5175438523292542,
"avg_line_length": 17.387096405029297,
"blob_id": "4b85a0a526c7f36543bd0d8b4f62864db0da3928",
"content_id": "78ea3a2e6aa84faafd11528ba68f407ecd6e7da5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 590,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 31,
"path": "/LSD/LSD.h",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <string>\n#include <algorithm>\nusing namespace std;\n\n//低位优先的字符串排序\nclass LSD\n{\npublic:\n\tvoid sort(vector<string> &vec, int W)\n\t{\n\t\tint N = vec.size();\n\t\tint R = 256;\n\n\t\tfor(int d = W-1; d >= 0; --d)\n\t\t{\n\t\t\tvector<int> count(R+1, 0);\n\t\t\tvector<string> aux(N, \"\");\n\t\t\tfor(int i = 0; i < N; ++i)\n\t\t\t\tcount[vec[i][d]+1]++;\n\t\t\tfor(int d = 0; d < R; ++d)\n\t\t\t\tcount[d+1] += count[d];\n\t\t\tfor(int i = 0; i < N; ++i)\n\t\t\t\taux[count[vec[i][d]]++] = vec[i];\n\t\t\tfor(int i = 0; i < N; ++i)\n\t\t\t\tvec[i] = aux[i];\n\t\t}\n\t}\n};\n"
},
{
"alpha_fraction": 0.5221238732337952,
"alphanum_fraction": 0.5575221180915833,
"avg_line_length": 19.08888816833496,
"blob_id": "1cf7ea742129505551c1c47824e629d23748c164",
"content_id": "9273cab66c41bdc5ea3b99685980c7896b4d1038",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 904,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 45,
"path": "/nothing/Test.java",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "import java.util.Arrays;\n\npublic class Test\n{\n\tpublic static double sqrt(double c)\n\t{\n\t\tif(c<0) return Double.NaN;\n\t\tdouble err = 1e-15;\n\t\tdouble t = c;\n\t\twhile(Math.abs(t - c/t) > err*t)\n\t\t\tt = (c/t + t) / 2.0;\n\t\treturn t;\n\t}\n\n\tpublic static int rank(int key, int[] a)\n\t{\n\t\tint lo = 0;\n\t\tint hi = a.length - 1;\n\t\twhile(lo <= hi)\n\t\t{\n\t\t\tint mid = lo + (hi - lo)/2;\n\t\t\tif(key < a[mid]) hi = mid - 1;\n\t\t\telse if(key > a[mid]) lo = mid + 1;\n\t\t\telse return mid;\n\t\t}\n\t\treturn -1;\n\t}\n\tpublic static void main(String []args)\n\t{\n\t\tint [] a = {1, 2, 1, 42};\n\t\tArrays.sort(a);\n\t//\tstdDraw.point(12,4);\n\t\tfor(int i=0; i<a.length; ++i)\n\t\t\tSystem.out.println(a[i]);\n\t\tSystem.out.println(sqrt(3780));\n\n\t\tif((args[0] == args[1])&&(args[0] == args[2]))\n\t\t\tSystem.out.println(\"equal\");\n\t\telse\n\t\t\tSystem.out.println(\"Not equal\");\n\t\tSystem.out.println(args[0]+\" \"+args[1]+\" \"+args[2]);\n\t\tSystem.out.println('b'+'c');\n\n\t}\n}\n"
},
{
"alpha_fraction": 0.5930191874504089,
"alphanum_fraction": 0.5933682322502136,
"avg_line_length": 16.363636016845703,
"blob_id": "553e38c44715add030569aef005e09894d3100a4",
"content_id": "0bfbbe1940f4836c3f4f4e8641f29afff68689c9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2865,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 165,
"path": "/BST_cpp/BST.cpp",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include \"BST.h\"\n\ntemplate <typename Key, typename Value>\nclass BST\n{\npublic:\n\tBST(): root(NULL){}\n\tvoid put(Key key, Value val)\n\t{\n\t\troot = put(root, key, val);\n\t}\n\n\tValue get(Key key)\n\t{\n\t\tTreeNode<Key, Value>* node = root;\n\t\tif(contains(key))\n\t\t\twhile(node != NULL)\n\t\t\t\tif(key < node->key)\n\t\t\t\t\tnode = node->left;\n\t\t\t\telse if(key > node->key)\n\t\t\t\t\tnode = node->right;\n\t\t\t\telse\n\t\t\t\t\treturn node->value;\n\t\telse\n\t\t\treturn static_cast<Key>(NULL);\n\t}\n\n\tvoid erase(Key key)\n\t{\n\t\troot = erase(root, key);\n\t}\n\n\tbool contains(Key key)\n\t{\n\t\tTreeNode<Key, Value>* node = root;\n\t\twhile(node != NULL)\n\t\t{\n\t\t\tif(key < node->key)\n\t\t\t\tnode = node->left;\n\t\t\telse if(key > node->key)\n\t\t\t\tnode = node->right;\n\t\t\telse\n\t\t\t\treturn true;\n\t\t}\n\t\treturn false;\n\t}\n\n\tbool isEmpty()\n\t{\n\t\treturn treeSize == 0;\n\t}\n\n\tint size()\n\t{\n\t\treturn treeSize;\n\t}\n\n\tKey min()\n\t{\n\t\tTreeNode<Key, Value>* node = root;\n\t\twhile(node->left != NULL)\n\t\t\tnode = node->left;\n\t\treturn node->key;\n\t}\n\n\tKey max()\n\t{\n\t\tTreeNode<Key, Value>* node = root;\n\t\twhile(node->right != NULL)\n\t\t\tnode = node->right;\n\t\treturn node->key;\n\t}\n\n\tvoid deleteMin()\n\t{\n\t\troot = deleteMin(root);\n\t}\n\n\tvoid deleteMax()\n\t{\n\t\troot = deleteMax(root);\n\t}\n\nprivate:\n\tTreeNode<Key, Value>* put(TreeNode<Key, Value>* node, Key key, Value value)\n\t{\n\t\tif(node == NULL)\n\t\t{\n\t\t\t++treeSize;\n\t\t\treturn new TreeNode<Key, Value>(key, value, NULL, NULL);\n\t\t}\n\t\tif(key == node->key)\n\t\t\tnode->value = value;\n\t\telse if(key < node->key)\n\t\t\tnode->left = put(node->left, key, value);\n\t\telse if(key > node->key)\n\t\t\tnode->right = put(node->right, key, value);\n\t\treturn node;\n\t}\n\n\tTreeNode<Key, Value>* erase(TreeNode<Key, Value>* node, Key key)\n\t{\n\t\tif(node == NULL)\n\t\t\treturn node;\n\t\tif(key < node->key)\n\t\t\tnode->left = erase(node->left, key);\n\t\telse if(key > node->key)\n\t\t\tnode->right = erase(node->right, key);\n\t\telse\n\t\t{\n\t\t\t--treeSize;\n\t\t\tif(node->left == NULL)\n\t\t\t\treturn node->right;\n\t\t\tif(node->right == NULL)\n\t\t\t\treturn node->left;\n\t\t\tTreeNode<Key, Value>* t = node;\n\t\t\tnode->key = min(node->right);\n\t\t\tnode->value = get(node->key);\n\t\t\tnode->right = deleteMin(t->right);\n\t\t\tnode->left = t->left;\n\t\t}\n\t\treturn node;\n\t}\n\n\tKey min(TreeNode<Key, Value>* h)\n\t{\n\t\tTreeNode<Key, Value>* node = h;\n\t\twhile(node->left != NULL)\n\t\t\tnode = node->left;\n\t\treturn node->key;\n\t}\n\n\tKey max(TreeNode<Key, Value>* h)\n\t{\n\t\tTreeNode<Key, Value>* node = h;\n\t\twhile(node->right != NULL)\n\t\t\tnode = node->right;\n\t\treturn node->key;\n\t}\n\n\tTreeNode<Key, Value>* deleteMin(TreeNode<Key, Value>* node)\n\t{\n\t\tif(node->left == NULL)\n\t\t{\n\t\t\t--treeSize;\n\t\t\treturn node->right;\n\t\t}\n\t\tnode->left = deleteMin(node->left);\n\t\treturn node;\n\t}\n\n\tTreeNode<Key, Value>* deleteMax(TreeNode<Key, Value>* node)\n\t{\n\t\tif(node->right == NULL)\n\t\t{\n\t\t\t--treeSize;\n\t\t\treturn node->left;\n\t\t}\n\t\tnode->right = deleteMax(node->right);\n\t\treturn node;\n\t}\nprivate:\n\tTreeNode<Key, Value>* root;\n\tint treeSize;\n};\n"
},
{
"alpha_fraction": 0.5146726965904236,
"alphanum_fraction": 0.544018030166626,
"avg_line_length": 17.45833396911621,
"blob_id": "f4e9b4384f43134c73031e922afb049c21103ef6",
"content_id": "ce02ddf9c0a4af2a9d9cd9b2ae0ad57dadc16fb5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 443,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 24,
"path": "/BST_cpp/main.cpp",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include \"BST.h\"\n\nint main()\n{\n\tBST<int, int> tree;\n\n\tfor(int i = 0; i != 100; ++i)\n\t\ttree.put(i, i);\n\ttree.deleteMin();\n\ttree.deleteMax();\n\tcout<<tree.min()<<\" \"<<tree.max()<<endl;\n\tcout<<tree.size()<<endl;\n\n\tfor(int i = 1; i != 90; ++i)\n\t\ttree.erase(i);\n\tcout<<tree.min()<<\" \"<<tree.max()<<endl;\n\tcout<<tree.size()<<endl;\n\n\tfor(int i = 90; i != 100; ++i)\n\t\tif(tree.get(i) != static_cast<int>(NULL))\n\t\t\tcout<<tree.get(i)<<endl;\n\n\treturn 0;\n}\n"
},
{
"alpha_fraction": 0.6536430716514587,
"alphanum_fraction": 0.6546990275382996,
"avg_line_length": 14.783333778381348,
"blob_id": "33f05bfc49327f4b691763c59ae85688a249188f",
"content_id": "3aed908f27c6045ac0e409336bbfb282c173b818",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 947,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 60,
"path": "/EdgeWeightedDigraph/EdgeWeightedDigraph.h",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <queue>\n#include <fstream>\nusing namespace std;\n\nclass DirectedEdge\n{\npublic:\n\tDirectedEdge(int v, int w, double _edgeWeight):\n\t\tbegin(v), end(w), edgeWeight(_edgeWeight){}\n\tdouble weight() { return edgeWeight; }\n\tint from() { return begin; }\n\tint to() { return end; }\n\nprivate:\n\tint begin;\n\tdouble edgeWeight;\n\tint end;\n};\n\nclass EdgeWeightedDigraph\n{\npublic:\n\tEdgeWeightedDigraph(int _v)\n\t{\n\t\tadj = vector<vector<DirectedEdge>>(_v, vector<DirectedEdge>());\n\t\tv = _v;\n\t\te = 0;\n\t}\n\n\tint V() { return v; }\n\tint E() { return e; }\n\n\tvoid addEdge(DirectedEdge de)\n\t{\n\t\tadj[de.from()].push_back(de);\n\t\t++e;\n\t}\n\n\tvector<DirectedEdge> getAdj(int v)\n\t{\n\t\treturn adj[v];\n\t}\n\n\tvector<DirectedEdge> edges()\n\t{\n\t\tvector<DirectedEdge> allEdge;\n\t\tfor(auto x: adj)\n\t\t\tfor(auto y: x)\n\t\t\t\tallEdge.push_back(y);\n\t\treturn allEdge;\n\t}\n\nprivate:\n\tvector<vector<DirectedEdge>> adj;\n\tint v;\n\tint e;\n};\n"
},
{
"alpha_fraction": 0.48864758014678955,
"alphanum_fraction": 0.499506413936615,
"avg_line_length": 18.669902801513672,
"blob_id": "abdedabe1c33bc459eb70770ed2e5d0be3ab1b66",
"content_id": "1352821cefe02c69996804f49ec469cc185dc8ed",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2026,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 103,
"path": "/Sort_cpp/countReverse.cpp",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <algorithm>\n#define SIZE 10000\nusing namespace std;\n\nint countReverse(vector<int>& vec);\nint countReverse(vector<int>& vec, int lo, int hi);\nint count(vector<int>& vec, int lo, int mid, int hi);\nvoid insertSort(vector<int>& vec, int lo, int hi);\n\nint ans = 0;\n\nint main()\n{\n ifstream in(\"random.txt\");\n\n vector<int> vec;\n int num;\n\n while(in >> num)\n vec.push_back(num);\n\n vector<int> vecTwo(vec);\n insertSort(vecTwo, 0, vec.size()-1);\n\n cout << \"MY ANSWER: \" << countReverse(vec) << endl;\n cout << \"TRUE ANSWER: \" << ans << endl;\n\n return 0;\n}\n\nint countReverse(vector<int>& vec)\n{\n return countReverse(vec, 0, vec.size()-1);\n}\n\nint countReverse(vector<int>& vec, int lo, int hi)\n{\n if(lo < hi)\n {\n int mid = lo + (hi-lo)/2;\n int pre = countReverse(vec, lo, mid);\n int post = countReverse(vec, mid+1, hi);\n return pre + post + count(vec, lo, mid, hi);\n }\n return 0;\n}\n\n/****** buggy ******/\n\nint count(vector<int>& vec, int lo, int mid, int hi)\n{\n vector<int> vecCopy;\n for(int i = lo; i <= hi; ++i)\n vecCopy.push_back(vec[i]);\n\n int i = lo, j = mid+1, cnt = 0;\n bool counted = false;\n\n for(int k = lo; k <= hi; ++k)\n {\n if(counted == false && vecCopy[i-lo] > vecCopy[j-lo])\n {\n cnt += hi-i+1;\n counted = true;\n }\n if(vecCopy[i-lo] <= vecCopy[j-lo])\n {\n vec[k] = vecCopy[i-lo];\n ++i;\n }\n else\n {\n vec[k] = vecCopy[j-lo];\n ++j;\n counted = false;\n }\n }\n return cnt;\n}\n\n/*** count reverse by insertSort***/\n\nvoid exchange(int &a, int &b)\n{\n ++ans;\n auto x = a;\n a = b;\n b = x;\n}\n\nvoid insertSort(vector<int>& vec, int lo, int hi)\n{\n for(int i = lo+1; i != hi+1; ++i)\n {\n for(int j = i; j > 0 && vec[j] < vec[j-1]; --j)\n {\n exchange(vec[j], vec[j-1]);\n }\n }\n}\n"
},
{
"alpha_fraction": 0.6655405163764954,
"alphanum_fraction": 0.6655405163764954,
"avg_line_length": 15.44444465637207,
"blob_id": "3a90e5d1731ff3b3d795bb4f98d12231fcdb8a51",
"content_id": "4d4607a3f18df4603d9e544324d7ec765596a5b3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 296,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 18,
"path": "/Sort_cpp/Shell.h",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <vector>\nusing namespace std;\n\ntemplate <typename T>\nclass Shell\n{\npublic:\n\tShell(vector<T> &_vec): vec(_vec){}\n\tvoid sort();\n\tvoid sort(vector<T> &vec);\n\tbool isSorted(vector<T> &vec);\nprivate:\n\tvoid exch(vector<T>& vec, int i, int j);\n\nprivate:\n\tvector<T> &vec;\n};\n"
},
{
"alpha_fraction": 0.626928448677063,
"alphanum_fraction": 0.6297335028648376,
"avg_line_length": 20.606060028076172,
"blob_id": "139b96df3201f1e121b074e5538650fe619a9d3d",
"content_id": "43e4e7f6a423d5a65727a15627367dfad0a32b37",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 713,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 33,
"path": "/StringSearchTree/main.cpp",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include \"StringST.h\"\n\nint main()\n{\n\tifstream in(\"words.txt\");\n\tStringST strTree;\n\n\tstring str;\n\twhile(in >> str)\n\t\tstrTree.put(str, str.size());\n\n\tif(strTree.contains(\"surely\"))\n\t\tcout << strTree.get(\"surely\") << endl;\n\tcout << strTree.size() << endl;\n\n\tcout << strTree.keysWithPrefix(\"a\").size() << endl;\n\tfor(auto x: strTree.keysWithPrefix(\"\"))\n\t\tcout << x << endl;\n\n\tfor(auto x: strTree.keysThatMatch(\".;\"))\n\t\tcout << x << endl;\n\n\tcout << \"Test of longestPrefixOf:\" << endl;\n\tcout << strTree.longestPrefixOf(\"youArePig\") << endl;\n\n\tfor(auto x: strTree.keysThatMatch(\".\"))\n\t\tstrTree.deleteKey(x);\n\n\tcout << \"After delete 1 length words:\" << endl;\n\tfor(auto x: strTree.keys())\n\t\tcout << x << endl;\n\treturn 0;\n}\n"
},
{
"alpha_fraction": 0.5423189401626587,
"alphanum_fraction": 0.5563809871673584,
"avg_line_length": 16.862558364868164,
"blob_id": "c6f40f8e934b201c8936ef44a2a6d8d6e02526b0",
"content_id": "0be3fbab13fcc0e9f669f98c7742092ff26a0d94",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3809,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 211,
"path": "/Sort_cpp/Sort.cpp",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include \"Sort.h\"\ntemplate <typename T>\nvoid Sort<T>::selecteSort(vector<T> &vec)\n{\n\tint n = vec.size();\n\tfor(int i = 0; i < n-1; ++i)\n\t\tfor(int j = i+1; j < n; ++j)\n\t\t\tif(less(vec, j, i))\n\t\t\t\texch(vec, i, j);\n}\n\n//vector<T>\ntemplate <typename T>\nvoid Sort<T>::shellSort(vector<T> &vec)\n{\n\tint n = vec.size();\n\tint h = 1;\n\twhile(h < n/3)\n\t\th = 3*h + 1;\n\twhile(h >= 1)\n\t{\n\t\tfor(int i = h; i < n; ++i)\n\t\t\tfor(int j = i; j >= h && less(vec, j, j-h); j-=h)\n\t\t\t\texch(vec, j, j-h);\n\t\th /= 3;\n\t}\n}\n\ntemplate <typename T>\nvoid Sort<T>::insertSort(vector<T> &vec)\n{\n\tint n = vec.size();\n\tfor(int i = 1; i < n; ++i)\n\t\tfor(int j = i; j > 0 && less(vec, j, j-1); --j)\n\t\t\texch(vec, j, j-1);\n}\n\ntemplate <typename T>\nvoid Sort<T>::mergeSort(vector<T> &vec)\n{\n\tauto begin = vec.begin();\n\twhile(begin != vec.end())\n\t\tvecCopy.push_back(*begin++);\n\tmergeSort(vec, 0, vec.size()-1);\n}\n\ntemplate <typename T>\nvoid Sort<T>::mergeSort(vector<T>& vec, int lo, int hi)\n{\n\tif(lo < hi)\n\t{\n\t\tint mid = lo + (hi- lo)/2;\n\t\tmergeSort(vec, lo, mid);\n\t\tmergeSort(vec, mid+1, hi);\n\t\tif(!less(vec, mid, mid+1)) //跳过有序数组的merge\n\t\t\tmerge(vec, lo, mid, hi);\n\t}\n}\n\ntemplate <typename T>\nvoid Sort<T>::merge(vector<T> &vec, int lo, int mid, int hi)\n{\n\tint i = lo;\n\tint j = mid+1;\n\n\tfor(int k = lo; k <= hi; ++k)\n\t\tvecCopy[k] = vec[k];\n\tfor(int k = lo; k <= hi; ++k)\n\t\tif(i > mid)\n\t\t\tvec[k] = vecCopy[j++];\n\t\telse if(j > hi)\n\t\t\tvec[k] = vecCopy[i++];\n\t\telse if(less(vecCopy, i, j))\n\t\t\tvec[k] = vecCopy[i++];\n\t\telse\n\t\t\tvec[k] = vecCopy[j++];\n}\n\ntemplate <typename T>\nvoid Sort<T>::quickSort(vector<T> &vec)\n{\n\t//quickSort(vec, 0, vec.size()-1);\n\tquickSortThreeWay(vec, 0, vec.size()-1);\n}\n\ntemplate <typename T>\nvoid Sort<T>::quickSort(vector<T> &vec, int lo, int hi)\n{\n\tif(lo >= hi)\n\t\treturn;\n\tif(lo >= hi - 10)\n\t{\n\t\tinsertSort(vec);\n\t\treturn;\n\t}\n\tint j = partition(vec, lo, hi);\n\tquickSort(vec, lo, j-1);\n\tquickSort(vec, j+1, hi);\n}\n\ntemplate <typename T>\nint Sort<T>::partition(vector<T> &vec, int lo, int hi)\n{\n\tint i = lo, j = hi+1;\n\tT v = vec[lo];\n\twhile(true)\n\t{\n\t\twhile(less(vec, ++i, lo))\n\t\t\tif(i == hi) break;\n\t\twhile(less(vec, lo, --j))\n\t\t\tif(j == lo) break;\n\t\tif(i >= j) \tbreak;\n\t\texch(vec, i, j);\n\t}\n\texch(vec, lo, j);\n\treturn j;\n}\n\n/*优化quicksort,对重复元素的处理更快*/\ntemplate <typename T>\nvoid Sort<T>::quickSortThreeWay(vector<T> &vec, int lo, int hi)\n{\n\tif(lo >= hi) return;\n\tint lt = lo, i = lo+1, gt = hi;\n\tT v = vec[lo];\n\twhile(i <= gt)\n\t{\n\t\tif(vec[i] < v)\n\t\t\texch(vec, i++, lt++);\n\t\telse if(vec[i] > v)\n\t\t\texch(vec, i, gt--);\n\t\telse\n\t\t\ti++;\n\t}\n\tquickSortThreeWay(vec, lo, lt-1);\n\tquickSortThreeWay(vec, gt+1, hi);\n}\n\ntemplate <typename T>\nvoid Sort<T>::heapSort(vector<T> &vec)\n{\n\tint n = vec.size();\n\tfor(int i = n/2; i >= 0; --i)\n\t\tsink(vec, i, n);\n\tfor(int i = n-1; i > 0; --i)\n\t{\n\t\texch(vec, 0, i);\n\t\tsink(vec, 0, i-1);\n\t}\n}\n\ntemplate <typename T>\nbool Sort<T>::isSorted(vector<T> &vec)\n{\n\tfor(int i = 0; i < vec.size()-1; ++i)\n\t\tif(less(vec, i+1, i))\n\t\t\treturn false;\n\treturn true;\n}\n\n\n//private functions\ntemplate <typename T>\nvoid Sort<T>::exch(vector<T> &vec, int i, int j)\n{\n\tT tmp = vec[i];\n\tvec[i] = vec[j];\n\tvec[j] = tmp;\n}\n\ntemplate <typename T>\nbool Sort<T>::less(vector<T> &vec, int i, int j)\n{\n\treturn vec[i] < vec[j];\n}\n\ntemplate <typename T>\nint Sort<T>::compare(vector<T> &vec, int i, int j)\n{\n\tif(vec[i] < vec[j])\n\t\treturn -1;\n\telse if(vec[i] > vec[j])\n\t\treturn 1;\n\telse\n\t\treturn 0;\n}\n\ntemplate <typename T>\nvoid Sort<T>::sink(vector<T> &vec, int i, int n)\n{\n\twhile(2*i < n)\n\t{\n\t\tint child = 2*i + 1;\n\t\tif(child+1 < n && less(vec, child, child+1))\n\t\t\t++child;\n\t\tif(!less(vec, i, child))\n\t\t\tbreak;\n\t\texch(vec, child, i);\n\t\ti = child;\n\t}\n}\n\ntemplate <typename T>\nvoid Sort<T>::swim(vector<T> &vec, int i)\n{\n\twhile(less(vec, i/2, i) && i > 0)\n\t{\n\t\texch(vec, i, i/2);\n\t\ti /= 2;\n\t}\n}\n"
},
{
"alpha_fraction": 0.5980392098426819,
"alphanum_fraction": 0.6274510025978088,
"avg_line_length": 11.239999771118164,
"blob_id": "1b284115cc91869c009da1857dc1ab0cc3ed990e",
"content_id": "7561cb47925b707af27e748739f59df4b044680b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 306,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 25,
"path": "/nothing/JudgeBigEndian.cpp",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include <iostream>\nusing namespace std;\n\nunion u\n{\n\tshort int a;\n\tchar b;\n};\n\nbool isBigEndian()\n{\n\tunion u un;\n\tun.a = 0x1122;\n\treturn un.b == 0x11;\n}\n\nint main()\n{\n\tif(isBigEndian())\n\t\tcout << \"This computer is big endian\" << endl;\n\telse\n\t\tcout << \"This computer is small endian\" << endl;\n\n\treturn 0;\n}\n"
},
{
"alpha_fraction": 0.6875,
"alphanum_fraction": 0.7067307829856873,
"avg_line_length": 18,
"blob_id": "9175d01c1165aff23d1bdffc16a9f7589c95e987",
"content_id": "f1674bd3372d609a14e983970556100aaa4194c9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "CMake",
"length_bytes": 208,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 11,
"path": "/Digraph/CMakeLists.txt",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "cmake_minimum_required(VERSION 3.3)\nproject(Digraph)\n\nset(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -std=c++11\")\n\nset(SOURCE_FILES\n Digraph.h\n main.cpp\n tinyDG.txt)\n\nadd_executable(Digraph ${SOURCE_FILES})"
},
{
"alpha_fraction": 0.6115261316299438,
"alphanum_fraction": 0.6136606335639954,
"avg_line_length": 13.640625,
"blob_id": "a4d07aa9b4e9994214bbe35f10fc2816697266dd",
"content_id": "2515b8f811c955e7436913e4a9f1f6e6def5d96f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 937,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 64,
"path": "/UF_cpp/weighted_union_find.h",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include <vector>\nusing namespace std;\n\nclass weighted_union_find\n{\npublic:\n\tweighted_union_find(int n);\n\tvoid _union(int p, int q);\n\tint find(int p);\n\tbool connected(int p, int q);\n\tint count();\n\nprivate:\n\tvector<int> vec;\n\tvector<int> size;\n\tint area_count;\n};\n\nweighted_union_find::weighted_union_find(int n)\n{\n\tfor(int i = 0; i < n; ++i)\n\t{\n\t\tvec.push_back(i);\n\t\tsize.push_back(1);\n\t}\n\tarea_count = n;\n}\n\nvoid weighted_union_find::_union(int p, int q)\n{\n\tint proot = find(p);\n\tint qroot = find(q);\n\tif(proot != qroot)\n\t{\n\t\tif(size[proot] > size[qroot])\n\t\t{\n\t\t\tvec[qroot] = proot;\n\t\t\tsize[proot] += size[qroot];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvec[proot] = qroot;\n\t\t\tsize[qroot] += size[proot];\n\t\t}\n\t\t--area_count;\n\t}\n}\n\nint weighted_union_find::find(int p)\n{\n\twhile(vec[p] != p)\n\t\tp = vec[p];\n\treturn p;\n}\n\nbool weighted_union_find::connected(int p, int q)\n{\n\treturn find(p) == find(q);\n}\n\nint weighted_union_find::count()\n{\n\treturn area_count;\n}\n"
},
{
"alpha_fraction": 0.510769248008728,
"alphanum_fraction": 0.5246154069900513,
"avg_line_length": 14.116278648376465,
"blob_id": "8321a056a6d65b9411545e43189a9fe5d137e301",
"content_id": "443501e913d2f345bb38cd901352f54d3ba3d00d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 650,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 43,
"path": "/Sort_cpp/Shell.cpp",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include \"Shell.h\"\n\ntemplate <typename T>\nvoid Shell<T>::sort()\n{\n\tint N = vec.size();\n\tint h = 1;\n\twhile(h < N/3)\n\t\th = 3*h + 1;\n\twhile(h >= 1)\n\t{\n\t\tfor(int i = h; i < N; ++i)\n\t\t{\n\t\t\tfor(int j = i; j >= h && vec[j] < vec[j-h]; j-=h)\n\t\t\t\texch(vec, j, j-h);\n\t\t}\n\t\th /= 3;\n\t}\n}\n\ntemplate <typename T>\nvoid Shell<T>::sort(vector<T> &_vec)\n{\n\tvec = _vec;\n\tsort();\n}\n\ntemplate <typename T>\nbool Shell<T>::isSorted(vector<T>& vec)\n{\n\tfor(int i = 0; i < vec.size()-1; ++i)\n\t\tif(vec[i] > vec[i+1])\n\t\t\treturn false;\n\treturn true;\n}\n\ntemplate <typename T>\nvoid Shell<T>::exch(vector<T> &vec, int i, int j)\n{\n\tT tmp = vec[i];\n\tvec[i] = vec[j];\n\tvec[j] = tmp;\n}\n"
},
{
"alpha_fraction": 0.38764044642448425,
"alphanum_fraction": 0.39513108134269714,
"avg_line_length": 16.83333396911621,
"blob_id": "fb03ac91eb889c1043afb786ad94d8032b8eb826",
"content_id": "d71fbb6d6eff22303604f934720756a90d246515",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 534,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 30,
"path": "/StringPattern/brute_force.h",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include <vector>\n#include <string>\n\nusing std::vector;\nusing std::string;\n\nclass BruteForce {\npublic:\n BruteForce (string _pat):\n pat(_pat) { }\n\n int search(const string &txt) {\n int i = 0, j = 0;\n int m = pat.size();\n int n = txt.size();\n\n while (i < n - m && j < m) {\n for (j = 0; txt[i+j] == pat[j++]; ) {\n if (j == m) {\n return i;\n }\n }\n ++i;\n }\n return -1;\n }\n\nprivate:\n string pat;\n};"
},
{
"alpha_fraction": 0.4938271641731262,
"alphanum_fraction": 0.5075445771217346,
"avg_line_length": 13.877551078796387,
"blob_id": "76b604aec1cd156ad580a196c74c3f635e64dea4",
"content_id": "60c2bc90e117dbe8ecbb8d5b470b29ff539180f0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 729,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 49,
"path": "/MSD/Quick3string.h",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include \"MSD.h\"\n\nclass Quick3string\n{\npublic:\n\tvoid sort(vector<string> &vec)\n\t{\n\t\tsort(vec, 0, vec.size()-1, 0);\n\t}\n\nprivate:\n\tint charAt(string s, int d)\n\t{\n\t\tif(d < s.size())\n\t\t\treturn s[d];\n\t\telse\n\t\t\treturn -1;\n\t}\n\n\tvoid sort(vector<string> &vec, int lo, int hi, int d)\n\t{\n\t\tif(hi <= lo) return;\n\t\tint lt = lo, gt = hi, mi = lo+1;\n\t\tint v = charAt(vec[lo], d);\n\n\t\twhile(mi <= gt)\n\t\t{\n\t\t\tint t = charAt(vec[mi], d);\n\t\t\tif(t < v)\n\t\t\t\texch(vec, mi++, lt++);\n\t\t\telse if(t > v)\n\t\t\t\texch(vec, mi, gt--);\n\t\t\telse\n\t\t\t\t++mi;\n\t\t}\n\n\t\tsort(vec, lo, lt-1, d);\n\t\tif(v >= 0)\n\t\t\tsort(vec, lt, gt, d+1);\n\t\tsort(vec, gt+1, hi, d);\n\t}\n\n\tvoid exch(vector<string> &vec, int a, int b)\n\t{\n\t\tauto x = vec[a];\n\t\tvec[a] = vec[b];\n\t\tvec[b] = x;\n\t}\n};\n"
},
{
"alpha_fraction": 0.5332555174827576,
"alphanum_fraction": 0.5484247207641602,
"avg_line_length": 19.404762268066406,
"blob_id": "6a52d23788e103f4ddfc31a1af05c04c107a24df",
"content_id": "ed518a7bbae2a344e03eefa98b009680dde90dc9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 857,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 42,
"path": "/EdgeWeightedDigraph/main.cpp",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include \"ShortestPath.h\"\n\nint main()\n{\n\tifstream in(\"tinyEWD.txt\");\n\tint graphSize;\n\tin >> graphSize;\n\n\tEdgeWeightedDigraph G(graphSize);\n\tint v, w;\n\tdouble weight;\n\twhile(in >> v >> w >> weight)\n\t\tG.addEdge(DirectedEdge(v, w, weight));\n\tcout << G.V() << \" \" << G.E() << endl;\n\n\tDijkstraSP DPS(G, 0);\n\tfor(int i = 0; i < G.V(); ++i)\n\t{\n\t\tcout << 0 << \" to \" << i;\n\t\tprintf(\"(%4.2f) \", DPS.getDistTo(i));\n\n\t\tvector<DirectedEdge> edges = DPS.pathTo(i);\n\t\tfor(DirectedEdge e: edges)\n\t\t\tprintf(\" %d->%d %.2lf \", e.from(), e.to(), e.weight());\n\t\tcout << endl;\n\t}\n\n\n\tAcyclicSP AS(G, 0);\n\tfor(int i = 0; i < G.V(); ++i)\n\t{\n\t\tcout << 0 << \" to \" << i;\n\t\tprintf(\"(%4.2f) \", AS.getDistTo(i));\n\n\t\tvector<DirectedEdge> edgesTwo = AS.pathTo(i);\n\t\tfor(DirectedEdge e: edgesTwo)\n\t\t\tprintf(\" %d->%d %.2lf \", e.from(), e.to(), e.weight());\n\t\tcout << endl;\n\t}\n\n\treturn 0;\n}\n"
},
{
"alpha_fraction": 0.8035714030265808,
"alphanum_fraction": 0.8214285969734192,
"avg_line_length": 27,
"blob_id": "6420c1f84d8e636f906c1eca975e77ce1a33b5b8",
"content_id": "44c53b6990c8ac27a5244c4e182f1f274372e4ff",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 56,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 2,
"path": "/notes/README.md",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "# AlgorithmCode\nthese are codes of Algorithms-4 edition\n"
},
{
"alpha_fraction": 0.5891324877738953,
"alphanum_fraction": 0.5919923782348633,
"avg_line_length": 13.77464771270752,
"blob_id": "5ac590482cc76a3715b891f9dedd9d2a1cc0b051",
"content_id": "4c64fb6bdab1211c13b0ff22927ef253ad9cd50b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2098,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 142,
"path": "/EdgeWeightedGraph/EdgeWeightedGraph.h",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <vector>\n#include <fstream>\n#include <algorithm>\n#include <string>\n#include <queue>\nusing namespace std;\n\n\nclass Edge\n{\n\tfriend bool operator<(Edge a, Edge b);\npublic:\n\tEdge(int _v, int _w, double _weight):\n\tv(_v), w(_w), edgeWeight(_weight){}\n\n\tdouble weight() { return edgeWeight; }\n\tint either() { return v; }\n\n\tint other(int _v)\n\t{\n\t\tif(v == _v)\n\t\t\treturn w;\n\t\telse if(w == _v)\n\t\t\treturn v;\n\t\telse\n\t\t\tthrow runtime_error(\"Inconsistent edge\");\n\t}\n\n\tint compareTo(Edge that)\n\t{\n\t\tif(edgeWeight < that.weight())\n\t\t\treturn -1;\n\t\telse if(edgeWeight > that.weight())\n\t\t\treturn 1;\n\t\telse\n\t\t\treturn 0;\n\t}\nprivate:\n\tint v;\n\tint w;\n\tdouble edgeWeight;\n};\n\nbool operator<(Edge a, Edge b)\n{\n\tif(a.weight() < b.weight())\n\t\treturn true;\n\telse\n\t\treturn false;\n}\n\nclass EdgeWeightedGraph\n{\npublic:\n\tEdgeWeightedGraph(int _v)\n\t{\n\t\tv = _v;\n\t\te = 0;\n\t\tadj = vector<vector<Edge>>(_v, vector<Edge>());\n\t}\n\n\tvoid addEdge(Edge edge)\n\t{\n\t\tint v = edge.either();\n\t\tint w = edge.other(v);\n\t\tadj[v].push_back(edge);\n\t\tadj[w].push_back(edge);\n\t\t++e;\n\t}\n\n\tvector<Edge> edges()\n\t{\n\t\tvector<Edge> allEdge;\n\t\tfor(int i = 0; i < v; ++i)\n\t\t\tfor(Edge x: adj[i])\n\t\t\t\tif(x.other(i) > i)\n\t\t\t\t\tallEdge.push_back(x);\n\t\treturn allEdge;\n\t}\n\n\tint V(){ return v; }\n\tint E(){ return e; }\n\tvector<Edge> getAdj(int v) { return adj[v]; }\n\nprivate:\n\tvector<vector<Edge>> adj;\n\tint v;\n\tint e;\n};\n\nclass LazyPrimMST\n{\npublic:\n\tLazyPrimMST(EdgeWeightedGraph G)\n\t{\n\t\tmarked = vector<bool>(G.V(), false);\n\t\tvisit(G, 0);\n\t\twhile(!pq.empty())\n\t\t{\n\t\t\tEdge e = pq.top();\n\t\t\tpq.pop();\n\n\t\t\tint v = e.either(), w = e.other(v);\n\t\t\tif(marked[v] && marked[w])\n\t\t\t\tcontinue;\n\t\t\tmst.push_back(e);\n\t\t\tif(!marked[v])\n\t\t\t\tvisit(G, v);\n\t\t\tif(!marked[w])\n\t\t\t\tvisit(G, w);\n\n\t\t}\n\t}\n\n\tvector<Edge> edges()\n\t{\n\t\treturn mst;\n\t}\n\n\tdouble weight()\n\t{\n\t\tdouble w;\n\t\tfor(auto x: mst)\n\t\t\tw += x.weight();\n\t\treturn w;\n\t}\n\nprivate:\n\tvoid visit(EdgeWeightedGraph G, int v)\n\t{\n\t\tmarked[v] = true;\n\t\tfor(auto x: G.getAdj(v))\n\t\t\tif(!marked[x.other(v)])\n\t\t\t\tpq.push(x);\n\t}\n\nprivate:\n\tvector<Edge> mst;\n\tpriority_queue<Edge> pq;\n\tvector<bool> marked;\n};\n"
},
{
"alpha_fraction": 0.6000000238418579,
"alphanum_fraction": 0.613043487071991,
"avg_line_length": 11.105262756347656,
"blob_id": "ae74c7efd1aaa31879311062a7cc13340d665f2a",
"content_id": "214e02f9a23735df2c17698205d3adc351f8b069",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 230,
"license_type": "no_license",
"max_line_length": 27,
"num_lines": 19,
"path": "/LSD/main.cpp",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include \"LSD.h\"\n\nint main()\n{\n\tifstream in(\"words3.txt\");\n\tstring str;\n\tvector<string> strVec;\n\twhile(in >> str)\n\t\tstrVec.push_back(str);\n\n\tLSD lsd;\n\n\tlsd.sort(strVec, 3);\n\n\tfor(auto x: strVec)\n\t\tcout << x << endl;\n\n\treturn 0;\n}\n"
},
{
"alpha_fraction": 0.5564572811126709,
"alphanum_fraction": 0.5642201900482178,
"avg_line_length": 16.280487060546875,
"blob_id": "52247b080d1325a1d3ea7444338c7d5843ec9390",
"content_id": "51be4f75bba70cb539d953dcd4ccd6749ff0e791",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2846,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 164,
"path": "/StringSearchTree/StringST.h",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <vector>\n#include <fstream>\n#include <string>\n#include <algorithm>\n#include <limits.h>\nusing namespace std;\n\nconst int null = INT_MAX;\nconst int R = 256;\n\nclass Node\n{\npublic:\n\tNode(): val(null), next(vector<Node*>(R, NULL)){}\npublic:\n\tint val;\n\tvector<Node*> next;\n};\n\nclass StringST\n{\npublic:\n\tStringST(){ root = new Node(); }\n\npublic:\n\tint size() { return size(root); }\n\tbool contains(string key) { return get(root, key, 0) != NULL; }\n\tbool isEmpty() { return size(root) == 0; }\n\n\tstring longestPrefixOf(string s)\n\t{\n\t\tint length = search(root, s, 0, 0);\n\t\treturn string(s, 0, length);\n\t}\n\n\tvector<string> keysWithPrefix(string pre)\n\t{\n\t\tvector<string> vec;\n\t\tcollect(get(root, pre, 0), pre, vec);\n\t\treturn vec;\n\t}\n\n\tvector<string> keysThatMatch(string pat) // '.'代表任意字符\n\t{\n\t\tvector<string> vec;\n\t\tcollect(root, \"\", pat, vec);\n\t\treturn vec;\n\t}\n\n\tvector<string> keys()\n\t{\n\t\treturn keysWithPrefix(\"\");\n\t}\n\n\tint get(string key)\n\t{\n\t\tNode *x = get(root, key, 0);\n\t\tif(x == NULL)\n\t\t\treturn null;\n\t\treturn x->val;\n\t}\n\n\tvoid put(string key, int val)\n\t{\n\t\troot = put(root, key, val, 0);\n\t}\n\n\tvoid deleteKey(string key)\n\t{\n\t\troot = deleteKey(root, key, 0);\n\t}\n\nprivate:\n\tNode* get(Node* x, string key, int d)\n\t{\n\t\tif(x == NULL)\n\t\t\treturn NULL;\n\t\telse if(key.size() == d)\n\t\t\treturn x;\n\t\treturn get(x->next[key[d]], key, d+1);\n\t}\n\n\tNode* put(Node* x, string key, int val, int d)\n\t{\n\t\tif(x == NULL)\n\t\t\tx = new Node();\n\t\tif(d == key.size())\n\t\t{\n\t\t\tx->val = val;\n\t\t\treturn x;\n\t\t}\n\t\tx->next[key[d]] = put(x->next[key[d]], key, val, d+1);\n\t\treturn x;\n\t}\n\n\tint size(Node* x)\n\t{\n\t\tif(x == NULL)\n\t\t\treturn 0;\n\t\tint cnt = 0;\n\t\tif(x->val != null)\n\t\t\t++cnt;\n\t\tfor(int c = 0; c < R; ++c)\n\t\t\tcnt += size(x->next[c]);\n\t\treturn cnt;\n\t}\n\n\tNode* deleteKey(Node* x, string key, int d)\n\t{\n\t\tif(x == NULL)\n\t\t\treturn NULL;\n\t\tif(d == key.size())\n\t\t\tx->val = null;\n\t\telse\n\t\t\tx->next[key[d]] = deleteKey(x->next[key[d]], key, d+1);\n\n\t\tif(x->val != null)\n\t\t\treturn x;\n\t\tfor(int c = 0; c < R; ++c)\n\t\t\tif(x->next[c] != NULL)\n\t\t\t\treturn x;\n\t\treturn NULL;\n\t}\n\n\tvoid collect(Node* x, string pre, vector<string>& vec)\n\t{\n\t\tif(x == NULL)\n\t\t\treturn;\n\t\tif(x->val != null)\n\t\t\tvec.push_back(pre);\n\t\tfor(int c = 0; c < R; ++c)\n\t\t\tcollect(x->next[c], pre + char(c), vec);\n\t}\n\n\tvoid collect(Node* x, string pre, string pat, vector<string>& vec)\n\t{\n\t\tint d = pre.size();\n\t\tif(x == NULL)\n\t\t\treturn;\n\t\tif(d == pat.size() && x->val != null)\n\t\t\tvec.push_back(pre);\n\t\tif(d == pat.size())\n\t\t\treturn;\n\n\t\tfor(int i = 0; i < R; ++i)\n\t\t\tif(pat[d] == '.' || pat[d] == i)\n\t\t\t\tcollect(x->next[i], pre + char(i), pat, vec);\n\t}\n\n\tint search(Node* x, string s, int d, int length)\n\t{\n\t\tif(x == NULL)\n\t\t\treturn length;\n\t\tif(x->val != null)\n\t\t\tlength = d;\n\t\tif(d == s.size())\n\t\t\treturn length;\n\t\treturn search(x->next[s[d]], s, d+1, length);\n\t}\n\t\nprivate:\n\tNode *root;\n};\n"
},
{
"alpha_fraction": 0.5339967012405396,
"alphanum_fraction": 0.5389717817306519,
"avg_line_length": 12.862069129943848,
"blob_id": "96139146b49a2953664b2afb3cddc84265f8c5d7",
"content_id": "77a6c48344d020374a96ba8a017ee4e6dee65d8f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1220,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 87,
"path": "/UF_cpp/union_find.h",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "//\n// Created by xvvx on 17-7-19.\n//\n\n\n#ifndef TREE_JAVA_UNION_FIND_H\n#define TREE_JAVA_UNION_FIND_H\n\n#include <vector>\nusing namespace std;\n\n// quick_find and quick_union\n\nclass union_find\n{\npublic:\n union_find(int N);\n void _union(int p, int q);\n int find(int p);\n bool connected(int p, int q);\n int count();\n\nprivate:\n vector<int> vec;\n int _count; //连通分量的数量\n};\n\nunion_find::union_find(int N)\n{\n for(int i = 0; i < N; ++i)\n vec.push_back(i);\n\t_count = N;\n}\n\n// quick_find\n\nvoid union_find::_union(int p, int q)\n{\n if(find(p) != find(q))\n {\n int p_num = vec[p], q_num = vec[q];\n for(auto &x: vec)\n {\n if(x == p_num)\n x = q_num;\n }\n --_count;\n }\n}\n\nint union_find::find(int p)\n{\n return vec[p];\n}\n/*\n// quick_union\nvoid union_find::_union(int p, int q)\n{\n\tint proot = find(p);\n\tint qroot = find(q);\n\tif(proot != qroot)\n\t{\n\t\tvec[proot] = qroot;\n\t\t--_count;\n\t}\n}\n\nint union_find::find(int p)\n{\n\twhile(vec[p] != p)\n\t\tp = vec[p];\n\treturn p;\n}\n*/\nbool union_find::connected(int p, int q)\n{\n return find(p) == find(q);\n}\n\nint union_find::count()\n{\n return _count;\n}\n\n\n\n#endif //TREE_JAVA_UNION_FIND_H\n"
},
{
"alpha_fraction": 0.5685387253761292,
"alphanum_fraction": 0.5733298063278198,
"avg_line_length": 17.32682991027832,
"blob_id": "9c88f347ca2224a3c6bbedfb905cc0b2073daed7",
"content_id": "faae2801086d96b4989fa8d4c6aa9a4475030b77",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3961,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 205,
"path": "/EdgeWeightedDigraph/ShortestPath.h",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include \"EdgeWeightedDigraph.h\"\n#include <float.h>\n\nclass IndexPQ\n{\npublic:\n\tIndexPQ() { count = 0; }\n\tIndexPQ(int v)\n\t{\n\t\tvec = vector<double>(v, DBL_MAX);\n\t\tcount = 0;\n\t}\n\n\tbool empty() { return count == 0; }\n\n\tint delMin()\n\t{\n\t\tint del = 0;\n\t\tdouble min = vec[0];\n\t\tfor(int i = 0; i < vec.size(); ++i)\n\t\t{\n\t\t\tif(vec[i] < min)\n\t\t\t\tdel = i;\n\t\t}\n\t\tvec[del] = DBL_MAX;\n\t\t--count;\n\t\treturn del;\n\t}\n\n\tvoid insert(int pos, double val)\n\t{\n\t\t++count;\n\t\tvec[pos] = val;\n\t}\n\n\tvoid change(int pos, double val) { vec[pos] = val; }\n\tbool contains(int i) { return vec[i] != DBL_MAX; }\n\nprivate:\n\tvector<double> vec;\n\tint count;\n};\n\n/******************Dijkstra********************\n/* 从最起点开始,每次都对队列中最小的那个边进行放松,\n/* relax(), 根据归纳法,局部最优保证了整体最优\n**********************************************/\nclass DijkstraSP\n{\npublic:\n\tDijkstraSP(EdgeWeightedDigraph G, int _s)\n\t{\n\t\ts = _s;\n\t\tedgeTo = vector<DirectedEdge>(G.V(), DirectedEdge(0, 0, 0));\n\t\tdistTo = vector<double>(G.V(), DBL_MAX);\n\t\tdistTo[s] = 0;\n\t\tpq = IndexPQ(G.V());\n\t\tmarked = vector<bool>(G.V(), false);\n\n\t\tpq.insert(s, 0.0);\n\t\twhile(!pq.empty())\n\t\t\trelax(G, pq.delMin());\n\t}\n\n\tdouble getDistTo(int v) { return distTo[v]; }\n\tbool hasPathTo(int v) { return marked[v]; }\n\n\tvector<DirectedEdge> pathTo(int v)\n\t{\n\t\tvector<DirectedEdge> pathToV;\n\t\tif(!hasPathTo(v))\n\t\t\treturn pathToV;\n\t\tfor(int x = v; x != s; x = edgeTo[x].from())\n\t\t\tpathToV.push_back(edgeTo[x]);\n\t\treverse(pathToV.begin(), pathToV.end());\n\t\treturn pathToV;\n\t}\nprivate:\n\t// 边的松弛\n\tvoid relax(DirectedEdge edge)\n\t{\n\t\tint v = edge.from(), w = edge.to();\n\t\tmarked[v] = true;\n\t\tmarked[w] = true;\n\t\tif(distTo[w] > distTo[v] + edge.weight())\n\t\t{\n\t\t\tdistTo[w] = distTo[v] + edge.weight();\n\t\t\tedgeTo[w] = edge;\n\t\t}\n\t}\n\n\t// 顶点的松弛\n\tvoid relax(EdgeWeightedDigraph G, int v)\n\t{\n\t\tfor(DirectedEdge edge: G.getAdj(v))\n\t\t{\n\t\t\tint w = edge.to();\n\t\t\tmarked[w] = true;\n\t\t\tmarked[v] = true;\n\t\t\tif(distTo[w] > distTo[v] + edge.weight())\n\t\t\t{\n\t\t\t\tdistTo[w] = distTo[v] + edge.weight();\n\t\t\t\tedgeTo[w] = edge;\n\t\t\t\tif(pq.contains(w))\n\t\t\t\t\tpq.change(w, distTo[w]);\n\t\t\t\telse\n\t\t\t\t\tpq.insert(w, distTo[w]);\n\t\t\t}\n\t\t}\n\t}\n\nprivate:\n\tvector<DirectedEdge> edgeTo;\n\tvector<double> distTo;\n\tvector<bool> marked;\n\tIndexPQ pq;\n\tint s;\n};\n\n/**************AcyclicSP*****************\n/* 该算法适用于无环加权图的最短路径寻找,可以在\n/* 线性时间内完成,具体就是按照该图拓扑排序的顺序\n/* 放松所有的顶点\n***************************************/\n\nclass Topological\n{\npublic:\n\tTopological(EdgeWeightedDigraph G)\n\t{\n\t\tmarked = vector<bool>(G.V(), false);\n\t\tfor(int v = 0; v < G.V(); ++v)\n\t\t\tif(!marked[v])\n\t\t\t\tdfs(G, v);\n\t}\n\n\tvector<int> order()\n\t{\n\t\treverse(_order.begin(), _order.end());\n\t\treturn _order;\n\t}\n\nprivate:\n\tvoid dfs(EdgeWeightedDigraph G, int v)\n\t{\n\t\tmarked[v] = true;\n\t\tfor(auto x: G.getAdj(v))\n\t\t\tif(!marked[x.to()])\n\t\t\t\tdfs(G, x.to());\n\t\t_order.push_back(v);\n\t}\n\nprivate:\n\tvector<bool> marked;\n\tvector<int> _order;\n\tint s;\n};\n\nclass AcyclicSP\n{\npublic:\n\tAcyclicSP(EdgeWeightedDigraph G, int _s)\n\t{\n\t\ts = _s;\n\t\tdistTo = vector<double>(G.V(), DBL_MAX);\n\t\tdistTo[0] = 0;\n\t\tedgeTo = vector<DirectedEdge>(G.V(), DirectedEdge(0, 0, 0));\n\n\t\tTopological top(G);\n\t\tfor(auto x: top.order())\n\t\t\trelax(G, x);\n\t}\n\n\tdouble getDistTo(int v) { return distTo[v]; }\n\tbool hasPathTo(int v){ return distTo[v] != DBL_MAX; }\n\n\tvector<DirectedEdge> pathTo(int v)\n\t{\n\t\tvector<DirectedEdge> path;\n\t\tif(!hasPathTo(v))\n\t\t\treturn path;\n\t\tfor(int x = v; x != s; x = edgeTo[x].from())\n\t\t\tpath.push_back(edgeTo[x]);\n\t\treverse(path.begin(), path.end());\n\t\treturn path;\n\t}\nprivate:\n\tvoid relax(EdgeWeightedDigraph G, int v)\n\t{\n\t\tfor(auto e: G.getAdj(v))\n\t\t{\n\t\t\tint w = e.to();\n\t\t\tif(distTo[w] > distTo[v] + e.weight())\n\t\t\t{\n\t\t\t\tdistTo[w] = distTo[v] + e.weight();\n\t\t\t\tedgeTo[w] = e;\n\t\t\t}\n\t\t}\n\t}\n\nprivate:\n\tvector<double> distTo;\n\tvector<DirectedEdge> edgeTo;\n\tint s;\n};\n"
},
{
"alpha_fraction": 0.5192307829856873,
"alphanum_fraction": 0.5528846383094788,
"avg_line_length": 10.55555534362793,
"blob_id": "a73b9ccf85888a80c115735e92e96467380dbe88",
"content_id": "0c03f7376cb2e4755c9e615d7a8243711c69a063",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 208,
"license_type": "no_license",
"max_line_length": 30,
"num_lines": 18,
"path": "/BST_cpp/test.cpp",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include \"AVLTree.h\"\n\nint main()\n{\n\tAVLTree tree;\n\n\tfor(int i = 1; i != 100; ++i)\n\t{\n\t\ttree.insert(i);\n\t\ttree.insert(-i);\n\t\ttree.erase(i-10);\n\t}\n\ttree.midOrder();\n\n\tcout << tree.size() << endl;\n\n\treturn 0;\n}\n"
},
{
"alpha_fraction": 0.700964629650116,
"alphanum_fraction": 0.700964629650116,
"avg_line_length": 19.733333587646484,
"blob_id": "c26fa15f10650e42a9197f9d26abc756eb1adc37",
"content_id": "59e09edc1f90b28d2edbd05a601e23beb0d235a0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 311,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 15,
"path": "/BST_cpp/BST.h",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <string>\nusing namespace std;\n\ntemplate <typename Key, typename Value>\nclass TreeNode\n{\npublic:\n\tTreeNode(Key _key, Value _value, TreeNode* _left, TreeNode* _right):\n\tkey(_key), value(_value), left(_left), right(_right){}\npublic:\n\tKey key;\n\tValue value;\n\tTreeNode *left, *right;\n};\n"
},
{
"alpha_fraction": 0.4540358781814575,
"alphanum_fraction": 0.5201793909072876,
"avg_line_length": 21.871795654296875,
"blob_id": "6b4c9f9b8e5147fa07ffa4617703bc0831d26d7e",
"content_id": "7f4dcd8ee0ad975639c213fee3fe065a758c9a0d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 908,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 39,
"path": "/UF_cpp/main.cpp",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <fstream>\n#include <time.h>\n#include \"union_find.h\"\n#include \"weighted_union_find.h\"\nusing namespace std;\n\nint main()\n{\n\tifstream in(\"test_large.txt\");\n\tint N;\n\tin>>N;\n\n union_find uf(N);\n//\tweighted_union_find uf_w(N);\n\n\tint begin = clock();\n for(int i = 0; i < 50; ++i)\n\t{\n\t\tint p, q;\n\t\tin>>p>>q;\n\t//\tuf_w._union(p, q);\n uf._union(p, q);\n\t}\n\tint end = clock();\n\n cout << \"quick_union| \" << \"area: \" << uf.count()\n\t<< \" time: \"<<(end-begin)/1000000.0 <<\"s\"<< endl;\n\t//cout << \"weighted_quick_union| \" << \"area: \" << uf_w.count()\n\t//<< \" time: \"<<(end-begin)/1000000.0 <<\"s\"<< endl;\n\n\treturn 0;\n}\n\n/****************测试结果 100w数据 200w连接**************\n *quick_find| area: 999950 time: 0.593439s\n *quick_union| area: 999950 time: 2.6e-05s\n *weighted_quick_union| area: 999950 time: 3.1e-05s\n *****************************************************/\n"
},
{
"alpha_fraction": 0.5244318246841431,
"alphanum_fraction": 0.5335227251052856,
"avg_line_length": 19.465116500854492,
"blob_id": "0658de5d52e807a1f239a18ddbdc63b73f0b1154",
"content_id": "f2d6adc78e7fd3f4d0813aa48deffcb21de85738",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1760,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 86,
"path": "/Digraph/main.cpp",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include \"Digraph.h\"\n\nint main()\n{\n\tifstream in(\"tinyDG.txt\");\n\tDigraph G(13);\n\n\tint x, y;\n\twhile(in >> x >> y)\n\t\tG.addEdge(x, y);\n\n// Test of directed graph DFS\n\tDepthFirstDirectedPaths DP(G, 4);\n\tvector<vector<int>> pathsDFS(G.V(), vector<int>());\n\tfor(int i = 0; i < G.V(); ++i)\n\t\tpathsDFS[i] = DP.pathTo(i);\n\n\tcout << \"DFS:\" << endl;\n\tfor(int i = 0; i < G.V(); ++i)\n\t{\n\t\tcout << \"4 to \" << i << \"'s path: \";\n\t\tif(pathsDFS[i].empty())\n\t\t{\n\t\t\tcout << \"no path from 4 to \" << i << endl;\n\t\t\tcontinue;\n\t\t}\n\n\t\tfor(auto x: pathsDFS[i])\n\t\t\tif(x == 4)\n\t\t\t\tcout << x;\n\t\t\telse\n\t\t\t\tcout << \" - \" << x;\n\t\tcout << endl;\n\t}\n\n\t// Test of directed graph BFS\n\tBreadthFirstDirectedPaths BP(G, 4);\n\tvector<vector<int>> pathsBFS(G.V(), vector<int>());\n\tfor(int i = 0; i < G.V(); ++i)\n\t\tpathsBFS[i] = BP.pathTo(i);\n\n\tcout << \"\\nBFS:\" << endl;\n\tfor(int i = 0; i < G.V(); ++i)\n\t{\n\t\tcout << \"4 to \" << i << \"'s path: \";\n\t\tif(pathsBFS[i].empty())\n\t\t{\n\t\t\tcout << \"no path from 4 to \" << i << endl;\n\t\t\tcontinue;\n\t\t}\n\n\t\tfor(auto x: pathsBFS[i])\n\t\t\tif(x == 4)\n\t\t\t\tcout << x;\n\t\t\telse\n\t\t\t\tcout << \" - \" << x;\n\t\tcout << endl;\n\t}\n\n\t// Test of DirectedCycle\n\t//(judge cycle in a directed graph)\n\t DirectedCycle DC(G);\n\t cout << DC.hasCycle() << endl;\n\t vector<int> cycle = DC.getCycle();\n\t for(auto x: cycle)\n\t \tcout << x << \"-\";\n\tcout << '\\b' << \" \" << endl;\n\n\t//Test of Topological\n\tTopological topo(G);\n\tcout << topo.isDAG() << endl;\n\n\t//Test of strongly connected\n\tSCC strongCC(G);\n\tvector<vector<int>> allComponent = strongCC.components();\n\tcout << \"This graph have \" << strongCC.count() << \" components:\" << endl;\n\tfor(int i = 0; i < allComponent.size(); ++i)\n\t{\n\t\tcout << \"component\" << i << \": \";\n\t\tfor(auto x: allComponent[i])\n\t\t\tcout << x << \" \";\n\t\tcout << endl;\n\t}\n\n\treturn 0;\n}\n"
},
{
"alpha_fraction": 0.5210918188095093,
"alphanum_fraction": 0.5285359621047974,
"avg_line_length": 13.925926208496094,
"blob_id": "4fb1386e5ea02e33e2fb92a20de60b59d6fca5d8",
"content_id": "e71fa5bcf30742153efd543bf4b5b984b2f9fa80",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 403,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 27,
"path": "/Graph_cpp/SymbolGraphTest.cpp",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include \"Graph.h\"\n\nint main()\n{\n\tifstream in(\"routes.txt\");\n\tSymbolGraph SG(in);\n\tGraph G = SG.getGraph();\n\n\tcout << G.E() << endl;\n\tcout << G.V() << endl;\n\n\tfor(int i = 0; i < 7; ++i)\n\t{\n\t\tfor(auto x: G.allAdj(i))\n\t\t\tcout << x << \" \";\n\t\tcout << endl;\n\t}\n\n\tstring source;\n\twhile(getline(cin, source))\n\t{\n\t\tfor(auto w: G.allAdj(SG.index(source)))\n\t\t\tcout << \" \" << SG.name(w) << endl;\n\t}\n\n\treturn 0;\n}\n"
},
{
"alpha_fraction": 0.6204379796981812,
"alphanum_fraction": 0.6313868761062622,
"avg_line_length": 12.047618865966797,
"blob_id": "4f03673ee1519a750b88e9e05f3bff3e22a46bca",
"content_id": "1315c888af9a8ca92b49174e934bbe7076c6d3be",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 274,
"license_type": "no_license",
"max_line_length": 25,
"num_lines": 21,
"path": "/MSD/main.cpp",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include \"Quick3string.h\"\n\nint main()\n{\n\tifstream in(\"test.txt\");\n\tvector<string> strVec;\n\tstring str;\n\twhile(in >> str)\n\t\tstrVec.push_back(str);\n\n\t//MSD msd;\n\t//msd.sort(strVec);\n\tQuick3string qs;\n\tqs.sort(strVec);\n\n\tfor(auto x: strVec)\n\t\tcout << x << endl;\n\n\n\treturn 0;\n}\n"
},
{
"alpha_fraction": 0.6509695053100586,
"alphanum_fraction": 0.6509695053100586,
"avg_line_length": 14.69565200805664,
"blob_id": "4178fe8f214e7dd1e0f2dc7fd4906d75e25bfaa5",
"content_id": "5393f6915705b0e5899be42ce418bbbdbe45d968",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 361,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 23,
"path": "/StringPattern/main.cc",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include \"kmp.h\"\n#include \"brute_force.h\"\n\n#include <iostream>\n#include <fstream>\n\nusing namespace std;\n\n\nint main() {\n string pattern;\n string txt;\n\n pattern = \"INDSLFJldsajflsadjfIADFNlNFLznocijlfndlfNSAOIFASLFDNSAL\";\n\n cin >> txt;\n\n Kmp kmp(pattern);\n //BruteForce bf(pattern);\n\n cout << kmp.search(txt);\n // cout << bf.search(txt);\n}\n"
},
{
"alpha_fraction": 0.5643153786659241,
"alphanum_fraction": 0.5880261063575745,
"avg_line_length": 16.75789451599121,
"blob_id": "bf830d3d019d4cea2c463a60e3c46549ea6d53ed",
"content_id": "d4556a7215fa5a62c6879548575fef95bd45837f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2285,
"license_type": "no_license",
"max_line_length": 155,
"num_lines": 95,
"path": "/UF_cpp/union_find.md",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "# union_find数据结构\n\n#### union_find迄今还没有找到能够保证在常数时间内完成的算法,最快的也只是加权quick_union算法(此处算法3)的对数时间内完成。####\n\n\n\nunion_find的实现有三种方法,分别是:\n\n- quick_find 这个方法是find常数时间,而union是平方级别的。该算法的实现就是,同一个集合的所有元素都指向同一个数。mark\n\n- quick_union 这个方法是union常数时间,而find是最坏情形平方级别,quick_union在大部分情况比quick_find快,但是最坏情形十分糟糕。这个算法的实现是每个元素都有一个连接,指向connected的另一个元素,也可以指向自己,如果连接指向自己,那么这个元素就是根节点root。\n\n- weighted_quick_union是最好的算法,他是对数级别的。因为这个算法多添加了记录每个树的大小的数组,来避免大树连接在小树的情况发生。该算法的find()函数和quick_union的一致,只是union()函数有所修改,来改进性能。\n\n### quick_find算法\n```\n// quick_find\nvoid union_find::_union(int p, int q)\n{\n if(find(p) != find(q))\n {\n int p_num = vec[p], q_num = vec[q];\n for(auto &x: vec)\n {\n if(x == p_num)\n x = q_num;\n }\n --_count;\n }\n}\n\nint union_find::find(int p)\n{\n return vec[p];\n}\n```\n\n\n### quick_union算法\n```\n// quick_union\nvoid union_find::_union(int p, int q)\n{\n\tint proot = find(p);\n\tint qroot = find(q);\n\n\tif(proot != qroot)\n\t{\n\t\tvec[proot] = qroot;\n\t\t--_count;\n\t}\n}\n\nint union_find::find(int p)\n{\n\twhile(vec[p] != p)\n\t\tp = vec[p];\n\treturn p;\n}\n```\n\n\n### weighted_quick_union算法\n```\n\nvoid weighted_union_find::_union(int p, int q)\n{\n\tint proot = find(p);\n\tint qroot = find(q);\n\tif(proot != qroot)\n\t{\n\t\tif(size[proot] > size[qroot])\n\t\t{\n\t\t\tvec[qroot] = proot;\n\t\t\tsize[proot] += size[qroot];\n\t\t}\n\t\telse\n\t\t{\n\t\t\tvec[proot] = qroot;\n\t\t\tsize[qroot] += size[proot];\n\t\t}\n\t\t--area_count;\n\t}\n}\n\n```\n\n\n```\n/****************测试结果 100w数据 200w连接**************\n * quick_find| area: 999950 time: 0.593439s\n * quick_union| area: 999950 time: 2.6e-05s\n * weighted_quick_union| area: 999950 time: 3.1e-05s\n *****************************************************/\n```\n"
},
{
"alpha_fraction": 0.5817757248878479,
"alphanum_fraction": 0.6074766516685486,
"avg_line_length": 16.1200008392334,
"blob_id": "dc4e65cfce61284fe20b1fb300423cb6f4b8327e",
"content_id": "97973d488ed8db5a6b45324a7d2543e561bc6156",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 430,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 25,
"path": "/Sort_cpp/main.cpp",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include \"Sort.h\"\n// sort(T*, int)\n// sort(vector<T>&)\n\nint main()\n{\n\tSort<int> sort;\n\tvector<int> vec;\n\tfor(int i = 0; i != 11111; ++i)\n\t{\n\t\tauto num = static_cast<int>(rand()%1000);\n\t\tvec.push_back(num);\n\t}\n\t//sort.shellSort(vec);\n\t//sort.insertSort(vec);\n\t//sort.selecteSort(vec);\n\t//sort.mergeSort(vec);\n\t//sort.quickSort(vec);\n\tsort.heapSort(vec);\n\n\tif(sort.isSorted(vec))\n\t\tfor(auto x: vec)\n\t\t\tcout<<x<<endl;\n\treturn 0;\n}\n"
},
{
"alpha_fraction": 0.37042802572250366,
"alphanum_fraction": 0.3929961025714874,
"avg_line_length": 22.796297073364258,
"blob_id": "cfd2749af8299ed29d7dca44fa90378535f7ad6c",
"content_id": "e46080b8af48adb70c2d248f686e7229767478fa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1285,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 54,
"path": "/Graph_cpp/main.cpp",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include \"Graph.h\"\n\nint main()\n{\n Graph gra(10);\n gra.addEdge(0, 5);\n gra.addEdge(2, 4);\n gra.addEdge(2, 3);\n gra.addEdge(1, 2);\n gra.addEdge(0, 1);\n gra.addEdge(3, 4);\n gra.addEdge(3, 5);\n gra.addEdge(0, 2);\n\n DepthFirstPaths search(gra, 0);\n BreadthFirstPaths searchBFS(gra, 0);\n\n cout << \"DFS:\" << endl;\n for(int v = 0; v < gra.V(); ++v)\n {\n cout << 0 << \" to \" << v << \": \";\n if(search.hasPathTo(v))\n {\n vector<int> path = search.pathTo(v);\n for (int i = 0; i < path.size(); ++i)\n if (path[i] == 0)\n cout << path[i];\n else\n cout << \"-\" << path[i];\n }\n cout << endl;\n }\n\n cout << \"\\nBFS:\" << endl;\n for(int v = 0; v < gra.V(); ++v)\n {\n cout << 0 << \" to \" << v << \": \";\n if(searchBFS.hasPathTo(v))\n {\n vector<int> path = searchBFS.pathTo(v);\n for (int i = 0; i < path.size(); ++i)\n if (path[i] == 0)\n cout << path[i];\n else\n cout << \"-\" << path[i];\n }\n cout << endl;\n }\n\n CC cc(gra);\n cout << \"\\nGraph gra has \" << cc.count() << \" components\" << endl;\n\n return 0;\n}\n"
},
{
"alpha_fraction": 0.39657020568847656,
"alphanum_fraction": 0.4115755558013916,
"avg_line_length": 20.227272033691406,
"blob_id": "b79703aaa2882d50e859680fba13943ab0c0016b",
"content_id": "c8be29b27d708fa10c036090f8901a71b5b7ee46",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 933,
"license_type": "no_license",
"max_line_length": 60,
"num_lines": 44,
"path": "/StringPattern/kmp.h",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include <vector>\n#include <string>\n\nusing std::vector;\nusing std::string;\n\nclass Kmp {\npublic:\n Kmp (string _pat):\n pat(_pat) {\n auto row = 256;\n auto col = pat.size();\n dfa = vector<vector<int>>(row, vector<int>(col, 0));\n dfa[int(pat[0])][0] = 1;\n \n for (int x = 0, j = 1; j < col; ++j) {\n for (int c = 0; c < row; ++c) {\n dfa[c][j] = dfa[c][x];\n }\n dfa[pat[j]][j] = j + 1;\n x = dfa[pat[j]][x];\n }\n }\n\n int search(const string &txt) {\n auto m = pat.size();\n auto n = txt.size();\n\n auto it_pat = 0;\n auto it_txt = 0;\n while (it_pat < m && it_txt < n) {\n it_pat = dfa[txt[it_txt]][it_pat];\n ++it_txt;\n }\n\n if (it_pat == m) \n return it_txt - m;\n return -1;\n }\n\nprivate:\n vector<vector<int>> dfa;\n string pat;\n};"
},
{
"alpha_fraction": 0.5249999761581421,
"alphanum_fraction": 0.625,
"avg_line_length": 23.200000762939453,
"blob_id": "0fc04f66ef73c51a02bb0fffd50c45380d879cdb",
"content_id": "fe5c33619244e64a9c9443016429951ef93db5f9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 120,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 5,
"path": "/StringPattern/a.py",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "import random\n\nwith open('txt', 'wt') as fw:\n for i in range(10000000):\n fw.write(chr(random.randint(65, 91)))"
},
{
"alpha_fraction": 0.5870862603187561,
"alphanum_fraction": 0.5885331630706787,
"avg_line_length": 13.25,
"blob_id": "a136e233c3076443d1439b0ba064f354965be49b",
"content_id": "168b7b1a9f91cadb74b7676f7d2851eb134669f0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5537,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 388,
"path": "/Digraph/Digraph.h",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <fstream>\n#include <vector>\n#include <algorithm>\n#include <queue>\n#include <stack>\nusing namespace std;\n\nclass Digraph\n{\npublic:\n\tDigraph(int _v): v(_v), e(0)\n\t{\n\t\tadj = vector<vector<int>>(_v, vector<int>());\n\t}\n\n\tvector<int> getAdj(int v) { return adj[v]; }\n\tint V() { return v; }\n\tint E()\t{ return e;\t}\n\n\tvoid addEdge(int v, int w)\n\t{\n\t\t++e;\n\t\tadj[v].push_back(w);\n\t}\n\n\tDigraph reverse()\n\t{\n\t\tDigraph dg(v);\n\t\tfor(int i = 0; i < v; ++i)\n\t\t\tfor(auto x: adj[i])\n\t\t\t\tdg.addEdge(x, i);\n\t\treturn dg;\n\t}\n\nprivate:\n\tvector<vector<int>> adj;\n\tint v;\n\tint e;\n};\n\n\nclass DirectedDFS\n{\npublic:\n\tDirectedDFS(Digraph G, int s)\n\t{\n\t\tmarked = vector<bool>(G.V(), false);\n\t\tdfs(G, s);\n\t}\n\n\tDirectedDFS(Digraph G, vector<int> sources)\n\t{\n\t\tmarked = vector<bool>(G.V(), false);\n\t\tfor(auto x: sources)\n\t\t\tdfs(G, x);\n\t}\n\n\tbool isMarked(int v)\n\t{\n\t\treturn marked[v];\n\t}\n\nprivate:\n\tvoid dfs(Digraph G, int v)\n\t{\n\t\tmarked[v] = true;\n\t\tfor(auto x: G.getAdj(v))\n\t\t{\n\t\t \tif(!isMarked(x))\n\t\t\t\tdfs(G, x);\n\t\t}\n\t}\n\nprivate:\n\tvector<bool> marked;\n};\n\nclass DepthFirstDirectedPaths\n{\npublic:\n\tDepthFirstDirectedPaths(Digraph DG, int _s)\n\t{\n\t\tmarked = vector<bool>(DG.V(), false);\n\t\tedgeTo = vector<int>(DG.V(), _s);\n\t\ts = _s;\n\t\tdfs(DG, _s);\n\t}\n\n\tbool hasPathTo(int v)\n\t{\n\t\treturn isMarked(v);\n\t}\n\n\tvector<int> pathTo(int v)\n\t{\n\t\tvector<int> pathToStart;\n\t\tif(!hasPathTo(v))\n\t\t\treturn pathToStart;\n\n\t\tfor(int x = v; x != s; x = edgeTo[x])\n\t\t\tpathToStart.push_back(x);\n\t\tpathToStart.push_back(s);\n\t\treverse(pathToStart.begin(), pathToStart.end());\n\t\treturn pathToStart;\n\t}\n\n\tbool isMarked(int v)\n\t{\n\t\treturn marked[v];\n\t}\n\nprivate:\n\tvoid dfs(Digraph DG, int v)\n\t{\n\t\tmarked[v] = true;\n\t\tfor(auto x: DG.getAdj(v))\n\t\t{\n\t\t\tif (!marked[x])\n\t\t\t{\n\t\t\t\tedgeTo[x] = v;\n\t\t\t\tdfs(DG, x);\n\t\t\t}\n\t\t}\n\t}\n\nprivate:\n\tvector<bool> marked;\n\tvector<int> edgeTo;\n\tint s;\n};\n\nclass BreadthFirstDirectedPaths\n{\npublic:\n\tBreadthFirstDirectedPaths(Digraph DG, int _s)\n\t{\n\t\tmarked = vector<bool>(DG.V(), false);\n\t\tedgeTo = vector<int>(DG.V(), _s);\n\t\ts = _s;\n\t\tbfs(DG, s);\n\t}\n\n\tbool hasPathTo(int v)\n\t{\n\t\treturn isMarked(v);\n\t}\n\n\tvector<int> pathTo(int v)\n\t{\n\t\tvector<int> pathToStart;\n\t\tif(!hasPathTo(v))\n\t\t\treturn pathToStart;\n\n\t\tfor(int x = v; x != s; x = edgeTo[x])\n\t\t\tpathToStart.push_back(x);\n\t\tpathToStart.push_back(s);\n\t\treverse(pathToStart.begin(), pathToStart.end());\n\t\treturn pathToStart;\n\t}\n\n\tbool isMarked(int v)\n\t{\n\t\treturn marked[v];\n\t}\n\nprivate:\n\tvoid bfs(Digraph DG, int v)\n\t{\n\t\tqueue<int> q;\n\t\tq.push(v);\n\t\tmarked[v] = true;\n\n\t\twhile(!q.empty())\n\t\t{\n\t\t\tint s = q.front();\n\t\t\tq.pop();\n\t\t\tfor(auto x: DG.getAdj(s))\n\t\t\t{\n\t\t\t\tif(!marked[x])\n\t\t\t\t{\n\t\t\t\t\tq.push(x);\n\t\t\t\t\tedgeTo[x] = s;\n\t\t\t\t\tmarked[x] = true;\n\t\t\t\t}\n\t\t\t}\n\t\t}\n\t}\n\nprivate:\n\tvector<bool> marked;\n\tvector<int> edgeTo;\n\tint s;\n};\n\nclass DirectedCycle\n{\npublic:\n\tDirectedCycle(Digraph G)\n\t{\n\t\tmarked = vector<bool>(G.V(), false);\n\t\tedgeTo = vector<int>(G.V(), 0);\n\t\tonStack = vector<bool>(G.V(), false);\n\t\tfor(int v = 0; v < G.V(); ++v)\n\t\t\tdfs(G, v);\n\t}\n\n\tbool hasCycle()\n\t{\n\t\treturn !cycle.empty();\n\t}\n\n\tvector<int> getCycle()\n\t{\n\t\tvector<int> cycleVec;\n\t\twhile(!cycle.empty())\n\t\t{\n\t\t\tcycleVec.push_back(cycle.top());\n\t\t\tcycle.pop();\n\t\t}\n\t\treturn cycleVec;\n\t}\nprivate:\n\tvoid dfs(Digraph G, int v)\n\t{\n\t\tonStack[v] = true;\n\t\tmarked[v] = true;\n\t\tfor(int w: G.getAdj(v))\n\t\t{\n\t\t\tif(hasCycle())\n\t\t\t\treturn;\n\t\t\telse if(!marked[w])\n\t\t\t{\n\t\t\t\tedgeTo[w] = v;\n\t\t\t\tdfs(G, w);\n\t\t\t}\n\t\t\telse if(onStack[w])\n\t\t\t{\n\t\t\t\tfor(int x = v; x != w; x = edgeTo[x])\n\t\t\t\t\tcycle.push(x);\n\t\t\t\tcycle.push(w);\n\t\t\t\tcycle.push(v);\n\t\t\t}\n\t\t}\n\t\tonStack[v] = false;\n\t}\n\nprivate:\n\tvector<bool> marked;\n\tvector<int> edgeTo;\n\tstack<int> cycle;\n\tvector<bool> onStack;\n};\n\nclass DepthFirstOrder\n{\npublic:\n\tDepthFirstOrder(Digraph G)\n\t{\n\t\tmarked = vector<bool>(G.V(), false);\n\t\tfor(int v = 0; v < G.V(); ++v)\n\t\t\tif(!marked[v])\n\t\t\t\tdfs(G, v);\n\t}\n\n\tvector<int> preOrder()\n\t{\n\t\treturn pre;\n\t}\n\n\tvector<int> postOrder()\n\t{\n\t\treturn post;\n\t}\n\n\tvector<int> reversePostOrder()\n\t{\n\t\treverse(reversePost.begin(), reversePost.end());\n\t\treturn reversePost;\n\t}\n\nprivate:\n\tvoid dfs(Digraph G, int v)\n\t{\n\t\tpre.push_back(v);\n\t\tmarked[v] = true;\n\t\tfor(auto x: G.getAdj(v))\n\t\t{\n\t\t\tif(!marked[x])\n\t\t\t\tdfs(G, x);\n\t\t}\n\t\tpost.push_back(v);\n\t\treversePost.push_back(v);\n\t}\n\nprivate:\n\tvector<bool> marked;\n\tvector<int> pre;\n\tvector<int> post;\n\tvector<int> reversePost;\n};\n\n//拓扑排序\nclass Topological\n{\npublic:\n\tTopological(Digraph G)\n\t{\n\t\tDirectedCycle cycleJudge(G);\n\t\tif(!cycleJudge.hasCycle())\n\t\t{\n\t\t\tDepthFirstOrder dfs(G);\n\t\t\torderVec = dfs.reversePostOrder();\n\t\t}\n\t}\n\n\tvector<int> order()\n\t{\n\t\treturn orderVec;\n\t}\n\n\tbool isDAG()\n\t{\n\t\treturn !orderVec.empty();\n\t}\n\nprivate:\n\tvector<int> orderVec;\n};\n\n// find all strongly connected components\n// use the Kosaraju algorithm\nclass SCC\n{\npublic:\n\tSCC(Digraph G)\n\t{\n\t\tmarked = vector<bool>(G.V(), false);\n\t\tid = vector<int>(G.V(), 0);\n\t\tcnt = 0;\n\n\t\tDepthFirstOrder dfsOrder(G.reverse());\n\t\tfor(auto x: dfsOrder.reversePostOrder())\n\t\t\tif(!marked[x])\n\t\t\t{\n\t\t\t\tdfs(G, x);\n\t\t\t\t++cnt;\n\t\t\t}\n\t}\n\n\tbool stronglyConnected(int v, int w)\n\t{\n\t\treturn id[v] == id[w];\n\t}\n\n\tint count()\n\t{\n\t\treturn cnt;\n\t}\n\n\tint getID(int v)\n\t{\n\t\treturn id[v];\n\t}\n\n\tvector<vector<int>> components()\n\t{\n\t\tvector<vector<int>> comp(count(), vector<int>());\n\t\tfor(int i = 0; i < id.size(); ++i)\n\t\t\tcomp[id[i]].push_back(i);\n\t\treturn comp;\n\t}\n\nprivate:\n\tvoid dfs(Digraph G, int v)\n\t{\n\t\tmarked[v] = true;\n\t\tid[v] = cnt;\n\t\tfor(auto x: G.getAdj(v))\n\t\t\tif(!marked[x])\n\t\t\t\tdfs(G, x);\n\t}\n\nprivate:\n\tvector<bool> marked;\n\tvector<int> id;\n\tint cnt;\n};\n"
},
{
"alpha_fraction": 0.516867458820343,
"alphanum_fraction": 0.5397590398788452,
"avg_line_length": 18.302326202392578,
"blob_id": "07b744cc829123c22c735659cedb80dfe173cee8",
"content_id": "422c9ac694fea65a3f0cb654540eaec5754a13b2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 846,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 43,
"path": "/MSD/MSD.h",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <vector>\n#include <fstream>\n#include <algorithm>\n#include <string>\nusing namespace std;\n\nclass MSD\n{\npublic:\n\tvoid sort(vector<string> &vec)\n\t{\n\t\tint N = vec.size();\n\t\taux = vector<string>(N, \"\");\n\t\tsort(vec, 0, N-1, 0);\n\t}\n\nprivate:\n\tvoid sort(vector<string> &vec, int lo, int hi, int d)\n\t{\n\t\tif(hi <= lo + M)\n\t\t{\n\t\t\tstd::sort(vec.begin()+lo, vec.begin()+hi+1);\n\t\t\treturn ;\n\t\t}\n\t\tvector<int> count(R+2, 0);\n\t\tfor(int i = lo; i <= hi; ++i)\n\t\t\tcount[vec[i][d]+2]++;\n\t\tfor(int r = 0; r < R+1; ++r)\n\t\t\tcount[r+1] += count[r];\n\t\tfor(int i = lo; i <= hi; ++i)\n\t\t\taux[count[vec[i][d]+1]++] = vec[i];\n\t\tfor(int i = lo; i <= hi; ++i)\n\t\t\tvec[i] = aux[i-lo];\n\t\tfor(int r = 0; r < R; ++r)\n\t\t\tsort(vec, lo+count[r], lo+count[r+1]-1, d+1);\n\t}\n\nprivate:\n\tint R = 256;\n\tint M = 3; //小数组的切换阀值\n\tvector<string> aux;\n};\n"
},
{
"alpha_fraction": 0.5706595182418823,
"alphanum_fraction": 0.5773889422416687,
"avg_line_length": 22.967741012573242,
"blob_id": "28ade94ed30201acd9ad3fea23829c87e47a8611",
"content_id": "a644d0ac9b802f3b8b64753c71cbd2aaf99d7d91",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 743,
"license_type": "no_license",
"max_line_length": 61,
"num_lines": 31,
"path": "/EdgeWeightedGraph/main.cpp",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include \"Kruskal.h\"\n\nint main()\n{\n\tifstream in(\"1000EWG.txt\");\n\tint graphSize;\n\tin >> graphSize;\n\n\tEdgeWeightedGraph EWG(graphSize);\n\tint w, v;\n\tdouble weight;\n\twhile(in >> w >> v >> weight)\n\t\tEWG.addEdge(Edge(w, v, weight));\n\tcout << EWG.V() << \" \" << EWG.E() << endl;\n\n\tLazyPrimMST LMST(EWG);\n\tvector<Edge> mst = LMST.edges();\n\tcout << \"The mst weight(Prim): \" << LMST.weight() << endl;\n\tcout << \"The mst: \" << endl ;\n\tfor(auto x: mst)\n\t\tcout << x.either() << \"-\" << x.other(x.either()) << endl;\n\n\tKruskalMST KMST(EWG);\n\tvector<Edge> kmst = KMST.edges();\n\tcout << \"The mst weight(Kruskal):\" << KMST.weight() << endl;\n\tcout << \"The mst: \" << endl;\n\tfor(auto x: kmst)\n\t\tcout << x.either() << \"-\" << x.other(x.either()) << endl;\n\n\treturn 0;\n}\n"
},
{
"alpha_fraction": 0.509040355682373,
"alphanum_fraction": 0.5194714665412903,
"avg_line_length": 18.432432174682617,
"blob_id": "e99a34bf5b4e2a4dbf048d4a9270e3165ff7fd29",
"content_id": "642d2151636c869cfa8cb451c4fb35440dad63dc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1438,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 74,
"path": "/Sort_cpp/randomSelect.cpp",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <vector>\n#include <fstream>\n#include <algorithm>\nusing namespace std;\n\nconst int SIZE = 10000;\n\nint randomizedSelect(vector<int>& vec, int lo, int hi, int i);\nint partition(vector<int>& vec, int lo, int hi);\nvoid exchange(int &a, int &b);\n\nint main()\n{\n ifstream in(\"random.txt\");\n ifstream sorted(\"sorted.txt\");\n\n vector<int> vec;\n int num;\n\n while(in >> num)\n vec.push_back(num);\n\n for(int i = 0; i != SIZE; ++i)\n {\n sorted >> num;\n if(randomizedSelect(vec, 0, SIZE-1, i) == num)\n cout << \"TESTING \" << i << endl;\n else\n cout << \"ERROR \" << i << endl;\n }\n cout << \"PASSED\" << endl;\n\n return 0;\n}\n\nint randomizedSelect(vector<int>& vec, int lo, int hi, int i)\n{\n if(hi == lo)\n return vec[lo];\n\n int par = partition(vec, lo, hi);\n int k = par-lo+1;\n\n if(k == i)\n return vec[par];\n else if(k < i)\n return randomizedSelect(vec, par+1, hi, i-k);\n else\n return randomizedSelect(vec, lo, par-1, i);\n}\n\nint partition(vector<int>& vec, int lo, int hi)\n{\n int lt = lo, i = lo+1, gt = hi;\n int v = vec[lo];\n\n while(i <= gt)\n {\n int cmp = vec[i] - v;\n if(cmp < 0) exchange(vec[lt++], vec[i++]);\n else if(cmp > 0) exchange(vec[i], vec[gt--]);\n else ++i;\n }\n \n return i;\n}\n\nvoid exchange(int& a, int& b)\n{\n auto x = a;\n a = b;\n b = x;\n}\n"
},
{
"alpha_fraction": 0.5650356411933899,
"alphanum_fraction": 0.5667568445205688,
"avg_line_length": 13.524999618530273,
"blob_id": "1ce638b241746bf00e5503c6e79d6e197d33475f",
"content_id": "378aa7a2b1055100d1fadf0ddaf83964935a710c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4079,
"license_type": "no_license",
"max_line_length": 59,
"num_lines": 280,
"path": "/Graph_cpp/Graph.h",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <vector>\n#include <algorithm>\n#include <fstream>\n#include <sstream>\n#include <queue>\n#include <map>\nusing namespace std;\n\nclass Graph\n{\npublic:\n\tGraph(int _v): v(_v), e(0), adj(_v, vector<int>()){}\n\tGraph(): v(0), e(0){}\n\tint V(){return v;}\n\tint E(){return e;}\n\tvoid addEdge(int v, int w)\n\t{\n\t\tif(find(adj[v].begin(), adj[v].end(), w) == adj[v].end())\n\t\t\tadj[v].push_back(w);\n\t\tif(find(adj[w].begin(), adj[w].end(), v) == adj[w].end())\n\t\t\tadj[w].push_back(v);\n\t\t++e;\n\t}\n\tvector<int>& allAdj(int v){return adj[v];}\n\nprivate:\n\tint v;\n\tint e;\n\tvector<vector<int>> adj;\n};\n\nclass SymbolGraph\n{\npublic:\n\tSymbolGraph(ifstream& stream, string dot)\n\t{\n\t\tstring strOne, strTwo;\n\t\tvector<pair<string, string>> pairs;\n\n\t\twhile(stream >> strOne >> strTwo )\n\t\t{\n\t\t\tpairs.push_back(make_pair(strOne, strTwo));\n\t\t\tif(find(keys.begin(), keys.end(), strOne) == keys.end())\n\t\t\t\tkeys.push_back(strOne);\n\t\t\tif(find(keys.begin(), keys.end(), strTwo) == keys.end())\n\t\t\t\tkeys.push_back(strTwo);\n\t\t}\n\n\t\tfor(int i = 0; i < keys.size(); ++i)\n\t\t\tst[keys[i]] = i;\n\n\t\tG = Graph(keys.size());\n\t\tfor(auto x: pairs)\n\t\t\tG.addEdge(st[x.first], st[x.second]);\n\t}\n\n\tbool contains(string s)\n\t{\n\t\treturn find(keys.begin(), keys.end(), s) != keys.end();\n\t}\n\n\tint index(string s)\n\t{\n\t\treturn st[s];\n\t}\n\n\tstring name(int v)\n\t{\n\t\treturn keys[v];\n\t}\n\n\tGraph getGraph()\n\t{\n\t\treturn G;\n\t}\n\nprivate:\n\tGraph G;\n\tmap<string, int> st;\n\tvector<string> keys;\n};\n\nclass Search\n{\npublic:\n\tSearch(Graph G, int s): vOfs(G.allAdj(s)){}\n\tbool marked(int v)\n\t{\n\t\tauto x = find(vOfs.begin(), vOfs.end(), v);\n\t\treturn x != vOfs.end();\n\t}\n\tint count()\n\t{\n\t\treturn vOfs.size();\n\t}\n\nprivate:\n\tvector<int> vOfs;\n};\n\nclass DepthFirstSearch\n{\npublic:\n\tDepthFirstSearch(Graph G, int s)\n\t{\n\t\tmarked = vector<bool>(G.V(), false);\n\t\tdfs(G, s);\n\t}\n\n\tbool isMarked(int w)\n\t{\n\t\treturn marked[w];\n\t}\n\n\tint count()\n\t{\n\t\treturn _count;\n\t}\n\nprivate:\n\tvoid dfs(Graph G, int v)\n\t{\n\t\tmarked[v] = true;\n\t\t_count++;\n\t\tfor(auto w: G.allAdj(v))\n\t\t\tif(marked[w] == false)\n\t\t\t\tdfs(G, w);\n\t}\n\nprivate:\n\tvector<bool> marked;\n\tint _count;\n};\n\n\nclass DepthFirstPaths\n{\npublic:\n\tDepthFirstPaths(Graph G, int _s)\n\t{\n\t\tmarked = vector<bool>(G.V(), false);\n\t\tedgeTo = vector<int>(G.V(), _s);\n\t\ts = _s;\n\t\tdfs(G, s);\n\t}\n\n\tvoid dfs(Graph G, int v)\n\t{\n\t\tmarked[v] = true;\n\t\tfor(auto w: G.allAdj(v))\n\t\t\tif(!marked[w])\n\t\t\t{\n\t\t\t\tedgeTo[w] = v;\n\t\t\t\tdfs(G, w);\n\t\t\t}\n\t}\n\n\tbool hasPathTo(int v)\n\t{\n\t\treturn marked[v];\n\t}\n\n\tvector<int> pathTo(int v)\n\t{\n\t\tvector<int> path;\n\t\tif(!hasPathTo(v))\n\t\t\treturn path;\n\t\tfor(int x = v ; x != s; x = edgeTo[x])\n\t\t\tpath.push_back(x);\n\t\tpath.push_back(s);\n\t\treverse(path.begin(), path.end());\n\t\treturn path;\n\t}\n\nprivate:\n\tvector<bool> marked;\n\tvector<int> edgeTo;\n\tint s;\n};\n\nclass BreadthFirstPaths\n{\npublic:\n\tBreadthFirstPaths(Graph G, int _s)\n\t{\n\t\tmarked = vector<bool>(G.V(), false);\n\t\tedgeTo = vector<int>(G.V(), s);\n\t\ts = _s;\n\t\tbfs(G, s);\n\t}\n\n\tvoid bfs(Graph G, int s)\n\t{\n\t\tqueue<int> q;\n\t\tmarked[s] = true;\n\t\tq.push(s);\n\t\twhile(!q.empty())\n\t\t{\n\t\t\tint v = q.front();\n\t\t\tq.pop();\n\t\t\tfor(auto w: G.allAdj(v))\n\t\t\t\tif(!marked[w])\n\t\t\t\t{\n\t\t\t\t\tedgeTo[w] = v;\n\t\t\t\t\tmarked[w] = true;\n\t\t\t\t\tq.push(w);\n\t\t\t\t}\n\t\t}\n\t}\n\n\tbool hasPathTo(int v)\n\t{\n\t\treturn marked[v];\n\t}\n\n\tvector<int> pathTo(int v)\n\t{\n\t\tvector<int> path;\n\t\tif(!hasPathTo(v))\n\t\t\treturn path;\n\t\tfor(int x = v; x != s; x = edgeTo[x])\n\t\t\tpath.push_back(x);\n\t\tpath.push_back(s);\n\t\treverse(path.begin(), path.end());\n\t\treturn path;\n\t}\n\nprivate:\n\tvector<bool> marked;\n\tvector<int> edgeTo;\n\tint s;\n};\n\n//计算连通分量\nclass CC\n{\npublic:\n\tCC(Graph G)\n\t{\n\t\tmarked = vector<bool>(G.V(), false);\n\t\t_id = vector<int>(G.V(), 0);\n\t\t_count = 0;\n\t\tfor(int s = 0; s < G.V(); ++s)\n\t\t\tif(!marked[s])\n\t\t\t{\n\t\t\t\tdfs(G, s);\n\t\t\t\t_count++;\n\t\t\t}\n\t}\n\n\tvoid dfs(Graph G, int v)\n\t{\n\t\tmarked[v] = true;\n\t\t_id[v] = _count;\n\t\tfor(auto x: G.allAdj(v))\n\t\t\tif(!marked[x])\n\t\t\t\tdfs(G, x);\n\t}\n\n\tbool connected(int v, int w)\n\t{\n\t\treturn id(v) == id(w);\n\t}\n\n\tint id(int v)\n\t{\n\t\treturn _id[v];\n\t}\n\n\tint count()\n\t{\n\t\treturn _count;\n\t}\n\nprivate:\n\tvector<bool> marked;\n\tvector<int> _id;\n\tint _count;\n};\n"
},
{
"alpha_fraction": 0.4755687415599823,
"alphanum_fraction": 0.48981207609176636,
"avg_line_length": 18.901575088500977,
"blob_id": "b99fd7928af0392a5ea79f7a2fe5549e61a22abf",
"content_id": "c1705aa14156d7921afa69ef9a7d73259b529184",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5113,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 254,
"path": "/Sort_cpp/test.cpp",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include <iostream>\n#include <algorithm>\n#include <vector>\n#include <fstream>\n#define SIZE 10000\n#define LEFT(n) (n*2+1)\n#define RIGHT(n) (LEFT(n)+ 1)\n#define PARENT(n) (n>>1)\nusing namespace std;\n\nvoid insertSort(vector<int>& vec);\nvoid selecteSort(vector<int>& vec);\nvoid mergeSort(vector<int>& vec);\nvoid heapSort(vector<int>& vec);\nvoid quickSort(vector<int>& vec);\n\nvoid countingSort(vector<int>& vec);\nvoid radixSort(vector<int>& vec);\n\nvoid exchange(int &a, int &b);\nvoid sink(vector<int>& vec, int i, int n);\nint partition(vector<int>& vec, int lo, int hi);\n\nint main()\n{\n ifstream in(\"random.txt\");\n ifstream sorted(\"sorted.txt\");\n\n int num, i = 0;\n vector<int> vec;\n\n while(in >> num)\n {\n vec.push_back(num);\n }\n\n countingSort(vec);\n\n while(sorted >> num)\n {\n cout << \"TESTING........\" << num << endl;\n int test = vec[i++];\n if(num == test)\n {\n continue;\n }\n else\n {\n cout << \"WRONG ANSWER\" << endl;\n cout << \"ERROR POSITION: \" << num << endl;\n exit(0);\n }\n }\n cout << \"PASSED\" << endl;\n\n return 0;\n}\n\nvoid exchange(int &a, int &b)\n{\n auto temp = a;\n a = b;\n b = temp;\n}\n\nvoid insertSort(vector<int>& vec, int lo, int hi)\n{\n for(int i = lo+1; i != hi+1; ++i)\n {\n for(int j = i; j > lo && vec[j] < vec[j-1]; --j)\n {\n exchange(vec[j], vec[j-1]);\n }\n }\n}\n\nvoid insertSort(vector<int>& vec)\n{\n insertSort(vec, 0, vec.size()-1);\n}\n\nvoid selecteSort(vector<int>& vec)\n{\n int size = vec.size();\n\n for(int i = 0; i != size-1; ++i)\n {\n int min = i;\n for(int j = i+1; j != size; ++j)\n {\n if(vec[j] < vec[min])\n {\n min = j;\n }\n }\n exchange(vec[min], vec[i]);\n }\n}\n\nvoid merge(vector<int>& vec, vector<int>& vecCopy, int lo, int mid, int hi)\n{\n for(int i = lo; i <= hi; ++i)\n vecCopy[i] = vec[i];\n\n int i = lo, j = mid+1;\n for(int k = lo; k <= hi; ++k)\n {\n if(i > mid)\n vec[k] = vecCopy[j++];\n else if(j > hi)\n vec[k] = vecCopy[i++];\n else if(vecCopy[i] < vecCopy[j])\n vec[k] = vecCopy[i++];\n else\n vec[k] = vecCopy[j++];\n }\n}\n\nvoid mergeSort(vector<int>& vec, vector<int>& vecCopy, int lo, int hi)\n{\n int n = hi-lo+1;\n if(n <= 10)\n {\n insertSort(vec, lo, hi);\n return;\n }\n if(lo >= hi)\n return;\n\n int mid = lo + (hi-lo)/2;\n mergeSort(vec, vecCopy, lo, mid);\n mergeSort(vec, vecCopy, mid+1, hi);\n merge(vec, vecCopy, lo, mid, hi);\n}\n\nvoid mergeSort(vector<int>& vec)\n{\n vector<int> vecCopy(vec);\n mergeSort(vec, vecCopy, 0, vec.size()-1);\n}\n\nvoid sink(vector<int>& vec, int i, int n)\n{\n while(i*2 < n)\n {\n int child = 2*i+1;\n if(child+1 < n && vec[child] < vec[child+1])\n ++child;\n if(vec[child] < vec[i])\n break;\n exchange(vec[child], vec[i]);\n i = child;\n }\n}\n\nvoid heapSort(vector<int>& vec)\n{\n int len = vec.size();\n for(int i = len/2; i >= 0; --i)\n sink(vec, i, len);\n for(int i = len-1; i > 0; --i)\n {\n exchange(vec[i], vec[0]);\n sink(vec, 0, i-1);\n }\n}\n\nvoid quickSort(vector<int>& vec, int lo ,int hi)\n{\n if(lo < hi)\n {\n int par = partition(vec, lo, hi);\n quickSort(vec, lo, par-1);\n quickSort(vec, par+1, hi);\n }\n}\n\nvoid threeWayQuickSort(vector<int>& vec, int lo, int hi)\n{\n if(hi <= lo) return;\n int lt = lo, i = lo+1, gt = hi;\n int v = vec[lo];\n\n while(i <= gt)\n {\n int cmp = vec[i] - v;\n if(cmp < 0) exchange(vec[lt++], vec[i++]);\n else if(cmp > 0) exchange(vec[i], vec[gt--]);\n else ++i;\n }\n threeWayQuickSort(vec, lo, lt-1);\n threeWayQuickSort(vec, gt+1, hi);\n}\n\nvoid quickSort(vector<int>& vec)\n{\n threeWayQuickSort(vec, 0, vec.size()-1);\n// quickSort(vec, 0, vec.size()-1);\n}\n\nint partition(vector<int>& vec, int lo, int hi)\n{\n int i = lo-1, j = hi, x = vec[hi];\n while(1)\n {\n while(vec[++i] < x)\n if(i == hi) break;\n while(vec[--j] > x)\n if(j == lo) break;\n if(i < j)\n exchange(vec[i], vec[j]);\n else\n break;\n }\n exchange(vec[i], vec[hi]);\n return i;\n}\n\n//计数排序\n\n\nvoid countingSort(vector<int>& vec, vector<int>& aux, int k)\n{\n\tint N = vec.size();\n\tvector<int> count(k+1, 0); //记录的是这个数应该的起始位置\n\tfor(int i = 0; i < N; ++i)\n\t\tcount[vec[i]+1]++;\n\tfor(int d = 0; d < k; ++d)\n\t\tcount[d+1] += count[d];\n\tfor(int i = 0; i < N; ++i)\n\t\taux[count[vec[i]]++] = vec[i];\n}\n\nvoid countingSort(vector<int>& vec)\n{\n int k = 10000;\n vector<int> aux(vec.size(), 0);\n countingSort(vec, aux, k);\n for(int i = 0; i < vec.size(); ++i)\n vec[i] = aux[i];\n}\n\nvoid radixSort(vector<int>& vec, int d) //对5位数的整数进行排序\n{\n for(int i = d-1; i >= 0; --i)\n {\n\n }\n}\n\nvoid radixSort(vector<int>& vec)\n{\n radixSort(vec, 5);\n}\n"
},
{
"alpha_fraction": 0.4683052897453308,
"alphanum_fraction": 0.5032341480255127,
"avg_line_length": 18.820512771606445,
"blob_id": "ef139103837f127e764ae7220b7224ba2f476ed3",
"content_id": "0639df78c893274e1bea5e53ce3f311aea93b959",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Java",
"length_bytes": 1546,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 78,
"path": "/nothing/Matrix.java",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "import java.util.Arrays;\n\npublic class Matrix\n{\n\tpublic static double dot(double[] x, double [] y)\n\t{\n\t\tdouble ans = 0.0;\n\t\tfor(int i=0; i<x.length; ++i)\n\t\t\tans += x[i]*y[i];\n\t\treturn ans;\n\t}\n\n\tpublic static double[][] mult(double[][] a, double[][] b)\n\t{\n\t\tint N = a.length;\n\t\tint M = b[0].length;\n\t\tint Q = b.length;\n\t\tdouble[][] c = new double[N][M];\n\n\t\tfor(int i=0; i< N; ++i)\n\t\t\tfor(int j=0; j<M; ++j)\n\t\t\t\tfor(int k=0; k<Q; ++k)\n\t\t\t\t\tc[i][k] = a[i][k] * b[k][j];\n\t\treturn c;\n\t}\n\n\tpublic static double[][] transpose(double[][] a)\n\t{\n\t\tint N = a.length, M = a[0].length;\n\t\tdouble [][]t = new double[N][M];\n\n\t\tfor(int i=0; i<N; ++i)\n\t\t\tfor(int j=0; j<M; ++j)\n\t\t\t\tt[j][i] = a[i][j];\n\t\treturn t;\n\t}\n\n\tpublic static double[] mult(double[][] a, double[] x)\n\t{\n\t\tint N = a.length, M = x.length;\n\t\tdouble[] b = new double[N];\n\n\t\tfor(int i=0; i<N; ++i)\n\t\t{\n\t\t\tb[i] = 0.0;\n\t\t\tfor(int j=0; j<M; ++j)\n\t\t\t\tb[i] += a[i][j]*x[j];\n\t\t}\n\t\treturn b;\n\t}\n\n\tpublic static double[] mult(double[] y, double[][]a)\n\t{\n\t\tint N = a.length, M = y.length;\n\t\tdouble[] b = new double[N];\n\n\t\tfor(int i=0; i<N; ++i)\n\t\t{\n\t\t\tb[i] = 0.0;\n\t\t\tfor(int j=0; j<M; ++j)\n\t\t\t\tb[i] += a[i][j]*y[j];\n\t\t}\n\t\treturn b;\n\t}\n\n\tpublic static void main(String[] args)\n\t{\n\t\tdouble[][] matrix_one = {{1,2,3,4},{1,2,3,4},{4,3,2,1},{4,3,5,6}};\n\t\tdouble[][] matrix_two = {{1,2,3,4},{4,3,2,1},{4,5,6,7},{4,3,3,3}};\n\t\tdouble[][] multMatrix = mult(matrix_two, matrix_one);\n\t\tfor(int i=0; i<4; ++i)\n\t\t{\n\t\t\tfor(int j=0; j<4; ++j)\n\t\t\t\tSystem.out.print(multMatrix[i][j]+\" \");\n\t\t\tSystem.out.println();\n\t\t}\n\t}\n}\n"
},
{
"alpha_fraction": 0.7093791365623474,
"alphanum_fraction": 0.7093791365623474,
"avg_line_length": 15.106383323669434,
"blob_id": "f78b267f87fdf7e269ebde8494c525a783dec9f8",
"content_id": "f6aa0be64aad444d4a2483c1843d0d68962e4b0b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 757,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 47,
"path": "/BST_cpp/AVLTree.h",
"repo_name": "dashahe/algorithm",
"src_encoding": "UTF-8",
"text": "#include <iostream>\nusing namespace std;\n\ntypedef int valueType;\n\nclass TreeNode\n{\npublic:\n\tTreeNode(valueType v):\n\t\tleft(nullptr),\n\t\tright(nullptr),\n\t\tval(v) {}\n\npublic:\n\tTreeNode* left;\n\tTreeNode* right;\n\tvalueType val;\n};\n\nclass AVLTree\n{\npublic:\n\tAVLTree(): root(nullptr){}\n\n\tvoid insert(valueType val);\n\tvoid erase(valueType val);\n\tint size();\n\tbool empty();\n\tbool find(valueType val);\n\tvalueType min();\n\n\tvoid preOrder();\n\tvoid midOrder();\n\nprivate:\n\tTreeNode* insert(valueType val, TreeNode* node);\n\tTreeNode* erase(valueType val, TreeNode* node);\n\tTreeNode* find(valueType val, TreeNode* node);\n\tint size(TreeNode* node);\n\tvalueType min(TreeNode* node);\n\n\tvoid preOrder(TreeNode* node);\n\tvoid midOrder(TreeNode* node);\n\nprivate:\n\tTreeNode* root;\n};\n"
}
] | 45 |
CharlesGe129/CS690Ponzi | https://github.com/CharlesGe129/CS690Ponzi | 3656e16643278d00b2b39138d942383cdfd96a72 | 3dc747e49720c77fe1c18f5108d36d30d4cb8101 | 44071edec5a1ad75d28e2324b7a8794ca982106b | refs/heads/master | 2020-04-10T10:48:13.038837 | 2018-12-10T18:27:12 | 2018-12-10T18:27:12 | 160,976,232 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5805755257606506,
"alphanum_fraction": 0.5932853817939758,
"avg_line_length": 36.56756591796875,
"blob_id": "4200a7ca242d1867185e48891c2395135b3bfb84",
"content_id": "49679c14995e452db5a9d4a5aae9f169a4e451f3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4170,
"license_type": "no_license",
"max_line_length": 167,
"num_lines": 111,
"path": "/scripts/import_data.py",
"repo_name": "CharlesGe129/CS690Ponzi",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n --------------------------------------------------------------------------------\n SPADE - Support for Provenance Auditing in Distributed Environments.\n Copyright (C) 2015 SRI International\n This program is free software: you can redistribute it and/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\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 GNU\n General Public License for more details.\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http://www.gnu.org/licenses/>.\n --------------------------------------------------------------------------------\n\n\"\"\"\n\n\n\"\"\"\n\nRun with file '../dataset/ponzi_collection.csv' and '../dataset/non_ponzi_collection.csv' containing the blockchain addresses of each smart contracts\n\nReturns: json files containing all the transactions info of each smart contract\n\n\"\"\"\n\nimport requests\nimport csv\nimport ast\nimport json\n\n\n\nPATH = '../dataset/'\nDB = PATH + 'sm_database/{}.json'\n\n\nclass EthCrawlerNormalTx:\n def __init__(self, addresses, saved_file):\n self.name = \"crawler_nml\"\n self.addresses = addresses\n self.addr_len = len(addresses)\n self.saved_file = saved_file\n self.url_nml_pattern = 'http://api.etherscan.io/api?module=account&action=txlist&address={0}&startblock=0&endblock=99999999&sort=asc&apikey=APIbirthday'\n self.count = 0\n\n def start(self):\n # with open(self.saved_file, 'w') as nml:\n # nml.close()\n [self.crawl(addr) for addr in self.addresses]\n\n def crawl(self, addr):\n self.count += 1\n print(addr + ', progress: ' + str(round(self.count/self.addr_len*100, 2)) + '%')\n while True:\n try:\n url = self.url_nml_pattern.format(addr)\n response = requests.get(url)\n break\n except Exception as e:\n print(\"Error: \")\n print(e)\n with open(self.saved_file, 'a') as f:\n f.write(addr + '\\n')\n f.write(response.text[38:-1] + '\\n')\n\n\nclass EthCrawlerInternalTx:\n def __init__(self, addresses, saved_file):\n self.name = \"crawler_nml\"\n self.addresses = addresses\n self.addr_len = len(addresses)\n self.saved_file = saved_file\n self.url_nml_pattern = 'http://api.etherscan.io/api?module=account&action=txlistinternal&address={0}&startblock=0&endblock=9999999&sort=asc&apikey=APIbirthday'\n self.count = 0\n\n def start(self):\n # with open(self.saved_file, 'w') as int:\n # int.close()\n [self.crawl(addr) for addr in self.addresses]\n\n def crawl(self, addr):\n self.count += 1\n print(addr + ', progress: ' + str(round(self.count/self.addr_len*100, 2)) + '%')\n while True:\n try:\n url = self.url_nml_pattern.format(addr)\n response = requests.get(url)\n break\n except Exception as e:\n print(\"Error: \")\n print(e)\n with open(self.saved_file, 'a') as f:\n f.write(addr + \"\\n\")\n f.write(response.text[38:-1] + '\\n' if response.text[25:27] == 'OK' else '[]\\n')\n\n\nif __name__ == '__main__':\n files = ['ponzi_collection.csv', 'non_ponzi_collection.csv']\n for pz_file in files:\n with open(PATH + pz_file, 'rt') as f:\n csv_data = list(csv.reader(f))\n addr_index = 2 if pz_file.startswith('ponzi') else 0\n addresses = [line[addr_index].split(',')[0].split(' ')[0] for line in csv_data[1:]]\n saved_file = DB.format('normal' if pz_file.startswith('ponzi') else 'normal_np')\n EthCrawlerNormalTx(addresses, saved_file).start()\n saved_file = DB.format('internal' if pz_file.startswith('ponzi') else 'internal_np')\n EthCrawlerInternalTx(addresses, saved_file).start()\n"
},
{
"alpha_fraction": 0.5144596695899963,
"alphanum_fraction": 0.534246563911438,
"avg_line_length": 23.33333396911621,
"blob_id": "bece93450567531b68de7f2b4c5e0a69a4ce7217",
"content_id": "4d992b9bb52d02c31de69bc708262952c2963228",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 657,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 27,
"path": "/scripts/test.py",
"repo_name": "CharlesGe129/CS690Ponzi",
"src_encoding": "UTF-8",
"text": "import os\nimport ast\nimport json\n\nPATH = '../Marion_files/sm_database/'\n\nindex = 88\npay_in = 0\npay_out = 0\ncontract_hash = a.op[0][index]\nfor tx in a.tr_dico[0][index][0]:\n if tx['from'] in [contract_hash, '']:\n pay_out += 1\n elif tx['to'] in [contract_hash, '']:\n pay_in += 1\n else:\n print(f\"con={contract_hash}, in={tx['from']}, out={tx['to']}\")\n\nfor tx in a.tr_dico[0][index][1]:\n if tx['from'] in [contract_hash, '']:\n pay_out += 1\n elif tx['to'] in [contract_hash, '']:\n pay_in += 1\n else:\n print(f\"con={contract_hash}, in={tx['from']}, out={tx['to']}\")\n\nprint(f\"in={pay_in}, out={pay_out}\")\n"
},
{
"alpha_fraction": 0.4584673345088959,
"alphanum_fraction": 0.47521349787712097,
"avg_line_length": 41.93809509277344,
"blob_id": "057efe53b16f8698850a480123e1ee5b21a3b183",
"content_id": "3b045c854da5eacf3045c489b365e1faeb6b1f71",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9017,
"license_type": "no_license",
"max_line_length": 123,
"num_lines": 210,
"path": "/scripts/open_data.py",
"repo_name": "CharlesGe129/CS690Ponzi",
"src_encoding": "UTF-8",
"text": "import ast\nimport time\nimport json\nimport os\nimport src.tools as tl\n\n\nOPCODES = ['SWAP8', 'DUP11', 'DUP14', 'SWAP10', 'DUP15', 'LOG2', 'INVALID', 'SWAP9', 'SWAP5', 'SWAP12', 'SWAP16',\n 'DUP9', 'LOG1', 'DUP12', 'SWAP11', 'SWAP2', 'MSTORE8', 'SWAP14', 'DUP13', 'POP', 'DUP8','DUP7',\n 'DUP3', 'DUP4', 'MSTORE', 'SWAP3', 'CODECOPY', 'JUMP', 'DUP5', 'SWAP13', 'STOP', 'CALLDATACOPY', 'SWAP7',\n 'SWAP1', 'SWAP6', 'RETURN', 'DUP6', 'SWAP4', 'REVERT', 'SELFDESTRUCT', 'DUP10', 'DUP16', 'JUMPI',\n 'SSTORE', 'PUSH', 'LOG3', 'LOG4', 'Missing', 'SWAP15', 'DUP1&2']\n\n\nclass EtherDataToFreqAndTrDisc:\n def __init__(self):\n self.cur_time = time.clock()\n self.paths = dict()\n self.op = list()\n self.opcodes = list()\n\n def define_path(self):\n self.cur_time = time.clock()\n print(\"EtherDataToFreqAndTrDisc: define variables...\")\n self.paths['db'] = '../dataset/'\n\n self.paths['database_nml'] = self.paths['db'] + 'sm_database/normal.json'\n self.paths['database_int'] = self.paths['db'] + 'sm_database/internal.json'\n self.paths['database_op'] = self.paths['db'] + 'ponzi/op_count/'\n\n self.paths['database_nml_np'] = self.paths['db'] + 'sm_database/normal_np.json'\n self.paths['database_int_np'] = self.paths['db'] + 'sm_database/internal_np.json'\n self.paths['database_op_np'] = self.paths['db'] + 'non_ponzi/op_count/'\n\n # # For original data Marion_files\n # self.paths['db'] = '../dataset/sm_database/'\n # self.paths['database_op'] = self.paths['db'] + 'opcode/opcodes_count/'\n # self.paths['database_op_np'] = self.paths['db'] + 'opcode_np/opcode_count/bytecode_np/'\n\n self.cur_time = tl.compute_time(self.cur_time)\n\n def load_op(self):\n self.op = [\n [fname.split('.csv')[0] for fname in os.listdir(self.paths['database_op']) if fname.endswith('.csv')],\n [fname.split('.csv')[0] for fname in os.listdir(self.paths['database_op_np']) if fname.endswith('.csv')]\n ]\n print(\"op length: \" + str(len(self.op[0])) + \", \" + str(len(self.op[1])))\n self.opcodes = OPCODES\n\n def gen_op_counts(self):\n opcode_paths = [self.paths['database_op'].replace('op_count', 'opcode'),\n self.paths['database_op_np'].replace('op_count', 'opcode')]\n output_path = [self.paths['database_op'], self.paths['database_op_np']]\n i = 0\n for op_index in range(2):\n for filename in os.listdir(opcode_paths[op_index]):\n i += 1\n print(f\"{i}, {filename}\")\n if not filename.endswith('.json'):\n continue\n self.gen_one_op_count(opcode_paths[op_index] + filename,\n output_path[op_index] + filename.replace('.json', '.csv'))\n\n @staticmethod\n def gen_one_op_count(data_path, output_path):\n codes = [0 for each in OPCODES]\n with open(data_path) as f_opcode:\n while True:\n line = f_opcode.readline()\n if not line:\n break\n if line[0] in ['#', ':', '\\n']:\n continue\n if '\\t' in line:\n code = line.split('\\t')[1].split('(')[0].strip('\\n')\n elif line.startswith('0x') and ' ' in line:\n code = line.split(' ')[1].split('(')[0].strip('\\n')\n if code in ['DUP1', 'DUP2']:\n code = 'DUP1&2'\n elif code.startswith('Missing'):\n code = 'Missing'\n if code not in OPCODES:\n print(code)\n else:\n codes[OPCODES.index(code)] += 1\n with open(output_path, 'w') as f_count:\n f_count.write('\\n'.join(\n [OPCODES[i] + ',' + str(codes[i]) for i in range(len(OPCODES)) if codes[i] != 0]))\n\n def gen_op_freq(self):\n print(\"EtherDataToFreqAndTrDisc: generating op_freq.json\")\n op_freq = [[], []]\n for i in range(2):\n db_path = self.paths['database_op'] if i == 0 else self.paths['database_op_np']\n for addr in self.op[i]:\n with open(db_path + addr + '.csv', 'r') as f:\n raw = f.readlines()\n res = [0 for i in range(len(self.opcodes))]\n if len(raw) > 1:\n tot = 0\n for opcode in raw:\n opcode = opcode.strip('\\n')\n code = opcode.split(',')[0]\n count = int(opcode.split(',')[1])\n tot += count\n res[self.opcodes.index(code)] += count\n tot = tot if len(raw) > 1 else 1\n res = [x / tot for x in res]\n op_freq[i].append(res)\n\n print(f\"{len(op_freq[0])}, {len(op_freq[1])}\")\n self.cur_time = tl.compute_time(self.cur_time)\n with open(self.paths['db'] + 'op_freq.json', 'w') as outfile:\n outfile.write(json.dumps(op_freq))\n print('op_freq serialized')\n\n def gen_tr_dico(self):\n # tr_dico is ordered by op[]\n # tr_dico[p=0, np=1][# of Contracts][nml=0, int=1][list of TXs in nml.json] = {'blockNumber': xxx} = dict()\n tr_dico = [[[0, 0] for i in range(len(self.op[0]))], [[0, 0] for i in range(len(self.op[1]))]]\n file_paths = ['database_nml', 'database_int', 'database_nml_np', 'database_int_np']\n op_indices = [0, 0, 1, 1]\n nml_int_indices = [0, 1, 0, 1]\n for i in range(4):\n tr_index = op_indices[i]\n cur_op = self.op[tr_index]\n nml_int_index = nml_int_indices[i]\n print(\"loading \" + file_paths[i])\n count = 0\n with open(self.paths[file_paths[i]]) as f:\n while True:\n count += 1\n if count % 100 == 0:\n print(count)\n contract_hash = f.readline().strip('\\n')\n list_line = f.readline()\n if not contract_hash:\n break\n if contract_hash not in cur_op:\n continue\n tr_dico[tr_index][cur_op.index(contract_hash)][nml_int_index] = ast.literal_eval(list_line.strip('\\n'))\n self.cur_time = tl.compute_time(self.cur_time)\n self.save_tr_dico(tr_dico)\n\n def save_tr_dico(self, tr_dico):\n for i in range(len(self.op[1])//500 + 1):\n with open(self.paths['db'] + 'tr_dico_nonponzi' + str(i) + '.json', 'w') as f:\n f.write(json.dumps(tr_dico[1][i*500:(i+1)*500]))\n print('serialized #' + str(i) + ' tr_dico from ' + str(i*500) + ' to ' + str((i+1)*500))\n with open(self.paths['db'] + 'tr_dico_ponzi.json', 'w') as f:\n f.write(json.dumps(tr_dico[0]))\n\n def gen_op_freq_origin(self):\n op_freq = [[], []]\n for add in self.op[0]:\n with open(self.paths['database_op'] + add + '.json', 'r') as f:\n # print(self.paths['database_op'] + add + '.json')\n raw = f.readlines()\n res = [0 for i in range(len(self.opcodes))]\n if len(raw) > 1:\n tot = 0\n for opcode in raw:\n # count = number % 10 instead of number?\n count = float(opcode[3])\n tot += count\n res[self.opcodes.index(opcode[5:-1])] = count\n else:\n tot = 1\n res = [x / tot for x in res]\n op_freq[0].append(res)\n print(res)\n\n # non ponzi instances\n\n for add in self.op[1]:\n with open(self.paths['database_op_np'] + add + '.json', 'r') as f:\n raw = f.readlines()\n res = [0 for i in range(len(self.opcodes))]\n if len(raw) > 1:\n tot = 0\n for opcode in raw:\n # count = number % 10 instead of number?\n count = float(opcode[3])\n tot += count\n res[self.opcodes.index(opcode[5:-1])] = count\n else:\n tot = 1\n\n res = [x / tot for x in res]\n op_freq[1].append(res)\n print(res)\n\n t2 = tl.compute_time(self.cur_time)\n\n with open(self.paths['db'] + 'op_freq.json', 'w') as outfile:\n outfile.write(json.dumps(op_freq))\n print('op_freq serialized')\n\n def start(self):\n self.define_path()\n self.gen_op_counts()\n self.load_op()\n # self.gen_op_freq_origin()\n self.gen_op_freq()\n # self.gen_tr_dico()\n\n\nif __name__ == '__main__':\n a = EtherDataToFreqAndTrDisc()\n a.start()\n"
},
{
"alpha_fraction": 0.6081720590591431,
"alphanum_fraction": 0.6292473077774048,
"avg_line_length": 36.51612854003906,
"blob_id": "21f728721ce6f615096625959219a1f9adf2b9d2",
"content_id": "804dc89ae4e6c6f89b5034a1bb638ba8bcdf2931",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2325,
"license_type": "no_license",
"max_line_length": 142,
"num_lines": 62,
"path": "/scripts/import_bcode.py",
"repo_name": "CharlesGe129/CS690Ponzi",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n --------------------------------------------------------------------------------\n SPADE - Support for Provenance Auditing in Distributed Environments.\n Copyright (C) 2015 SRI International\n This program is free software: you can redistribute it and/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\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 GNU\n General Public License for more details.\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http://www.gnu.org/licenses/>.\n --------------------------------------------------------------------------------\n\n\"\"\"\n\nfrom web3 import Web3\nimport csv\n\n#sm_file = 'Smart_Contract_Addresses.list'\nsm_file = 'sm_add_nponzi.csv'\npath = '/Users/charles/charles/university/Master Project/go-ethereum/analysis_tool_python/SmartPonziDetection/'\ndatabase_bcode = path + 'dataset/'\n\nweb3 = Web3(Web3.HTTPProvider('https://mainnet.infura.io/TO1X2JTG8k9PiaYd0iQr'))\n\n\n# with open(path + sm_file, 'rt') as f:\n# truc = csv.reader(f)\n# add = list(truc)\n#\n#\n# addresses = [pk[:42] for pklist in add for pk in pklist]\nwith open(database_bcode + 'non_ponzi_collection.csv') as f:\n truc = csv.reader(f)\n csv_file = list(truc)\n\n\naddresses = [line[0].split('(')[0].strip() for line in csv_file if line[0] != 'addr']\n\n\ni = 0\nfor ad in addresses:\n code = repr(web3.eth.getCode(web3.toChecksumAddress(ad)))[12:-2]\n if code:\n i += 1\n # print(str(i) + \": \" + ad)\n with open(database_bcode + 'non_ponzi_bcode/' + ad + '.json', 'w') as f:\n f.write(code)\n f.close()\n else:\n print(ad)\n #Disasemble\n #print(ad)\n #os.system('cat /Users/e31989/Documents/sm_database/bytecode/' + ad +'.json | evmdis > /Users/e31989/Documents/features/' + ad + '.json' )\n \n#for /r %i in (*.json); do cat \"%i\" | evmdis > \"/Users/e31989/Documents/features/$~ni.json\"; done\n#for %i in (*.json); do cat \"%i\" | evmdis > \"/Users/e31989/Documents/features/$~ni.json\"; done"
},
{
"alpha_fraction": 0.5099555850028992,
"alphanum_fraction": 0.5232022404670715,
"avg_line_length": 42.09928894042969,
"blob_id": "53d109eb9c7aea72828100beda43a7dc1a871622",
"content_id": "08ca6e0a24a5a84ee57b3a8ab9524a82e8df2fae",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 12154,
"license_type": "no_license",
"max_line_length": 144,
"num_lines": 282,
"path": "/scripts/features.py",
"repo_name": "CharlesGe129/CS690Ponzi",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\n --------------------------------------------------------------------------------\n SPADE - Support for Provenance Auditing in Distributed Environments.\n Copyright (C) 2015 SRI International\n This program is free software: you can redistribute it and/or\n modify it under the terms of the GNU General Public License as\n published by the Free Software Foundation, either version 3 of the\n License, or (at your option) any later version.\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 GNU\n General Public License for more details.\n You should have received a copy of the GNU General Public License\n along with this program. If not, see <http://www.gnu.org/licenses/>.\n --------------------------------------------------------------------------------\n\n\"\"\"\n\n\nimport numpy as np\nimport pandas as pd\nimport src.tools as tl\nimport os\nfrom arff2pandas import a2p\nfrom scipy import stats\nimport json\nimport time\nfrom sklearn import preprocessing\nimport matplotlib.pyplot as plt\nfrom src.open_data import OPCODES\n\n\nclass Feature:\n def __init__(self):\n self.cur_time = time.clock()\n self.paths = dict()\n self.op = list()\n self.opcodes = list()\n self.J = 100000\n self.tr_dico = list()\n self.size_info = list()\n self.op_freq = dict()\n self.ft_names = list()\n self.ft = list()\n self.ft_opcodes = list()\n self.ft_basic = list()\n self.df = None\n self.df_opcodes = None\n self.df_basic = None\n\n def start(self):\n self.define_path()\n self.load_op()\n self.load_tr_dico()\n self.compute_feature()\n self.df = self.create_pandas_dataframe(self.ft, self.ft_names + self.opcodes)\n self.df_opcodes = self.create_pandas_dataframe(self.ft_opcodes, ['ponzi'] + self.opcodes)\n self.df_basic = self.create_pandas_dataframe(self.ft_basic, self.ft_names)\n self.dump_arff()\n\n def define_path(self):\n print(\"Feature: define variable and load data\")\n self.paths['db'] = '../dataset/'\n\n self.paths['database_nml'] = self.paths['db'] + 'normal.json'\n self.paths['database_int'] = self.paths['db'] + 'internal.json'\n self.paths['database_op'] = self.paths['db'] + 'ponzi/op_count/'\n\n self.paths['database_nml_np'] = self.paths['db'] + 'normal_np.json'\n self.paths['database_int_np'] = self.paths['db'] + 'internal_np.json'\n self.paths['database_op_np'] = self.paths['db'] + 'non_ponzi/op_count/'\n\n # # For original data Marion_files\n # self.paths['db'] = '../dataset/sm_database/'\n # self.paths['database_op'] = self.paths['db'] + 'opcode/opcodes_count/'\n # self.paths['database_op_np'] = self.paths['db'] + 'opcode_np/opcode_count/bytecode_np/'\n\n self.cur_time = tl.compute_time(self.cur_time)\n pass\n\n def load_op(self):\n # op[p=0, np=1][index] = contract_address\n print(\"Loading op, opcodes, op_freq, size_info...\")\n self.op = [\n [fname.split('.csv')[0] for fname in os.listdir(self.paths['database_op']) if fname.endswith('.csv')],\n [fname.split('.csv')[0] for fname in os.listdir(self.paths['database_op_np']) if fname.endswith('.csv')]\n ]\n self.opcodes = OPCODES\n for i in self.op[0]:\n self.size_info.append(os.path.getsize(self.paths['db'] + 'ponzi/bcode/' + i + '.json'))\n for i in self.op[1]:\n self.size_info.append(os.path.getsize(self.paths['db'] + 'non_ponzi/bcode/' + i + '.json'))\n with open(self.paths['db'] + 'op_freq.json', 'rb', ) as f:\n self.op_freq = json.loads(f.read())\n self.cur_time = tl.compute_time(self.cur_time)\n\n def load_tr_dico(self):\n # tr_dico[p=0, np=1][# of Contracts][nml=0, int=1][list of TXs in nml.json] = {'blockNumber': xxx} = dict()\n tr_dico = [[], []]\n with open(self.paths['db'] + 'tr_dico_ponzi.json', 'rb') as f:\n tr_dico[0] = json.loads(f.read())\n\n with open(self.paths['db'] + 'tr_dico_nonponzi0.json', 'rb') as f:\n tr_dico[1] = json.loads(f.read())\n print(\"Reading tr_dico: \" + str(len(tr_dico[1])))\n for i in range(1, len(self.op[1])//500 + 1):\n with open(self.paths['db'] + 'tr_dico_nonponzi' + str(i) + '.json', 'rb') as f:\n tr_dico[1] += json.loads(f.read())\n print(\"Reading tr_dico: \" + str(len(tr_dico[1])))\n self.tr_dico = tr_dico\n self.cur_time = tl.compute_time(self.cur_time)\n\n def compute_feature(self):\n print(\"computing features for ponzi...\")\n self.ft_names = [# 'addr',\n 'ponzi', 'nbr_tx_in', 'nbr_tx_out', 'Tot_in', 'Tot_out',\n 'num_paid_in_addr', 'num_paid_out_addr', 'overlap_in_out_addr',\n 'mean_in', 'mean_out', 'sdev_in', 'sdev_out', 'gini_in', 'gini_out', 'avg_time_btw_tx',\n 'gini_time_out', 'lifetime']\n # ideas: lifetime,number of active days, max/min/avg delay between in and out, max/min balance\n self.cal_advanced_features()\n\n def cal_advanced_features(self):\n ft = []\n ft_opcodes = []\n ft_basic = []\n len_op = [len(self.op[0]), len(self.op[1])]\n for tr_index in range(2):\n print('computing features for ' + ('ponzi' if tr_index == 0 else 'non ponzi'))\n for i in range(len_op[tr_index]):\n # for each contract\n val_in = []\n val_out = []\n time_in = []\n time_out = []\n pay_in = 0\n pay_out = 0\n addr_in = set()\n addr_out = set()\n birth = float(self.tr_dico[tr_index][i][0][0]['timeStamp'])\n for tx in self.tr_dico[tr_index][i][0] + self.tr_dico[tr_index][i][1]:\n # for each tx of that contract\n contract_hash = self.op[tr_index][i]\n timestamp = float(tx['timeStamp'])\n if (timestamp - birth) / (60 * 60 * 24) <= self.J:\n self.cal_value_time_in_out({'tx': tx, 'contract_hash': contract_hash, 'val_in': val_in,\n 'val_out': val_out, 'time_in': time_in, 'time_out': time_out,\n 'timestamp': timestamp})\n (pay_in, pay_out) = self.cal_addr_in_out({'tx': tx, 'contract_hash': contract_hash,\n 'pay_in': pay_in, 'pay_out': pay_out, 'addr_in': addr_in,\n 'addr_out': addr_out})\n num_overlap_addr = len(addr_in.intersection(addr_out))\n res = tl.basic_features({'ponzi': 'ponzi' if tr_index == 0 else 'non_ponzi',\n 'val_in': np.asarray(val_in), 'val_out': np.asarray(val_out),\n 'time_in': np.asarray(time_in), 'time_out': np.asarray(time_out),\n 'pay_in': pay_in, 'pay_out': pay_out, 'num_overlap_addr': num_overlap_addr})\n ft.append(np.concatenate((res, np.asarray(self.op_freq[tr_index][i], dtype='float64'))))\n ft_opcodes.append(np.concatenate((np.asarray(['ponzi' if tr_index == 0 else 'non_ponzi']),\n np.asarray(self.op_freq[tr_index][i], dtype='float64'))))\n ft_basic.append(res)\n self.cur_time = tl.compute_time(self.cur_time)\n self.ft = ft\n self.ft_opcodes = ft_opcodes\n self.ft_basic = ft_basic\n\n @staticmethod\n def cal_value_time_in_out(args):\n if args['tx']['from'] in ['', args['contract_hash']]:\n args['val_out'].append(float(args['tx']['value']))\n args['time_out'].append(args['timestamp'])\n else:\n args['val_in'].append(float(args['tx']['value']))\n args['time_in'].append(args['timestamp'])\n\n @staticmethod\n def cal_addr_in_out(args):\n tx = args['tx']\n contract_hash = args['contract_hash']\n if tx['from'] in [contract_hash, '']:\n args['pay_out'] += 1\n args['addr_out'].add(tx['to'])\n if tx['to'] in [contract_hash, '']:\n args['pay_in'] += 1\n args['addr_in'].add(tx['from'])\n return args['pay_in'], args['pay_out']\n\n def create_pandas_dataframe(self, ft, ft_names):\n print(\"Creating pandas dataframe...\")\n columns = [s + '@NUMERIC' for s in ft_names]\n columns[0] = \"ponzi@{ponzi,non_ponzi}\"\n df = pd.DataFrame(data=ft, columns=columns)\n df['size_info@NUMERIC'] = self.size_info\n # data.loc[:, data.columns != columns[0]] = data.loc[:, data.columns != columns[0]].astype(np.float64)\n self.cur_time = tl.compute_time(self.cur_time)\n return df\n\n # deprecated\n def get_rid_of_outliers(self, columns):\n print(\"Getting rid of outliers for the non ponzi instances\")\n out_index = 3\n \"\"\"\n min_max_scaler = preprocessing.StandardScaler()\n dum = df.drop(df[df[columns[0]] == 'ponzi'].index)\n df_out = dum[(np.abs(stats.zscore(min_max_scaler.transform(dum.drop(labels=[columns[0]]+columns[n:],axis=1)))) < out_index).all(axis=1)]\n df_out = df_out.append(df.drop(df[df[columns[0]] == 'non_ponzi'].index))\n\n \"\"\"\n dum = self.df.drop(self.df[self.df[columns[0]] == 'ponzi'].index)\n df_out = dum[(\n np.abs(stats.zscore(\n np.asarray(dum.drop(labels=[columns[0]] + columns[len(self.ft_names):], axis=1), dtype='float64'))) < out_index).all(\n axis=1)]\n self.df_out = df_out.append(self.df.drop(self.df[self.df[columns[0]] == 'non_ponzi'].index))\n self.cur_time = tl.compute_time(self.cur_time)\n\n def dump_arff(self):\n print(\"Dumping into arff files ...\")\n with open(self.paths['db'] + 'models/PONZI_' + str(self.J) + '.arff', 'w') as f:\n a2p.dump(self.df, f)\n with open(self.paths['db'] + 'models/PONZI_opcodes_' + str(self.J) + '.arff', 'w') as f:\n a2p.dump(self.df_opcodes, f)\n with open(self.paths['db'] + 'models/PONZI_basic_' + str(self.J) + '.arff', 'w') as f:\n a2p.dump(self.df_basic, f)\n self.cur_time = tl.compute_time(self.cur_time)\n\n def remaining_code(self):\n pass\n '''\n plt.hist(df['avg_time_btw_tx@NUMERIC'][145:].astype('float32')/(60*60), bins = 15)\n plt.hist(df['avg_time_btw_tx@NUMERIC'][:145].astype('float32')/(60*60), bins = 15)\n \n plt.xlabel('Delay between transactions (hours)')\n plt.ylabel('number of instances')\n plt.title('Delay between transacstions histogram for non ponzi')\n plt.savefig(path + 'delay_histo.png')\n '''\n\n def nml_int_file_format(self):\n \"\"\"\n normal.json : {\n (0)'blockNumber': 'n',\n (1)'timeStamp': 'n'\n (2) 'hash': '0x..',\n (3) 'nonce': 'n',\n (4)'blockHash': '0x..e6',\n (5)'transactionIndex': '1',\n (6)'from': '0x..',\n (7)'to': '0x..',\n (8)'value': 'n',\n (9)'gas': 'n',\n (10)'gasPrice': 'n',\n (11)'isError': '0',\n (12)'txreceipt_status': '',\n (13)'input': '0x..',\n (14)'contractAddress': '0x..',\n (15)'cumulativeGasUsed': 'n',\n (16)'gasUsed': 'n,\n (17)'confirmations': 'n'}\n\n internal.json :{\n (0)'blockNumber',\n (1)'timeStamp',\n (2)'hash',\n (3)'from',\n (4)'to',\n (5)'value',\n (6)'contractAddress',\n (7)'input',\n (8)'type',\n (9)'gas',\n (10)'gasUsed',\n (11)'traceId',\n (12)'isError',\n (13)'errCode'}\n\n value = 10**18 ETH value\n \"\"\"\n\nif __name__ == '__main__':\n Feature().start()\n"
},
{
"alpha_fraction": 0.7634408473968506,
"alphanum_fraction": 0.7715053558349609,
"avg_line_length": 27.538461685180664,
"blob_id": "66be41be1e1a5784455f979c415bc60e73be2089",
"content_id": "c1bbe2da3776f73b410da0614d665395bbe85444",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 372,
"license_type": "no_license",
"max_line_length": 99,
"num_lines": 13,
"path": "/README.md",
"repo_name": "CharlesGe129/CS690Ponzi",
"src_encoding": "UTF-8",
"text": "# CS690Ponzi by Charles(Yunjie Ge)\n\n**Source code from \"Marion_files_origin.tar\"**\n\n**Here's the oroginal README:**\n\n**fork from rionma/smart-ponzi-detection: https://github.com/rionma/smart-ponzi-detection**\n\n# Detecting Ponzi schemes on Ethereum\nData mining model enabling early detection of Ponzi schemes implementation on Ethereum's blockchain\n\n\n# smart-ponzi-detection\n\n"
}
] | 6 |
duminhui/fontsub | https://github.com/duminhui/fontsub | 0fa6e3a4efb9a730b07c6cd9484ebcd96742a2e6 | 60ff599fd0090cf6c4ce80badecbbce35c9f57fb | 36e3b2f54c4d4605943a7f0f6cf942aff5137b8e | refs/heads/master | 2020-05-18T12:10:36.793744 | 2014-05-22T02:59:54 | 2014-05-22T02:59:54 | 20,045,448 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.38461539149284363,
"alphanum_fraction": 0.6153846383094788,
"avg_line_length": 12,
"blob_id": "9785f0cf37ba8a7939aca32221b593a10c0b4038",
"content_id": "1d4065ed06e7d37128e76fad2183e666047e2019",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 13,
"license_type": "no_license",
"max_line_length": 12,
"num_lines": 1,
"path": "/requirements.txt",
"repo_name": "duminhui/fontsub",
"src_encoding": "UTF-8",
"text": "web.py==0.36\n"
},
{
"alpha_fraction": 0.6306769251823425,
"alphanum_fraction": 0.637532114982605,
"avg_line_length": 20.218181610107422,
"blob_id": "14e2b595d38ef046248d42162f29a0e544533681",
"content_id": "74a89600efa78f6482990db533bc9091ee5d5cb1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1171,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 55,
"path": "/index.py",
"repo_name": "duminhui/fontsub",
"src_encoding": "UTF-8",
"text": "#-*- coding:utf-8 -*-\n\nimport web\nimport json\nimport sys\nimport os\nfrom fontTools import subset\nfrom bae.core.wsgi import WSGIApplication\n\nurls = (\n '/(.*)', 'generate'\n)\n\nBUF_SIZE = 262144\n\n#app_root = os.path.dirname(_file_)\n#sys.path.insert(0, app_root)\n#templates_root = os.path.join(app_root, 'templates')\n#render = web.template.render(templates_root)\napp = web.application(urls, globals()).wsgifunc()\n\nclass generate: \n\tdef GET(self, name):\n\t\t#data = json.loads(web.data())\n\t\tname = \"fangzheng.TTF\"\n\t\tdata = \"--text=我们\"\n\t\targ = [name,data]\n\t\t#fontTools.subset.main(arg)\n\t\tsubset.main(arg)\n\t\toutputFile = \"/tmp/\" + name + \".subset\"\n\t\tif (os.path.isfile(outputFile)):\n\t\t\ttry:\n\t\t\t\tf = open(outputFile, \"rb\")\n\t\t\t\tweb.header('Content-Type','application/octet-stream')\n\t\t\t\tweb.header('Content-disposition','attachment; filename=%s.dat' % outputFile)\n\t\t\t\twhile True:\n\t\t\t\t\tc = f.read(BUF_SIZE)\n\t\t\t\t\tif c:\n\t\t\t\t\t\tyield c\n\t\t\t\t\telse:\n\t\t\t\t\t\tbreak\n\t\t\texcept Exception, e:\n\t\t\t\tyield e\n\t\t\t\t#yield 'Error when read font file'\n\t\t\tfinally:\n\t\t\t\tif f:\n\t\t\t\t\tf.close()\n\t\t\t#return \"success\"\n\t\t#else:\n\t\t\t#return \"fail\"\n\t\t\n\t\t#return \"yes\" \n\n\napplication = WSGIApplication(app)\n"
},
{
"alpha_fraction": 0.7101449370384216,
"alphanum_fraction": 0.7855072617530823,
"avg_line_length": 85.25,
"blob_id": "43ef9e6e307e20c460af36a3b46f1c7da02fa754",
"content_id": "4c1f9a1ca81048bb017f3e2fb9643d95f0513f92",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 345,
"license_type": "no_license",
"max_line_length": 327,
"num_lines": 4,
"path": "/README.md",
"repo_name": "duminhui/fontsub",
"src_encoding": "UTF-8",
"text": "fontsub\n=======\n\nA solution for subseting CJK web fonts to make them easily used on web design based on [fontTools](https://github.com/behdad/fonttools) [ebde545](https://github.com/behdad/fonttools/commit/ebde5454e509ca68fe5647ae9b45fbfdc6480159). Only for ttf now. It can be deployed on any Web Server, which support WSGI. BAE is recommanded.\n"
}
] | 3 |
take-o20/geo_django | https://github.com/take-o20/geo_django | c2c835610cb1662a84524bb5cb3a4714934e07a9 | d701a51e7413f76cc1bededc8cffcf1843dd67c1 | d18c7a48c88129b5303d01694c0c1670881bb1ac | refs/heads/master | 2022-12-13T12:40:02.039493 | 2020-09-07T16:40:07 | 2020-09-07T16:40:07 | 293,580,705 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7245950102806091,
"alphanum_fraction": 0.7304860353469849,
"avg_line_length": 37.79999923706055,
"blob_id": "527c1ad21fa2079fc5a59f693d32c9485c58250d",
"content_id": "b37624a00fb52461f9e3b1c791ce98ced8727937",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1358,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 35,
"path": "/geodjango/geodjango/urls.py",
"repo_name": "take-o20/geo_django",
"src_encoding": "UTF-8",
"text": "\"\"\"geodjango URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/2.2/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: path('', views.home, name='home')\nClass-based views\n 1. Add an import: from other_app.views import Home\n 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Import the include() function: from django.urls import include, path\n 2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))\n\"\"\"\nfrom django.contrib.gis import admin\nfrom django.urls import path, include\nfrom rest_framework.routers import DefaultRouter\n\nfrom world.views import BorderViewSet, SchoolViewSet, FacilityViewSet, BusstopViewSet\n\nfrom world.views import index, GeojsonAPIView\nrouter = DefaultRouter()\nrouter.register('border', BorderViewSet)\nrouter.register('school', SchoolViewSet)\nrouter.register('facility', FacilityViewSet)\nrouter.register('busstop', BusstopViewSet)\n\nurlpatterns = [\n path('admin/', admin.site.urls),\n path('api/', include(router.urls)),\n path('', index, name='world_index'),\n path('world/geojson/', GeojsonAPIView.as_view(), name='geojson_view'),\n path('accounts/', include('django.contrib.auth.urls')),\n]\n"
},
{
"alpha_fraction": 0.3613733947277069,
"alphanum_fraction": 0.5639485120773315,
"avg_line_length": 42.185184478759766,
"blob_id": "990bcbc390084849f905670db2e31df6ffa361eb",
"content_id": "93fc9e16ef9ef03f01d540f5442ea98f20fd2348",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1165,
"license_type": "no_license",
"max_line_length": 122,
"num_lines": 27,
"path": "/geodjango/world/serializers.py",
"repo_name": "take-o20/geo_django",
"src_encoding": "UTF-8",
"text": "from rest_framework import serializers\nfrom .models import Border, School, Facility, Busstop\n\nclass BorderSerializer(serializers.ModelSerializer):\n class Meta:\n model = Border\n fields = ('__all__')\n\nclass SchoolSerializer(serializers.ModelSerializer):\n class Meta:\n model = School\n fields = ('__all__')\n\nclass FacilitySerializer(serializers.ModelSerializer):\n class Meta:\n model = Facility\n fields = ('__all__')\n \nclass BusstopSerializer(serializers.ModelSerializer):\n class Meta:\n model = Busstop\n exclude = (\"p11_003_2\", \"p11_003_3\", \"p11_003_4\", \"p11_003_5\", \"p11_003_6\", \"p11_003_7\", \"p11_003_8\", 'p11_003_9',\n \"p11_003_10\", \"p11_003_11\", \"p11_003_12\", \"p11_003_13\", \"p11_003_14\", \"p11_003_15\", \n \"p11_003_16\", \"p11_003_17\", \"p11_003_18\", 'p11_003_19',\n \"p11_004_2\", \"p11_004_3\", \"p11_004_4\", \"p11_004_5\", \"p11_004_6\", \"p11_004_7\", \"p11_004_8\", \"p11_004_9\",\n \"p11_004_10\", \"p11_004_11\", \"p11_004_12\", \"p11_004_13\", \"p11_004_14\", \"p11_004_15\", \"p11_004_16\", \n \"p11_004_17\", \"p11_004_18\", \"p11_004_19\")"
},
{
"alpha_fraction": 0.7066666483879089,
"alphanum_fraction": 0.7133333086967468,
"avg_line_length": 29,
"blob_id": "ab92446a72348dcfe142998649603ffa696d0e72",
"content_id": "a617a56d974a2ae94d3683fed4a33797cc29b7fc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": true,
"language": "Python",
"length_bytes": 150,
"license_type": "no_license",
"max_line_length": 43,
"num_lines": 5,
"path": "/env/bin/django-admin.py",
"repo_name": "take-o20/geo_django",
"src_encoding": "UTF-8",
"text": "#!/Users/udotakeo/geodjango/env/bin/python3\nfrom django.core import management\n\nif __name__ == \"__main__\":\n management.execute_from_command_line()\n"
},
{
"alpha_fraction": 0.7399576902389526,
"alphanum_fraction": 0.7822409868240356,
"avg_line_length": 30.600000381469727,
"blob_id": "957f43b4bb178e84e5cf0831b92a5b69df9ff8c6",
"content_id": "4ecc3257191c4fb82ece8e71b974a5c62c463195",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 473,
"license_type": "no_license",
"max_line_length": 58,
"num_lines": 15,
"path": "/geodjango/world/admin.py",
"repo_name": "take-o20/geo_django",
"src_encoding": "UTF-8",
"text": "from django.contrib.gis import admin\n\n# Register your models here.\nfrom world.models import Border, School, Facility, Busstop\n\nfrom leaflet.admin import LeafletGeoAdmin\n\nclass BorderAdmin(LeafletGeoAdmin):\n search_fields = ['n03_001', 'n03_003', 'n03_004']\n list_filter = ('n03_003')\n\nadmin.site.register(Border, LeafletGeoAdmin)\nadmin.site.register(School, LeafletGeoAdmin)\nadmin.site.register(Facility, LeafletGeoAdmin)\nadmin.site.register(Busstop, LeafletGeoAdmin)"
},
{
"alpha_fraction": 0.7289613485336304,
"alphanum_fraction": 0.7395754456520081,
"avg_line_length": 33.272727966308594,
"blob_id": "36cfa342da69dead67b3d79bee63aaa38745dbf6",
"content_id": "7bde0e0a9928588299cecfa334cb94d38a8e5c49",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2644,
"license_type": "no_license",
"max_line_length": 146,
"num_lines": 77,
"path": "/geodjango/world/views.py",
"repo_name": "take-o20/geo_django",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render\n\n# Create your views here.\nfrom rest_framework import viewsets\nfrom rest_framework_gis.filters import DistanceToPointFilter, InBBoxFilter\nfrom rest_framework.pagination import PageNumberPagination\n\nfrom .serializers import BorderSerializer, SchoolSerializer, FacilitySerializer, BusstopSerializer\nfrom .models import Border, School, Facility, Busstop\n\nclass MyPagination(PageNumberPagination):\n page_size_query_param = 'page_size'\n\nclass BorderViewSet(viewsets.ModelViewSet):\n queryset = Border.objects.all()\n serializer_class = BorderSerializer\n pagination_class = MyPagination\n filter_backends = (DistanceToPointFilter,)\n distance_filter_field = 'geom'\n distance_filter_convert_meters = True\n\nclass SchoolViewSet(viewsets.ModelViewSet):\n queryset = School.objects.all()\n serializer_class = SchoolSerializer\n pagination_class = MyPagination\n filter_backends = (DistanceToPointFilter,)\n distance_filter_field = 'geom'\n distance_filter_convert_meters = True\n\nclass FacilityViewSet(viewsets.ModelViewSet):\n queryset = Facility.objects.all()\n serializer_class = FacilitySerializer\n pagination_class = MyPagination\n filter_backends = (DistanceToPointFilter,)\n distance_filter_field = 'geom'\n distance_filter_convert_meters = False\n\nclass BusstopViewSet(viewsets.ModelViewSet):\n queryset = Busstop.objects.all()\n serializer_class = BusstopSerializer\n pagination_class = MyPagination\n filter_backends = (DistanceToPointFilter, InBBoxFilter)\n distance_filter_field = bbox_filter_field = 'geom'\n distance_filter_convert_meters = True\n\n\n\nfrom rest_framework.views import APIView\nfrom rest_framework.response import Response\nfrom rest_framework import status\nimport traceback\nimport json\nfrom django.core.serializers import serialize\n\nclass GeojsonAPIView(APIView):\n def get(self, request, *args, **keywords):\n try:\n encjson = serialize('geojson', Border.objects.filter(n03_004=\"中央区\"),srid=4326, geometry_field='geom', fields=('n03_003','n03_004',) )\n result = json.loads(encjson)\n response = Response(result, status=status.HTTP_200_OK)\n except Exception as e:\n traceback.print_exc()\n response = Response({}, status=status.HTTP_404_NOT_FOUND)\n except:\n response = Response({}, status=status.HTTP_404_NOT_FOUND)\n\n return response\n\n\nfrom django.shortcuts import render\nfrom django.contrib.auth.decorators import login_required\n\n@login_required\ndef index(request):\n contexts = {}\n\n return render(request, 'world/index.html', contexts)"
},
{
"alpha_fraction": 0.5860214829444885,
"alphanum_fraction": 0.6612903475761414,
"avg_line_length": 25.619047164916992,
"blob_id": "b6dd2bb4ebf38f5026e41e62b6f38a9844b9142b",
"content_id": "0c1c58e437d79b87eccdccead6ef71032494300a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 604,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 21,
"path": "/geodjango/world/load_elementary_school.py",
"repo_name": "take-o20/geo_django",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nimport os\nfrom django.contrib.gis.utils import LayerMapping\nfrom world.models import School\n\n# Modelとファイルのカラムのマッピング\nmapping = {\n 'a27_001': 'A27_001',\n 'a27_002': 'A27_002',\n 'a27_003': 'A27_003',\n 'a27_004': 'A27_004',\n 'geom' : 'POINT',\n}\n\n# ファイルパス\ngeojson_file = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data', 'elementary_school.geojson'))\n\n# 実行\ndef run(verbose=True):\n lm = LayerMapping(School, geojson_file, mapping, transform=False, encoding='UTF-8')\n lm.save(strict=True, verbose=verbose)"
}
] | 6 |
aquibjamal/hackerrank_solutions | https://github.com/aquibjamal/hackerrank_solutions | 8a9317afc3fc8c6b2f4d0542e5c979ad2c93f849 | bc27ea787743893c60d00c517ce133b6cea84942 | 09fc5379e5ecafc66eee7eac5ba8cf51244c7aa9 | refs/heads/master | 2020-07-24T07:40:23.877863 | 2020-02-29T02:03:55 | 2020-02-29T02:03:55 | 207,850,323 | 0 | 0 | null | 2019-09-11T15:50:47 | 2020-02-29T01:59:04 | 2020-02-29T02:03:55 | Python | [
{
"alpha_fraction": 0.5369649529457092,
"alphanum_fraction": 0.5914396643638611,
"avg_line_length": 16.066667556762695,
"blob_id": "3334f3a28d9a1942ac493ca144715daf08b9571d",
"content_id": "31a8955c94c3770a6c5356582e55ab7038933307",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 257,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 15,
"path": "/default_arguments.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:43:22 2019\n\n@author: aquib\n\"\"\"\n\n\n\ndef print_from_stream(n, stream=None):\n if stream is None:\n stream=EvenStream()\n for _ in range(n):\n print(stream.get_next())\n\n"
},
{
"alpha_fraction": 0.585185170173645,
"alphanum_fraction": 0.6370370388031006,
"avg_line_length": 18.285715103149414,
"blob_id": "2259426262c4b202ffca0edf99018c39c9cba3d8",
"content_id": "13e0416bbc72ec0d4e64e10ff3dacfd0a35ce5c4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 270,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 14,
"path": "/integer_comes_in_all_sizes.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:17:28 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\na=int(input())\nb=int(input())\nc=int(input())\nd=int(input())\nprint(pow(a,b)+pow(c,d),end='')\n"
},
{
"alpha_fraction": 0.5942491888999939,
"alphanum_fraction": 0.6485623121261597,
"avg_line_length": 16.38888931274414,
"blob_id": "5c4b7068dfc967dc2343b96302743a90fd9b16b5",
"content_id": "5790e7790bcbcc512074b08a73d6246ba6fe752a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 313,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 18,
"path": "/transpose_and_flatten.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:28:40 2019\n\n@author: aquib\n\"\"\"\n\nimport numpy\nrow,col = map(int,input().split())\narray=[]\nfor i in range(int(row)):\n x=input().split()\n array.append(x)\n\nlis1=numpy.array(array,int)\nprint(numpy.transpose(lis1))\nprint(lis1.flatten())\n"
},
{
"alpha_fraction": 0.6170799136161804,
"alphanum_fraction": 0.6611570119857788,
"avg_line_length": 23.200000762939453,
"blob_id": "4235d27b6a7ad6b0387ce6074a330318eb70b00a",
"content_id": "8b5a62f34db77fb5e4ff79552278309f4bf6a448",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 363,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 15,
"path": "/the_captains_room.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 21:58:50 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nK=int(input())\nrooms=list(map(int,input().split()))\ns=set(rooms)\nx=(sum(s)*K-sum(rooms))//(K-1)\n#since captains room will be included K times in sum(s)*K, divide by K-1\nprint(x,end='')\n"
},
{
"alpha_fraction": 0.591928243637085,
"alphanum_fraction": 0.6158445477485657,
"avg_line_length": 24.384614944458008,
"blob_id": "f0596472df116a921ededc2b78be4916f6ec8e76",
"content_id": "e5cea9144083abe9e4703368459e252c9a91ce94",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 669,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 26,
"path": "/set_mutations.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 21:54:55 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nnum_A=int(input())\nA=set(map(int,input().split()))\nnum_ops=int(input())\nfor _ in range(num_ops):\n c=input().split()\n command=c[0]\n num_B=c[1]\n B=set(map(int,input().split()))\n if command=='intersection_update':\n A.intersection_update(B)\n if command=='update':\n A.update(B)\n if command=='symmetric_difference_update':\n A.symmetric_difference_update(B)\n if command=='difference_update':\n A.difference_update(B)\nprint(sum(A),end='') \n\n"
},
{
"alpha_fraction": 0.6164383292198181,
"alphanum_fraction": 0.6602739691734314,
"avg_line_length": 19.27777862548828,
"blob_id": "d0a4788ef9018ca1ba9c06d6f107cc4b85db27f6",
"content_id": "60fc706304463904abdc5fef163902a3f39cc1d7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 365,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 18,
"path": "/iterables_iterators.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:41:32 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nfrom itertools import combinations\n\nN=int(input())\nL=input().split()\nK=int(input())\n\nC=list(combinations(L,K))\nF=filter(lambda c: 'a' in c, C)\nprint(\"{0:.3}\".format(len(list(F))/len(C)))\n"
},
{
"alpha_fraction": 0.6099071502685547,
"alphanum_fraction": 0.6532507538795471,
"avg_line_length": 22.071428298950195,
"blob_id": "e5573d369ff273d94889528910552cf2bdd47cf8",
"content_id": "06cae0022f3340bc34d0f6c1fd9f95db4304ebbb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 323,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 14,
"path": "/set_symmetric_difference.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 21:54:39 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nnum_e=int(input())\nroll_e=set(map(int,input().split()))\nnum_f=int(input())\nroll_f=set(map(int,input().split()))\nprint(len(roll_e^roll_f),end='')\n"
},
{
"alpha_fraction": 0.4359999895095825,
"alphanum_fraction": 0.492000013589859,
"avg_line_length": 14.5625,
"blob_id": "d5593e49bd11b0ab339071e9971790833b430a6c",
"content_id": "f185aa1ab89cec351ba7fa0a5cf111b4865a87fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 250,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 16,
"path": "/swap_case.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:21:09 2019\n\n@author: aquib\n\"\"\"\n\ndef swap_case(s):\n x=[]\n for c in s:\n if c.isalpha():\n c=c.swapcase()\n x.append(c)\n \n return ''.join(x)\n\n"
},
{
"alpha_fraction": 0.5823754668235779,
"alphanum_fraction": 0.6398467421531677,
"avg_line_length": 17.5,
"blob_id": "8962e49bdccddccbbb0871fd1684a44dcd17a0f4",
"content_id": "b11b3500fbbb5587b5a2f59bd000409a888b4f26",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 261,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 14,
"path": "/sum_and_prod.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:20:28 2019\n\n@author: aquib\n\"\"\"\n\nimport numpy\nN,M=map(int, input().split())\nx=numpy.array([input().split() for i in range(N)],int)\nsum=numpy.sum(x, 0)\nprod=numpy.prod(sum)\nprint(prod)\n\n\n"
},
{
"alpha_fraction": 0.6127946376800537,
"alphanum_fraction": 0.6734007000923157,
"avg_line_length": 21.846153259277344,
"blob_id": "b151daa613a98fc0cce2c485210f734c963d50e5",
"content_id": "ecb385723ab4a9a2ecc830e7babce5e6aa15e55b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 297,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 13,
"path": "/polar_coordinates.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:32:10 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nimport cmath\nnumber=complex(input().strip())\nprint(\"%.3f\"%cmath.polar(number)[0])\nprint(\"%.3f\"%cmath.polar(number)[1])\n"
},
{
"alpha_fraction": 0.5723270177841187,
"alphanum_fraction": 0.6163522005081177,
"avg_line_length": 16.66666603088379,
"blob_id": "13ffde2274eef0f1e66173cc02b9864514f53593",
"content_id": "873106db9179f0f0dd06ef382436de5a8cd6066b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 318,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 18,
"path": "/zipped.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:37:13 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\n\nN,X=map(int,input().split())\ns=[]\n\nfor _ in range(X):\n s.append(map(float,input().split()))\n\nfor i in zip(*s):\n print(sum(i)/len(i))\n"
},
{
"alpha_fraction": 0.5340313911437988,
"alphanum_fraction": 0.5689354538917542,
"avg_line_length": 22.875,
"blob_id": "f3eb02611159074b1ca48f9fac56b5161a5f7596",
"content_id": "5b6891ab831c56bf39971404518630b6368b4857",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 573,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 24,
"path": "/validating_uid.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:11:29 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nimport re\n\nnum_input=int(input())\nfor _ in range(num_input):\n UID=''.join(sorted(input()))\n try:\n assert re.search(r'[A-Z]{2}', UID)\n assert re.search(r'\\d\\d\\d',UID)\n assert not re.search(r'[^a-zA-Z0-9]',UID)\n assert not re.search(r'(.)\\1',UID)\n assert len(UID)==10\n except:\n print('Invalid\\n',end='')\n else:\n print('Valid\\n',end='')\n"
},
{
"alpha_fraction": 0.5968992114067078,
"alphanum_fraction": 0.6627907156944275,
"avg_line_length": 18.923076629638672,
"blob_id": "3ba42adc52c0c8b2f17481afd544eff84f4d09de",
"content_id": "a9e637f5ef476b4c31a18460fbb17a1b07fcefa4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 258,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 13,
"path": "/linear_algebra.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:23:58 2019\n\n@author: aquib\n\"\"\"\n\nimport numpy\nnumpy.set_printoptions(legacy='1.13')\nN=int(input())\nx=numpy.array([input().split() for i in range(N)], float)\nprint(numpy.linalg.det(x))"
},
{
"alpha_fraction": 0.49618321657180786,
"alphanum_fraction": 0.5496183037757874,
"avg_line_length": 17.714284896850586,
"blob_id": "dd9944fad911d2369ef0413eb671ffcb4c8db468",
"content_id": "b5d05e38b10659fe9814cea23b4d048f532394b4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 262,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 14,
"path": "/exceptions.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:36:04 2019\n\n@author: aquib\n\"\"\"\n\nfor i in range(int(input())):\n try:\n a,b=map(int,input().split())\n print(a//b)\n except Exception as e:\n print(\"Error Code:\",e)\n"
},
{
"alpha_fraction": 0.6188679337501526,
"alphanum_fraction": 0.6716980934143066,
"avg_line_length": 16.66666603088379,
"blob_id": "4f14856dacd63b25efab51e3c69c192c7dc0e028",
"content_id": "66526f26ba8ac3c7772ce15349707f14ea4157ee",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 265,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 15,
"path": "/floor_ceil_rint.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:29:57 2019\n\n@author: aquib\n\"\"\"\n\nimport numpy\nnumpy.set_printoptions(sign=' ')\na=input().split()\nx=numpy.array(a,dtype=float)\nprint(numpy.floor(x))\nprint(numpy.ceil(x))\nprint(numpy.rint(x))\n"
},
{
"alpha_fraction": 0.5336538553237915,
"alphanum_fraction": 0.5625,
"avg_line_length": 22.11111068725586,
"blob_id": "25c85ca40804946cdde8d003f1ce8e23991e5a09",
"content_id": "1112c74e116aa057ae94006908ccc176ff49a99a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 624,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 27,
"path": "/nested_lists.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 21:49:43 2019\n\n@author: aquib\n\"\"\"\n\nif __name__ == '__main__':\n students=[]\n for _ in range(int(input())):\n name = input()\n score = float(input())\n students.append([name,score])\n score_set=set([s[1] for s in students])\n #sort scores set\n score_sorted=sorted(score_set)\n\n second_name=[]\n for s in students:\n if s[1]==score_sorted[1]:\n second_name.append(s[0])\n #sort students with same second lowest score\n second_name.sort()\n for s in second_name:\n print(s)\n print(end='')\n"
},
{
"alpha_fraction": 0.5761904716491699,
"alphanum_fraction": 0.6428571343421936,
"avg_line_length": 13.928571701049805,
"blob_id": "067c13773fcb1f1216027618cc86bf762de61723",
"content_id": "0ebb8081a524afa79da4b2f4f446166c7f596cab",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 210,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 14,
"path": "/capitalize.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:20:26 2019\n\n@author: aquib\n\"\"\"\n\n\nimport string\n\n# Complete the solve function below.\ndef solve(s):\n return string.capwords(s,' ')\n\n"
},
{
"alpha_fraction": 0.5301587581634521,
"alphanum_fraction": 0.5873016119003296,
"avg_line_length": 18.6875,
"blob_id": "780e81524394afbf859287e768a87d8ab385d44b",
"content_id": "67d2b27eeb28e975d6212ee08ffb261f380f1637",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 315,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 16,
"path": "/validating_phone_nums.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:39:52 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nimport re\nn=int(input())\nfor _ in range(n):\n if re.match(r'[789]\\d{9}$', input()):\n print('YES')\n else:\n print('NO')\n"
},
{
"alpha_fraction": 0.679920494556427,
"alphanum_fraction": 0.7077534794807434,
"avg_line_length": 22.952381134033203,
"blob_id": "2e6fccc9f51c820442ab496cb419f28436f5318e",
"content_id": "4862d83d822364cfe1c17e6b4e62d98a8c68eef2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 503,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 21,
"path": "/set_union.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 21:52:43 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\n#read in number of English subscribers\nnum_e=int(input())\n#read roll number of English subscribers\nroll_e=list(map(int, input().split()))\n\n#read in number of French subscribers\nnum_f=int(input())\n#read roll number of French subscribers\nroll_f=list(map(int,input().split()))\n\ntotal=roll_e+roll_f\nprint(len(set(total)),end='')\n"
},
{
"alpha_fraction": 0.4368378221988678,
"alphanum_fraction": 0.44335779547691345,
"avg_line_length": 27.523256301879883,
"blob_id": "b86fdfc394c4fe4cec602c7369e722f63c3f039a",
"content_id": "9700bb4266f91cc58824ce5596fcd2bb0c66d479",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2454,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 86,
"path": "/Attribute Parser.cpp",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "//https://www.hackerrank.com/challenges/attribute-parser/problem\n\n#include <cmath>\n#include <cstdio>\n#include <sstream>\n#include <vector>\n#include <iostream>\n#include <algorithm>\nusing namespace std;\n#include <map>\n\nint main() {\n /* Enter your code here. Read input from STDIN. Print output to STDOUT */ \n int n,q;\n cin>>n>>q;\n cin.ignore();\n\n map<string,string> attributeDB;\n string inputstr, tag_preamble=\"\";\n\n //get each HRML line\n for(int i=0;i<n;++i)\n {\n getline(cin,inputstr);\n\n //for each HRML line break it into token words\n stringstream ss(inputstr);\n string word,attribute, value;\n size_t pos;\n while(getline(ss, word, ' '))\n {\n // for each token word\n // tag detected -> adjust tag_preamble by +/- tag\n if(word[0]=='<')\n {\n string tag;\n if(word[1]=='/')\n {\n // it's tag closing\n tag=word.substr(2);\n tag=tag.substr(0,tag.length()-1); // rid of \">\"\n pos=tag_preamble.find(\".\"+tag);\n if(pos==string::npos)\n tag_preamble=\"\";\n else\n tag_preamble=tag_preamble.substr(0,pos);\n }\n else\n {\n // it's tag opening\n tag=word.substr(1);\n if(tag.find(\">\")!=string::npos)\n tag=tag.substr(0,tag.length()-1); // rid of \">\"\n if(tag_preamble==\"\")\n tag_preamble=tag;\n else\n tag_preamble=tag_preamble+\".\"+tag;\n }\n }\n // value detected\n else if(word[0]=='\"')\n {\n pos=word.find_last_of('\"');\n value=word.substr(1,pos-1);\n attributeDB[attribute]=value; //insert into DB\n }\n // attribute name detected\n else if(word[0]!='=')\n {\n attribute=tag_preamble+\"~\"+word;\n }\n }\n }\n\n // now we process the queries\n for(int i=0;i<q;++i)\n {\n getline(cin,inputstr);\n if(attributeDB.find(inputstr)==attributeDB.end())\n cout<<\"Not Found!\"<<endl;\n else\n cout<<attributeDB[inputstr]<<endl;\n }\n\n return 0;\n}\n\n"
},
{
"alpha_fraction": 0.6119873523712158,
"alphanum_fraction": 0.6561514139175415,
"avg_line_length": 18.75,
"blob_id": "be0006b726456d1406915a80f916e2c7af1a9340",
"content_id": "94bddf1bbc6ea6a915ae24e9ee2c29c714f188ed",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 317,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 16,
"path": "/set_add.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 21:51:42 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\n#number of stamps\nN=int(input())\nstamps=set('')\n#read in stamp names\nfor _ in range(N):\n stamps.add(input())\nprint(len(stamps),end='')\n\n"
},
{
"alpha_fraction": 0.5471916794776917,
"alphanum_fraction": 0.5738274455070496,
"avg_line_length": 22.013334274291992,
"blob_id": "7fce35704135ced336662a5e8ec84e2ed4734306",
"content_id": "3112a59db6fa117daca8eebd75d52a2b87120895",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1727,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 75,
"path": "/Bit Array.cpp",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "//https://www.hackerrank.com/challenges/bitset-1/problem\n\n#include <cmath>\n#include <cstdio>\n#include <math.h>\n#include <vector>\n#include <iostream>\n#include <algorithm>\nusing namespace std;\n\nconstexpr unsigned exponent = 31;\nconstexpr unsigned two_to_exponent = 1u << exponent;\n\nunsigned solve_p_even(unsigned n, unsigned s, unsigned p, unsigned q)\n{\n if(p==0)\n {\n if(s==q)\n return 1;\n else {\n return 2;\n }\n }\n\n if(s==0 && q==0)\n {\n return 1;\n }\n\n unsigned a1_minus_a0=(p-1)*s+q;\n unsigned numerator = exponent - __builtin_popcount((a1_minus_a0 & -a1_minus_a0)-1);\n unsigned denominator=__builtin_popcount((p&-p)-1);\n unsigned m = numerator/denominator+(numerator%denominator==0?1:2);\n return std::min(m,n);\n}\n\nunsigned solve_p_odd(unsigned n, unsigned s, unsigned p, unsigned q)\n{\n if(p==1)\n return q==0?1: std::min(n, two_to_exponent / (q&-q));\n \n if(s==0 && q==0)\n return 1;\n \n unsigned m=1;\n unsigned long long p_minus_1=p-1;\n unsigned long long a1_minus_a0=p_minus_1*s+q;\n unsigned long long p_to_m = p;\n unsigned long long mask = (two_to_exponent * (p_minus_1&-p_minus_1)/ (a1_minus_a0&-a1_minus_a0))-1;\n\n while(m<n && (p_to_m & mask)!=1)\n {\n p_to_m= p_to_m*p_to_m;\n m= m*2;\n }\n return std::min(m,n);\n}\n\nunsigned solve( unsigned n, unsigned s, unsigned p, unsigned q)\n{\n if(p%2==0)\n {\n return solve_p_even(n,s,p,q);\n }\n else\n return solve_p_odd(n,s,p,q);\n}\n\nint main() {\n /* Enter your code here. Read input from STDIN. Print output to STDOUT */ \n unsigned n,s,p,q;\n std::cin>>n>>s>>p>>q;\n std::cout<<solve(n,s,p,q);\n return 0;\n}\n\n"
},
{
"alpha_fraction": 0.5535714030265808,
"alphanum_fraction": 0.5969387888908386,
"avg_line_length": 18.600000381469727,
"blob_id": "493eee1d96cd06e07364899ddea1e01ec8a2ce23",
"content_id": "53f01f34251b3a02fd261247302f6629a8a5d637",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 392,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 20,
"path": "/no_idea.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:27:15 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nn,m=map(int,input().split())\narr=list(map(int,input().split()))\na=set(map(int,input().split()))\nb=set(map(int,input().split()))\nh=0\nfor i in arr:\n if i in a:\n h= h+1\n if i in b:\n h=h-1\nprint(h)\n"
},
{
"alpha_fraction": 0.545045018196106,
"alphanum_fraction": 0.6171171069145203,
"avg_line_length": 14.928571701049805,
"blob_id": "c498403ebd5ac9fd62bbc145ddbfa79b5c0eb2e5",
"content_id": "23eea30a035facd15d80319dd6f8858fb061e0aa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 222,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 14,
"path": "/shape_and_reshape.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:28:00 2019\n\n@author: aquib\n\"\"\"\n\nimport numpy\nx=input().strip().split(' ')\nb=[int(i) for i in x]\na=numpy.array(b)\no=numpy.reshape(a,(3,3))\nprint(o)"
},
{
"alpha_fraction": 0.5930736064910889,
"alphanum_fraction": 0.6536796689033508,
"avg_line_length": 20,
"blob_id": "e4a873bc88895ee2c2539198c9d1e6349e37aa7b",
"content_id": "86abe7f0ef755f9a37ebf1940cf13ac0867e82e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 231,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 11,
"path": "/input.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:37:22 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nx,k=map(int,input().split())\nprint(eval(input())==k)\n"
},
{
"alpha_fraction": 0.6240601539611816,
"alphanum_fraction": 0.6766917109489441,
"avg_line_length": 16.66666603088379,
"blob_id": "27bfae90839d5770011072470a2a6542ae81bfb4",
"content_id": "52814060167a740406fa2d98c5cb967b1730ed8a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 266,
"license_type": "no_license",
"max_line_length": 79,
"num_lines": 15,
"path": "/reduce_function.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:41:58 2019\n\n@author: aquib\n\"\"\"\n\n\n\nimport operator\n\ndef product(fracs):\n t = reduce(operator.mul, fracs)# complete this line with a reduce statement\n return t.numerator, t.denominator\n\n"
},
{
"alpha_fraction": 0.5333333611488342,
"alphanum_fraction": 0.5690476298332214,
"avg_line_length": 14.55555534362793,
"blob_id": "bae0e1900a7d3dabd226cd5f8f59f9aaf85d71ad",
"content_id": "5af17776a911e9f1eacb84172db1f574af06d466",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 420,
"license_type": "no_license",
"max_line_length": 62,
"num_lines": 27,
"path": "/athlete_sort.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 21:43:50 2019\n\n@author: aquib\n\"\"\"\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n\n\nif __name__ == '__main__':\n n, m = map(int, input().split())\n nums = [list(map(int, input().split())) for i in range(n)]\n k = int(input())\n\n nums.sort(key=lambda x: x[k])\n\n for line in nums:\n print(*line, sep=' ')\n"
},
{
"alpha_fraction": 0.6156156063079834,
"alphanum_fraction": 0.6576576828956604,
"avg_line_length": 21.200000762939453,
"blob_id": "e18c1a47c8a7ff364ae3659d931515ac8cda8665",
"content_id": "f358d57ed5d9b7d7a5ac8ef3165ebe60f9f5505e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 333,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 15,
"path": "/set_difference.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 21:54:10 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nnum_e=int(input())\nroll_e=set(map(int,input().split()))\nnum_f=int(input())\nroll_f=set(map(int,input().split()))\ndiff=roll_e-roll_f\nprint(len(diff),end='')\n"
},
{
"alpha_fraction": 0.604651153087616,
"alphanum_fraction": 0.6611295938491821,
"avg_line_length": 20.35714340209961,
"blob_id": "a25764672d23f9fac14e9aa6d7ad47c42272071e",
"content_id": "97ac6141797c7a00db96fb3130ce38e04ed15b51",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 301,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 14,
"path": "/inner_outer.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:22:23 2019\n\n@author: aquib\n\"\"\"\n\nimport numpy\nnumpy.set_printoptions(legacy='1.13')\na=numpy.array([input().split()], int)\nb=numpy.array([input().split()], int)\nprint(numpy.asscalar(numpy.inner(a,b)))\nprint(numpy.outer(a,b))\n\n\n"
},
{
"alpha_fraction": 0.5339673757553101,
"alphanum_fraction": 0.5584239363670349,
"avg_line_length": 27.30769157409668,
"blob_id": "ce1e27e5589089c3a9e154b66c412ebbbf9f82e1",
"content_id": "e35e7e9205541dcc2975692eb4bfb0c06fcbf47b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 736,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 26,
"path": "/html_parser_part_1.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:10:02 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nfrom html.parser import HTMLParser\nclass MyHTMLParser(HTMLParser):\n def handle_starttag(self, tag, attrs): \n print ('Start :',tag)\n for ele in attrs:\n print ('->',ele[0],'>',ele[1])\n \n def handle_endtag(self, tag):\n print ('End :',tag)\n \n def handle_startendtag(self, tag, attrs):\n print ('Empty :',tag)\n for ele in attrs:\n print ('->',ele[0],'>',ele[1])\n \nMyParser = MyHTMLParser()\nMyParser.feed(''.join([input().strip() for _ in range(int(input()))]))\n"
},
{
"alpha_fraction": 0.5729926824569702,
"alphanum_fraction": 0.6240875720977783,
"avg_line_length": 18.571428298950195,
"blob_id": "d4af9fd18b773a76ce3ff8424200515d0ee31afe",
"content_id": "20a6b0d678baa5be516ff235bbc5c21a8e4d50ef",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 274,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 14,
"path": "/dot_and_cross.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:21:53 2019\n\n@author: aquib\n\"\"\"\n\nimport numpy\nn=int(input())\na=numpy.array([input().split() for _ in range(n)], int)\nb=numpy.array([input().split() for _ in range(n)], int)\nm=numpy.dot(a,b)\nprint(m)\n"
},
{
"alpha_fraction": 0.6213991641998291,
"alphanum_fraction": 0.6790123581886292,
"avg_line_length": 19.08333396911621,
"blob_id": "5c83943e6bc676c2f06a4c8477c976bcfd92139d",
"content_id": "3cde60dce2cef93485184f4e6801d8d4791ef51e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 243,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 12,
"path": "/zeros_ones.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:24:10 2019\n\n@author: aquib\n\"\"\"\n\nimport numpy\nshape=list(map(int,input().split()))\nprint(numpy.zeros(shape,dtype=numpy.int))\nprint(numpy.ones(shape,dtype=numpy.int))\n\n\n"
},
{
"alpha_fraction": 0.40049752593040466,
"alphanum_fraction": 0.44029849767684937,
"avg_line_length": 19.100000381469727,
"blob_id": "4df553fbe4d66c54779cd8f6bc3c2e699aa8a89d",
"content_id": "9ea60abac47e4ead82ee5877e489c1f57c78a379",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 402,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 20,
"path": "/lists.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:29:04 2019\n\n@author: aquib\n\"\"\"\n\nif __name__ == '__main__':\n N = int(input())\n l=[]\n for _ in range(N):\n s=input().split()\n command=s[0]\n arg=s[1:]\n if command!=\"print\":\n command = command + \"(\"+\",\".join(arg)+\")\"\n eval(\"l.\"+command)\n else:\n print(l)\n"
},
{
"alpha_fraction": 0.5977093577384949,
"alphanum_fraction": 0.6055833697319031,
"avg_line_length": 26.372549057006836,
"blob_id": "dc7507bfb69a0abf7fd065e8150093fa5b6e0cda",
"content_id": "b76265093883ad17d76684e7c22a6cce64d442d4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1397,
"license_type": "no_license",
"max_line_length": 470,
"num_lines": 51,
"path": "/Vector-Erase.cpp",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "//https://www.hackerrank.com/challenges/vector-erase/problem\n\n#include <cmath>\n#include <cstdio>\n#include <vector>\n#include <iostream>\n#include <algorithm>\nusing namespace std;\n\n\nint main() {\n /* Enter your code here. Read input from STDIN. Print output to STDOUT */ \n int N, temp;\n vector<int> v;\n cin>>N;\n // fill vector\n for(int i=0;i<N;i++)\n {\n cin>>temp;\n v.push_back(temp);\n }\n //remove itemp specified in 3rd line\n cin>>temp;\n if(temp<v.size())\n v.erase(v.begin()+temp-1);\n \n //remove range specified in 4th line\n int a,b;\n cin>>a>>b;\n\n if(a<b && b<v.size())\n v.erase(v.begin() +a-1, v.begin()+b-1);\n \n //print out remaining vector elements\n cout<<v.size()<<endl;\n\n /*\n It's a newer structure called a range-based for-loop (C++11). It takes anything that can be iterated through (in this case v), and goes through each item one-at-a-time, placing the value into \"auto (underscore)v\". Auto is a newer type (since C++11), that automatically determines what is being passed to it. So it basically detects that this is an int. It comes in handy when you have complicated types, like iterators of maps and such. It's basically equivalent to:\n \n for(int i; i<v.size(); i++) \n {\n int j=v[i];\n }\n \n */\n for(auto _v : v)\n cout<<_v<<\" \";\n cout<<endl;\n\n return 0;\n}\n\n"
},
{
"alpha_fraction": 0.44272446632385254,
"alphanum_fraction": 0.5170278549194336,
"avg_line_length": 15.947368621826172,
"blob_id": "78b8f148a5404d3522e7b9944f810095793c4411",
"content_id": "57897bd3a7c36c7fed4f464277f69bcf50048634",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 323,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 19,
"path": "/write_a_function.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 21:41:35 2019\n\n@author: aquib\n\"\"\"\n\ndef is_leap(year):\n leap = False\n \n # Write your logic here\n if year%4==0:\n leap=True\n if year%100==0:\n leap=False\n if year%400==0:\n leap=True\n return leap\n\n"
},
{
"alpha_fraction": 0.6301369667053223,
"alphanum_fraction": 0.6684931516647339,
"avg_line_length": 21.8125,
"blob_id": "488a4bf87744de4a1e2fceac243618ff78cd7d75",
"content_id": "22d5f76f02f1289d64a388465cc3047927140fd8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 365,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 16,
"path": "/set_intersection.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 21:53:31 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\n#num of English subscribers\nnum_e=int(input())\nroll_e=set(map(int,input().split()))\nnum_f=int(input())\nroll_f=set(map(int,input().split()))\ninter=roll_e & roll_f\nprint(len(inter),end='')\n"
},
{
"alpha_fraction": 0.6203208565711975,
"alphanum_fraction": 0.6631016135215759,
"avg_line_length": 23.933332443237305,
"blob_id": "98966b9f6eff02d1eaec3b0cc4438c8b75acba1a",
"content_id": "aa0b519c70d0cc51fe5737578f28d0c307e78453",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 374,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 15,
"path": "/maximize_it.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:44:11 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nfrom itertools import product\n\nk,m=map(int,input().split())\nn=(list(map(int, input().split()))[1:] for _ in range(k))\nresults=map(lambda x:sum(i**2 for i in x)%m, product(*n))\nprint(max(results))\n"
},
{
"alpha_fraction": 0.5192034244537354,
"alphanum_fraction": 0.5504978895187378,
"avg_line_length": 29.54347801208496,
"blob_id": "441dc9bb62c96f4f840e1e60ccfcf74029a94510",
"content_id": "3a888c08b2710de4d986e913de14afb88ec561e2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1406,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 46,
"path": "/dealing_with_complex_nums.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:43:36 2019\n\n@author: aquib\n\"\"\"\n\n\n\nclass Complex(object):\n def __init__(self, real, imaginary):\n self.real=real\n self.imaginary=imaginary\n\n def __add__(self, no):\n return Complex(self.real+no.real, self.imaginary+no.imaginary)\n\n def __sub__(self, no):\n return Complex(self.real-no.real, self.imaginary-no.imaginary)\n\n def __mul__(self, no):\n return Complex(self.real*no.real-self.imaginary*no.imaginary, self.real*no.imaginary+self.imaginary*no.real)\n\n def __truediv__(self, no):\n try:\n return self.__mul__(Complex(no.real, -1*no.imaginary)).__mul__(Complex(1.0/(no.mod().real)**2,0))\n except ZeroDivisionError as e:\n print(e)\n return None\n def mod(self):\n return Complex(pow(self.real**2+self.imaginary**2,0.5),0)\n\n def __str__(self):\n if self.imaginary == 0:\n result = \"%.2f+0.00i\" % (self.real)\n elif self.real == 0:\n if self.imaginary >= 0:\n result = \"0.00+%.2fi\" % (self.imaginary)\n else:\n result = \"0.00-%.2fi\" % (abs(self.imaginary))\n elif self.imaginary > 0:\n result = \"%.2f+%.2fi\" % (self.real, self.imaginary)\n else:\n result = \"%.2f-%.2fi\" % (self.real, abs(self.imaginary))\n return result\n\n"
},
{
"alpha_fraction": 0.5737051963806152,
"alphanum_fraction": 0.6334661245346069,
"avg_line_length": 16.928571701049805,
"blob_id": "e7a8ebdffb9c5478b1fc4030ede408f87828012e",
"content_id": "a95e8b684a7360eda42ca80a1a91de96fbacd8cb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 251,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 14,
"path": "/min_max.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:21:03 2019\n\n@author: aquib\n\"\"\"\n\nimport numpy\nN,M=map(int,input().split())\nx=numpy.array([input().split() for _ in range(N)], int)\nmn=numpy.min(x,1)\nmx=numpy.max(mn)\nprint(mx)\n"
},
{
"alpha_fraction": 0.5227272510528564,
"alphanum_fraction": 0.5909090638160706,
"avg_line_length": 18.25,
"blob_id": "f57de309be2cfb047129600957063de696bec418",
"content_id": "60a9c3596656e0cda9eb06b6fc84f3c78ebe84d3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 308,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 16,
"path": "/map_lambda_function.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:28:36 2019\n\n@author: aquib\n\"\"\"\n\ncube = lambda x: x**3# complete the lambda function \n\ndef fibonacci(n):\n # return a list of fibonacci numbers\n a=[0,1]\n for i in range(2,n):\n a.append(a[i-2]+a[i-1])\n return a[0:n]\n"
},
{
"alpha_fraction": 0.6035503149032593,
"alphanum_fraction": 0.6597633361816406,
"avg_line_length": 16.736841201782227,
"blob_id": "373dcd36281ac060b7b2a1461d88cdb055f9355b",
"content_id": "9f3965d8c9323e8bc8b73774e2a86041715d7a86",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 338,
"license_type": "no_license",
"max_line_length": 55,
"num_lines": 19,
"path": "/mean_var_std.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:21:26 2019\n\n@author: aquib\n\"\"\"\n\nimport numpy\nnumpy.set_printoptions(legacy='1.13')\n\nN,M=map(int, input().split())\nx=numpy.array([input().split() for i in range(N)], int)\nmean=numpy.mean(x,1)\nvar=numpy.var(x,0)\nstd=numpy.std(x)\nprint(mean)\nprint(var)\nprint(std)\n\n"
},
{
"alpha_fraction": 0.614814817905426,
"alphanum_fraction": 0.6666666865348816,
"avg_line_length": 21.5,
"blob_id": "d864ddfd4b99b86efa3747cf715dc88a77f4942f",
"content_id": "14a0595a3fba13d75c9a19ad0797221020f0217c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 270,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 12,
"path": "/compress_string.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:41:01 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nfrom itertools import groupby\n\nprint(*[(len(list(c)), int(k)) for k,c in groupby(input())])\n"
},
{
"alpha_fraction": 0.4527363181114197,
"alphanum_fraction": 0.5223880410194397,
"avg_line_length": 15.75,
"blob_id": "65427d6270e253a5c71f1b03d60ec3de48d4f159",
"content_id": "2d543089ad9ba26add91f6f41743ecf31d59f472",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 201,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 12,
"path": "/loops.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 21:38:56 2019\n\n@author: aquib\n\"\"\"\n\nif __name__ == '__main__':\n n = int(raw_input())\n for i in range(n):\n print i*i\n"
},
{
"alpha_fraction": 0.5547826290130615,
"alphanum_fraction": 0.582608699798584,
"avg_line_length": 20.296297073364258,
"blob_id": "fd0e4daef1d73c45d5dea4f73a5781bd8b46f4ab",
"content_id": "86c6b2b44c6208bb190a1fac353f12433d12e6cf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 575,
"license_type": "no_license",
"max_line_length": 77,
"num_lines": 27,
"path": "/ginorts.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 21:46:07 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nx=input()\nlowchar=[]\nuppchar=[]\nodddigit=[]\nevendigit=[]\nfor i in x:\n if i.isalpha():\n if i.isupper():\n uppchar.append(i)\n else:\n lowchar.append(i)\n elif i.isdigit():\n if int(i)%2==0:\n evendigit.append(i)\n else:\n odddigit.append(i)\ny=''.join(sorted(lowchar)+sorted(uppchar)+sorted(odddigit)+sorted(evendigit))\nprint(y)\n"
},
{
"alpha_fraction": 0.5583333373069763,
"alphanum_fraction": 0.6166666746139526,
"avg_line_length": 16.14285659790039,
"blob_id": "b3e3e8bb67741219caefe10682dcd1e12c3c0fdb",
"content_id": "d27dfa042bce7647134581786aea462940f2c214",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 240,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 14,
"path": "/introduction_to_sets.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:29:31 2019\n\n@author: aquib\n\"\"\"\n\ndef average(array):\n # your code goes here\n aset=set(array)\n total=sum(aset)\n avg=float(total)/len(aset)\n return avg\n"
},
{
"alpha_fraction": 0.49077489972114563,
"alphanum_fraction": 0.5498154759407043,
"avg_line_length": 17.066667556762695,
"blob_id": "5300cb477fb986a90d65945d1c5d86a51f092ce0",
"content_id": "d9285bd4b23d7e4cc1d4a76ed78123d6a0e0e236",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 271,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 15,
"path": "/print_function.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 21:42:05 2019\n\n@author: aquib\n\"\"\"\n\nfrom __future__ import print_function\n\nif __name__ == '__main__':\n n = int(raw_input())\n x=[str(i) for i in range(1,n+1)]\n y=int(''.join(x))\n print(y)\n"
},
{
"alpha_fraction": 0.5416012406349182,
"alphanum_fraction": 0.5682888627052307,
"avg_line_length": 15.333333015441895,
"blob_id": "126f0478c3c01b58edc10f8e5950fb3471c851c7",
"content_id": "9c71b1973fa68ea12e6b1637e7252736fc74b5c8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 637,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 39,
"path": "/mini_max_sum.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:35:50 2019\n\n@author: aquib\n\"\"\"\n\n#!/bin/python3\n\nimport math\nimport os\nimport random\nimport re\nimport sys\n\n# Complete the miniMaxSum function below.\ndef miniMaxSum(arr):\n max_list=[]\n min_list=[]\n\n l=arr.copy()\n for j in range(4):\n mx=max(l)\n max_list.append(mx)\n l.remove(mx)\n \n x=arr.copy()\n for j in range(4):\n mn=min(x)\n min_list.append(mn)\n x.remove(mn)\n\n print(sum(min_list),sum(max_list))\n\nif __name__ == '__main__':\n arr = list(map(int, input().rstrip().split()))\n\n miniMaxSum(arr)\n"
},
{
"alpha_fraction": 0.6239669322967529,
"alphanum_fraction": 0.6818181872367859,
"avg_line_length": 19.16666603088379,
"blob_id": "c3a54d124a2227496c8e010323b1bd1c6c0aed59",
"content_id": "02872d75079e6a5f0e19d684bbf34c7cfb959f05",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 242,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 12,
"path": "/python_evaluation.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 21:42:46 2019\n\n@author: aquib\n\"\"\"\n\nfrom __future__ import print_function\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nvar=raw_input()\neval(var)\n"
},
{
"alpha_fraction": 0.5866261124610901,
"alphanum_fraction": 0.6474164128303528,
"avg_line_length": 22.5,
"blob_id": "8182cc4641f4fd0f66e0a3717723b428e2e5b228",
"content_id": "8a5dcfff2a3a48838bd90be54ec0ed3f4e2499ee",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 329,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 14,
"path": "/any_or_all.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 21:44:28 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nn=input()\nnums = list(map(int, input().split()))\ncond1=all([i>0 for i in nums])\ncond2=any([str(i)==str(i)[::-1] for i in nums])\nprint(cond1 and cond2)\n"
},
{
"alpha_fraction": 0.5628140568733215,
"alphanum_fraction": 0.6331658363342285,
"avg_line_length": 15.416666984558105,
"blob_id": "f089d4fafcf6ad30eb119beaa068b68543ce5f03",
"content_id": "d3d583e34f1779237f6fc4db74176f3ce2dd2cb5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 199,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 12,
"path": "/polynomials.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:22:48 2019\n\n@author: aquib\n\"\"\"\n\nimport numpy\nn=list(map(float,input().split()))\nm=input()\nprint(numpy.polyval(n,int(m)))\n\n\n"
},
{
"alpha_fraction": 0.4887506067752838,
"alphanum_fraction": 0.49928194284439087,
"avg_line_length": 23.29069709777832,
"blob_id": "6ee3db5609d43747c1484a0ebbfabb8896bf4ba9",
"content_id": "cf94f541494d409404a85f37ca76a2b4d07767be",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 2089,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 86,
"path": "/Sorting Array of Strings.cpp",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "//https://www.hackerrank.com/challenges/sorting-array-of-strings/problem\n\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\nint lexicographic_sort(const char* a, const char* b) {\n return strcmp(a, b);\n}\n\nint lexicographic_sort_reverse(const char* a, const char* b) {\n return strcmp(b, a);\n}\n\nint distinct_chars(const char *a)\n{\n int dist = 0;\n \n while (*a != '\\0') {\n if (!strchr(a + 1, *a))\n dist++;\n a++;\n }\n return dist;\n}\n\nint sort_by_number_of_distinct_characters(const char* a, const char* b) {\n int res = distinct_chars(a) - distinct_chars(b);\n return (res) ? res : lexicographic_sort(a, b);\n}\n\nint sort_by_length(const char* a, const char* b) {\n int res = strlen(a) - strlen(b);\n return (res) ? res : lexicographic_sort(a, b);\n}\n\n/* simple bubble sort :) */\nvoid string_sort(char** arr, const int len,int (*cmp_func)(const char* a, const char* b)) {\n int sorted = 0;\n while (!sorted) {\n sorted = 1;\n for (int i = 0; i < len - 1; i++) {\n if (cmp_func(arr[i], arr[i + 1]) > 0) {\n char *tmp = arr[i];\n arr[i] = arr[i + 1];\n arr[i + 1] = tmp;\n sorted = 0;\n }\n }\n }\n}\n\n\nint main() \n{\n int n;\n scanf(\"%d\", &n);\n \n char** arr;\n\tarr = (char**)malloc(n * sizeof(char*));\n \n for(int i = 0; i < n; i++){\n *(arr + i) = malloc(1024 * sizeof(char));\n scanf(\"%s\", *(arr + i));\n *(arr + i) = realloc(*(arr + i), strlen(*(arr + i)) + 1);\n }\n \n string_sort(arr, n, lexicographic_sort);\n for(int i = 0; i < n; i++)\n printf(\"%s\\n\", arr[i]);\n printf(\"\\n\");\n\n string_sort(arr, n, lexicographic_sort_reverse);\n for(int i = 0; i < n; i++)\n printf(\"%s\\n\", arr[i]); \n printf(\"\\n\");\n\n string_sort(arr, n, sort_by_length);\n for(int i = 0; i < n; i++)\n printf(\"%s\\n\", arr[i]); \n printf(\"\\n\");\n\n string_sort(arr, n, sort_by_number_of_distinct_characters);\n for(int i = 0; i < n; i++)\n printf(\"%s\\n\", arr[i]); \n printf(\"\\n\");\n}\n"
},
{
"alpha_fraction": 0.5137614607810974,
"alphanum_fraction": 0.5573394298553467,
"avg_line_length": 19.714284896850586,
"blob_id": "1116652da6626758f3dd0abe7743bac26a6f39b2",
"content_id": "170ca2a6f48bec817bbe4a8918bf5cda25c6e024",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 436,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 21,
"path": "/set_discard_remove_pop.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 21:52:22 2019\n\n@author: aquib\n\"\"\"\n\nn = int(input())\ns = set(map(int, input().split()))\nnum_ops=int(input())\nfor _ in range(num_ops):\n command=input().split()\n\n if command[0] == 'pop':\n s.pop()\n elif command[0]== 'remove':\n s.remove(int(command[1]))\n elif command[0] == 'discard':\n s.discard(int(command[1]))\nprint(sum(s),end='')\n\n"
},
{
"alpha_fraction": 0.6013985872268677,
"alphanum_fraction": 0.6433566212654114,
"avg_line_length": 21.578947067260742,
"blob_id": "dbb4d38bd6e816c3ee40d996bb92da0bdbb6b23b",
"content_id": "ffe8e97d2bbcfcab6a9d84c779bebcd298e58a5b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 429,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 19,
"path": "/check_strict_superset.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:09:07 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nsetA=set(map(int,input().split()))\ncond=[]\nnumB=int(input())\nfor _ in range(numB):\n setB=set(map(int,input().split()))\n cond1=all([b in setA for b in setB])\n cond2=len(setA)>len(setB)\n cond.append(cond1 and cond2)\n\nprint(all(cond),end='')\n"
},
{
"alpha_fraction": 0.44354838132858276,
"alphanum_fraction": 0.48991936445236206,
"avg_line_length": 23.75,
"blob_id": "698183b5a7b8b3076c58c03bfefdd9e6e7fe1a65",
"content_id": "f7968fb556392c46b864bae6b48ef5678d82fa55",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 496,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 20,
"path": "/find_a_string.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:22:43 2019\n\n@author: aquib\n\"\"\"\n\ndef count_substring(string, sub_string):\n count=0\n for i in range(0, len(string)-len(sub_string)+1):\n if string[i] == sub_string[0]:\n flag=1\n for j in range(0,len(sub_string)):\n if string[i+j] != sub_string[j]:\n flag=0\n break\n if flag==1:\n count = count+1\n return count\n\n"
},
{
"alpha_fraction": 0.5591397881507874,
"alphanum_fraction": 0.5668202638626099,
"avg_line_length": 21.310344696044922,
"blob_id": "f6663f86dd474c6b8cbc266eb0a0ddd53d5c5a69",
"content_id": "03c8cf7707840480873c2c228c1f6f37331d6d06",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 651,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 29,
"path": "/Sets-STL.cpp",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "//https://www.hackerrank.com/challenges/cpp-sets/problem\n\n#include <cmath>\n#include <cstdio>\n#include <vector>\n#include <iostream>\n#include <set>\n#include <algorithm>\nusing namespace std;\n\n\nint main() {\n /* Enter your code here. Read input from STDIN. Print output to STDOUT */ \n int iCount;\n set<int> ss;\n cin>>iCount;\n for(int i=0;i<iCount;i++)\n {\n int type,query;\n cin>>type>>query;\n switch(type)\n {\n case 1: ss.insert(query);break;\n case 2: ss.erase(query);break;\n case 3: cout<<(ss.find(query)==ss.end()?\"No\":\"Yes\")<<endl;break;\n }\n }\n return 0;\n}\n\n\n\n\n"
},
{
"alpha_fraction": 0.5354610085487366,
"alphanum_fraction": 0.588652491569519,
"avg_line_length": 22.5,
"blob_id": "1a8ef669d1f4696427f186f41a885cc450f73b1d",
"content_id": "06ec8b9960981683b743c0dddfb512ec4335ad56",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 282,
"license_type": "no_license",
"max_line_length": 83,
"num_lines": 12,
"path": "/array_mathematics.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:29:43 2019\n\n@author: aquib\n\"\"\"\n\nimport numpy\nN,M=map(int,input().split())\na,b=(numpy.array([input().split() for _ in range(N)], dtype=int) for _ in range(2))\nprint(a+b, a-b, a*b, a//b, a%b, a**b, sep='\\n')\n"
},
{
"alpha_fraction": 0.5339673757553101,
"alphanum_fraction": 0.554347813129425,
"avg_line_length": 19.41666603088379,
"blob_id": "af567b9f28650a025c8dd2b843f542041876fe1b",
"content_id": "3ec40b22c7f0d6e0dc3dcb90a2fe4bd0caffbca8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 736,
"license_type": "no_license",
"max_line_length": 44,
"num_lines": 36,
"path": "/html_parser_part_2.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:10:20 2019\n\n@author: aquib\n\"\"\"\n\nfrom html.parser import HTMLParser\n\nclass MyHTMLParser(HTMLParser):\n def handle_comment(self,data):\n number_of_line=len(data.split('\\n'))\n if number_of_line >1:\n print(\">>> Multi-line Comment\")\n else:\n print(\">>> Single-line Comment\")\n if data.strip():\n print(data)\n\n def handle_data(self,data):\n if data.strip():\n print(\">>> Data\")\n print(data)\n \nparser=MyHTMLParser\nn=int(input())\n \nhtml = \"\" \nfor i in range(n):\n html += input().rstrip()\n html += '\\n'\n \nparser = MyHTMLParser()\nparser.feed(html)\nparser.close()\n\n"
},
{
"alpha_fraction": 0.6390041708946228,
"alphanum_fraction": 0.6452282071113586,
"avg_line_length": 21.85714340209961,
"blob_id": "95839f1bd8e6f1675103d4fa1b724d3e9e0ba94a",
"content_id": "08328134087cd23b9cb5c5fda346e22ed6ed3185",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 482,
"license_type": "no_license",
"max_line_length": 75,
"num_lines": 21,
"path": "/Basic Data Types.cpp",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "//https://www.hackerrank.com/challenges/c-tutorial-basic-data-types/problem\n\n#include <iostream>\n#include <cstdio>\nusing namespace std;\n\nint main() {\n // Complete the code.\n int inta;\n long longa;\n char chara;\n float floata;\n double doublea;\n cin >>inta>>longa>>chara>>floata>>doublea;\n cout<<inta<<endl<<longa<<endl<<chara<<endl;\n cout.precision(3);\n cout<<fixed<<floata<<endl;\n cout.precision(9);\n cout<<fixed<<doublea<<endl;\n return 0;\n}\n\n\n"
},
{
"alpha_fraction": 0.5687204003334045,
"alphanum_fraction": 0.649289071559906,
"avg_line_length": 16.5,
"blob_id": "2cb85820c4ef95e4da63ed169069365be4c4b12a",
"content_id": "75eb0e99812a49505a226b1ee22c64a6243a357e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 211,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 12,
"path": "/eye_identity.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:24:44 2019\n\n@author: aquib\n\"\"\"\n\nimport numpy\nnumpy.set_printoptions(legacy='1.13')\nN,M=map(int,input().split())\nprint(numpy.eye(N,M))\n\n"
},
{
"alpha_fraction": 0.4838709533214569,
"alphanum_fraction": 0.57419353723526,
"avg_line_length": 16.11111068725586,
"blob_id": "6b29f6ca9ffa5224300c7f56bc8f17cde6dcc2e0",
"content_id": "8402025dbfb307da7844c48ed162d8522f1d9397",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 155,
"license_type": "no_license",
"max_line_length": 45,
"num_lines": 9,
"path": "/re_split.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:38:37 2019\n\n@author: aquib\n\"\"\"\n\nregex_pattern = r\"[.,]+\"\t# Do not delete 'r'.\n\n"
},
{
"alpha_fraction": 0.612456738948822,
"alphanum_fraction": 0.6643598675727844,
"avg_line_length": 19.64285659790039,
"blob_id": "5d1de5afdbf737c16e9fa4372bb1f608854c5e85",
"content_id": "04f382dbe54053b5c46d7dae2c4c4dc86f81dfff",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 290,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 14,
"path": "/find_angle.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:31:26 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nimport math\nAB=float(input())\nBC=float(input())\n\nprint(str(int(round(math.degrees(math.atan2(AB,BC))))) + '°')\n"
},
{
"alpha_fraction": 0.5169082283973694,
"alphanum_fraction": 0.5845410823822021,
"avg_line_length": 16.16666603088379,
"blob_id": "a6c1801714d604c49af83556fe8f34e378029eab",
"content_id": "b426f57a9854d540fc9e73ece5d33fe035b3391b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 207,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 12,
"path": "/string_split_join.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:21:36 2019\n\n@author: aquib\n\"\"\"\n\ndef split_and_join(line):\n # write your code here\n x=line.split(' ')\n return '-'.join(x)\n\n"
},
{
"alpha_fraction": 0.5550661087036133,
"alphanum_fraction": 0.6211453676223755,
"avg_line_length": 17.83333396911621,
"blob_id": "c6bee7e2716519a1a60b576b4f93cd3b05d955b4",
"content_id": "2a2e59757f05781d9c88c54f5990e4524aec5a19",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 227,
"license_type": "no_license",
"max_line_length": 86,
"num_lines": 12,
"path": "/text_wrap.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:25:34 2019\n\n@author: aquib\n\"\"\"\n\n\n\ndef wrap(string, max_width):\n return '\\n'.join([string[i:i+max_width] for i in range(0,len(string), max_width)])\n\n"
},
{
"alpha_fraction": 0.5467625856399536,
"alphanum_fraction": 0.6115108132362366,
"avg_line_length": 22.16666603088379,
"blob_id": "0e2a54e25e06d81fb3f412f4d7ac3f82b277f252",
"content_id": "409d95a1d34e18e7d354372c9b51a94b091bc130",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 278,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 12,
"path": "/detect_floating_point_num.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:38:25 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nimport re\nfor _ in range(int(input())):\n print(bool(re.match(r'^[-+]?[0-9]*\\.[0-9]+$',input())))\n"
},
{
"alpha_fraction": 0.4258241653442383,
"alphanum_fraction": 0.4670329689979553,
"avg_line_length": 18.105262756347656,
"blob_id": "3bebe05897a993ff15ac72789e774165271b5260",
"content_id": "a72add716a66c19f9bb8fe85d815ee444fdd2c7e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 364,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 19,
"path": "/merge_tools.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:40:10 2019\n\n@author: aquib\n\"\"\"\n\ndef merge_the_tools(string, k):\n # your code goes here\n l=len(string)\n for i in range(0,l,k):\n s=\"\"\n for j in string[i:i+k]:\n if j in s:\n continue\n else:\n s = s+j\n print(s)\n\n"
},
{
"alpha_fraction": 0.6303191781044006,
"alphanum_fraction": 0.667553186416626,
"avg_line_length": 18.789474487304688,
"blob_id": "fb082240e0f3b377555073e65e11c6b5f59d9c85",
"content_id": "560fbf29339fabd1cd0cb9ffa5eef32e3f45eac8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 376,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 19,
"path": "/symmetric_difference.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:31:11 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nnuma=int(input())\nseta=set(map(int,input().split()))\nnumb=int(input())\nsetb=set(map(int,input().split()))\nu=seta.union(setb)\ni=seta.intersection(setb)\nai=u-i\nai=sorted(ai)\nfor i in ai:\n print(i)\n"
},
{
"alpha_fraction": 0.5066666603088379,
"alphanum_fraction": 0.5566666722297668,
"avg_line_length": 19,
"blob_id": "1a70f41637898ef8889217180afba732c307cd20",
"content_id": "cc671e1360cabb1edd99a930f18d96db88fea74a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 300,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 15,
"path": "/find_runner_up_score.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 21:48:31 2019\n\n@author: aquib\n\"\"\"\n\nif __name__ == '__main__':\n n = int(input())\n arr = map(int, input().split())\n x=sorted(arr)\n second_largest_index=x.count(max(x))\n y=x[:-second_largest_index]\n print(y[-1])\n"
},
{
"alpha_fraction": 0.570588231086731,
"alphanum_fraction": 0.5980392098426819,
"avg_line_length": 21.130434036254883,
"blob_id": "34fc4c5e72e99c3612b3350334cee132e3f00932",
"content_id": "290ac24d7ba1bfba023a5764672da55b41e8b2ce",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 510,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 23,
"path": "/check_subset.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:08:49 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\ntest=int(input())\ncond=[]\nfor _ in range(test):\n numA=int(input())\n setA=set(map(int,input().split()))\n numB=int(input())\n setB=set(map(int,input().split()))\n if all([a in setB for a in setA]):\n cond.append(True)\n else:\n cond.append(False)\n\nfor i in range(len(cond)):\n print(cond[i],\"\\n\",end='')\n\n"
},
{
"alpha_fraction": 0.4372197389602661,
"alphanum_fraction": 0.4730941653251648,
"avg_line_length": 15.44444465637207,
"blob_id": "cc2e52e7d3fc49b1dfdf1f1e95e69e82bffc0821",
"content_id": "f7c41a380fa42691a923b4951afaedc78c64f8e0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 446,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 27,
"path": "/minion_game.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:40:36 2019\n\n@author: aquib\n\"\"\"\n\ndef minion_game(string):\n # your code goes here\n vowels=\"AEIOU\"\n\n k=0\n s=0\n l=len(string)\n for i in range(l):\n if string[i] in vowels:\n k = k + l - i\n else:\n s = s + l - i\n\n if k>s:\n print(\"Kevin\",k)\n elif k<s:\n print(\"Stuart\",s)\n else:\n print(\"Draw\")\n\n\n"
},
{
"alpha_fraction": 0.5123674869537354,
"alphanum_fraction": 0.565371036529541,
"avg_line_length": 14.61111068725586,
"blob_id": "6a1ba052e4a9119742ae7162e4c96f511ec22340",
"content_id": "27c74967340eeabcc26d22f460f819bd08f21082",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 283,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 18,
"path": "/arrays.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:26:41 2019\n\n@author: aquib\n\"\"\"\n\n\n\ndef arrays(arr):\n # complete this function\n # use numpy.array\n l=len(arr)\n x=numpy.zeros(l)\n for i in range(l):\n x[i]=float(arr[l-1-i])\n return x\n\n\n"
},
{
"alpha_fraction": 0.6291666626930237,
"alphanum_fraction": 0.6583333611488342,
"avg_line_length": 23,
"blob_id": "2b58dcc1e5fbbc77cb506e405d9190bd3f9612d3",
"content_id": "bd19c6381dcdd29ed3ab6bb5124028057abdd152",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 480,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 20,
"path": "/detect_html_tags.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:11:09 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nfrom html.parser import HTMLParser\n\nclass MyHTMLParser(HTMLParser):\n def handle_starttag(self, tag,attrs):\n print(tag)\n [print('-> {} > {}'.format(*attr)) for attr in attrs]\n\nhtml='\\n'.join([input() for _ in range(int(input()))])\nparser=MyHTMLParser()\nparser.feed(html)\nparser.close()\n"
},
{
"alpha_fraction": 0.5061224699020386,
"alphanum_fraction": 0.563265323638916,
"avg_line_length": 19.41666603088379,
"blob_id": "ce226bd26219dbe3aa067fdbaeafa8de6e9ece5f",
"content_id": "8b3c64dbb8aabb74f71768eae0b31c0b3a87e8f8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 245,
"license_type": "no_license",
"max_line_length": 51,
"num_lines": 12,
"path": "/tuple.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:14:21 2019\n\n@author: aquib\n\"\"\"\n\nif __name__ == '__main__':\n n = int(input())\n integer_list = tuple(map(int, input().split()))\n print(hash(integer_list),end='')\n"
},
{
"alpha_fraction": 0.5815602540969849,
"alphanum_fraction": 0.631205677986145,
"avg_line_length": 16.625,
"blob_id": "1514df66c0e858e7bf631a8b5774139c97b2cbc4",
"content_id": "dfd3d571f207040bff0aabb4fcd929319186fa37",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 282,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 16,
"path": "/mod_divmod.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:16:46 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\na=int(input())\nb=int(input())\nrem=a//b\nmod=a%b\nprint(rem)\nprint(mod)\nprint(\"(%d, %d)\"%(rem,mod),end='')\n"
},
{
"alpha_fraction": 0.5637707710266113,
"alphanum_fraction": 0.60813307762146,
"avg_line_length": 21.54166603088379,
"blob_id": "52015723ceb6e40f5c5b88529992d7370acc4c7d",
"content_id": "7af7acd5c84b2b1ba8da9413d2bc48a9591f253d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 541,
"license_type": "no_license",
"max_line_length": 69,
"num_lines": 24,
"path": "/valid_credit_card_numbers.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:12:23 2019\n\n@author: aquib\n\"\"\"\n\n# Enter your code here. Read input from STDIN. Print output to STDOUT\nimport re\n\nvalid_structure = r\"[456]\\d{3}(-?\\d{4}){3}$\"\nno_four_repeats = r\"((\\d)-?(?!(-?\\2){3})){16}\"\nfilters=valid_structure, no_four_repeats\noutput=[]\nnum_cc=int(input())\nfor _ in range(num_cc):\n cc=input()\n if all(re.match(f, cc) for f in filters):\n output.append(\"Valid\")\n else:\n output.append(\"Invalid\")\nfor o in output:\n print(o)\n"
},
{
"alpha_fraction": 0.5913461446762085,
"alphanum_fraction": 0.6634615659713745,
"avg_line_length": 19.700000762939453,
"blob_id": "085feef12eeda72460a7506c9db89f65cfd2fb52",
"content_id": "05db4f30b4f25eaca6352e39c15b27d8390739b9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 208,
"license_type": "no_license",
"max_line_length": 50,
"num_lines": 10,
"path": "/mutations.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:21:52 2019\n\n@author: aquib\n\"\"\"\n\ndef mutate_string(string, position, character):\n return string[:position]+c+string[position+1:]\n\n"
},
{
"alpha_fraction": 0.5901162624359131,
"alphanum_fraction": 0.6424418687820435,
"avg_line_length": 23.64285659790039,
"blob_id": "a4d651193fc769541026d6a63f9b78043470aa06",
"content_id": "48aa36816a3dcaedbe0d7eae1dbcaadc8a4feab0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 344,
"license_type": "no_license",
"max_line_length": 57,
"num_lines": 14,
"path": "/concatenate.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Sep 12 02:25:35 2019\n\n@author: aquib\n\"\"\"\n\nimport numpy\nnumpy.set_printoptions(legacy='1.13')\nn,m,p=map(int,input().split())\na=numpy.array([(input().split()) for _ in range(n)], int)\nb=numpy.array([(input().split()) for _ in range(m)], int)\nprint(numpy.concatenate((a,b),axis=0))"
},
{
"alpha_fraction": 0.5070028305053711,
"alphanum_fraction": 0.5462185144424438,
"avg_line_length": 22.733333587646484,
"blob_id": "09e6cca73ea7ae36d09efa8eaf971f35013b2fc8",
"content_id": "6f3e105671ab4f32f58d6ddb7e8378affa0b1025",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 357,
"license_type": "no_license",
"max_line_length": 40,
"num_lines": 15,
"path": "/string_validators.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 22:23:14 2019\n\n@author: aquib\n\"\"\"\n\nif __name__ == '__main__':\n s = input()\n print(any([c.isalnum() for c in s]))\n print(any([c.isalpha() for c in s]))\n print(any([c.isdigit() for c in s]))\n print(any([c.islower() for c in s]))\n print(any([c.isupper() for c in s]))\n\n"
},
{
"alpha_fraction": 0.46439629793167114,
"alphanum_fraction": 0.5170278549194336,
"avg_line_length": 19.1875,
"blob_id": "ffc9ba8a78cdba3a4d847e0ca8cb6afb70947d8a",
"content_id": "2c0794660e9b893d5caa78759309fa5de305a2c8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 323,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 16,
"path": "/list_comprehensions.py",
"repo_name": "aquibjamal/hackerrank_solutions",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python2\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Wed Sep 11 21:48:13 2019\n\n@author: aquib\n\"\"\"\n\nif __name__ == '__main__':\n x = int(input())\n y = int(input())\n z = int(input())\n n = int(input())\n\n ar=[[i,j,k] for i in range(x+1) for j in range(y+1) for k in range(z+1) if i+j+k!=n]\n print(ar)\n"
}
] | 78 |
wtaylor45/power-hour-maker | https://github.com/wtaylor45/power-hour-maker | 102ff60aca63b678cbf9c5527701575f8dd4f188 | b18abd02f2d3822e3bd6a1883a760949a9065e84 | 22678141c1434991ffc5ace25526a9f13c5997dc | refs/heads/master | 2017-12-05T07:46:54.489383 | 2017-03-07T16:53:02 | 2017-03-07T16:53:02 | 83,484,635 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5796943306922913,
"alphanum_fraction": 0.5969432592391968,
"avg_line_length": 27.987340927124023,
"blob_id": "0d567eaf3db13908ca6fb555ef7b95a7a6b6e3a0",
"content_id": "2641d43a511c7c600fa72348e59d700a0180dde1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4580,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 158,
"path": "/phmaker.py",
"repo_name": "wtaylor45/power-hour-maker",
"src_encoding": "UTF-8",
"text": "from pydub import AudioSegment\nimport sys, getopt, logging\nimport os\nimport random\nfrom appJar import gui\n\n### INITIALIZATION ###\n\napp = ''\nbatchmode = False\n\nMAX = -3\n\n### MODEL ###\n\nnum_songs = 0\n\ndef makeph(inputdir, outputfile):\n path = inputdir\n powerhour = 0\n\n songs_added = 0\n\n for subdir, dirs, files in os.walk(path):\n random.shuffle(files)\n for file in files:\n if not file.endswith('.mp3'):\n logging.info('Non-mp3 file found... skipping.')\n continue\n song = trimSong(inputdir + '/' + file)\n powerhour += song\n songs_added += 1\n logging.info('[%s/%s] Added %s to power hour.', songs_added, num_songs, file)\n\n powerhour = powerhour.apply_gain(-powerhour.max_dBFS)\n\n logging.info('Finished creating power hour... exporting power hour to %s', outputfile)\n powerhour.export(outputfile, format=\"mp3\")\n statusUpdate('SUCCESS: Power hour exported to '+outputfile+'.')\n print 'SUCCESS: Power hour exported to '+outputfile+'.'\n\ndef validateFolder(path):\n global num_songs\n num_songs = 0\n\n # Check that there are enough MP3s in the directory\n for subdir, dirs, files in os.walk(path):\n for file in files:\n if not file.endswith('.mp3'):\n continue\n num_songs += 1\n\n if num_songs < 60:\n logging.error('ERROR: 60 mp3s are required for a power hour!')\n statusUpdate('Warning: 60 mp3s are required for a full power hour, only '+str(num_songs)+' found!')\n return 0\n\n logging.info('Validated input directory.')\n statusUpdate('Valid input folder!')\n\ndef trimSong(file):\n sound = AudioSegment.from_mp3(file)\n transition = AudioSegment.from_mp3('assets/transition.mp3')\n transition = transition.apply_gain(-3)\n\n start = sound[35000:]\n start = start.fade_in(1000)\n start = start.overlay(transition)\n song = start[:60000]\n\n song = song.apply_gain(-song.max_dBFS)\n\n return song\n\ndef parseInput(argv):\n inputdir = \"\"\n outputfile = \"\"\n\n try:\n opts, args = getopt.getopt(argv,\"bvhi:o:\")\n except getopt.GetoptError:\n logging.error('Missing argument! Use `phmaker.py -h` for help')\n sys.exit(2)\n for opt, arg in opts:\n if opt == '-h':\n print 'USAGE: phmaker.py -i <inputfolder> -o <outputfile> [-v, -h]'\n sys.exit()\n elif opt == \"-i\":\n if not os.path.isdir(arg):\n logging.error('Invalid input directory. Directory \\''+arg+'\\' not found.')\n sys.exit(2);\n validateFolder(arg)\n inputdir = arg\n logging.info('Found input directory.')\n elif opt == \"-o\":\n outputfile = arg\n elif opt == '-v':\n logging.getLogger().setLevel(logging.INFO)\n\n makeph(inputdir, outputfile)\n\n### CONTROLLER ###\n\ninputdir = ''\noutputfile = ''\n\ndef press(btn):\n if btn == 'Generate':\n makeph(app.getEntry(\"folder\"), app.getEntry('file'))\n elif btn == 'Input Folder':\n inputdir = app.directoryBox(title=None, dirName=None)\n app.setEntry('folder', inputdir)\n validateFolder(inputdir)\n app.enableButton(\"Generate\")\n elif btn == 'Output File':\n outputfile = app.directoryBox(title=None, dirName=None)\n app.setEntry('file', outputfile+'/powerhour.mp3')\n\ndef statusUpdate(message):\n if batchmode == False:\n app.setLabel('status', str(message));\n\n\n### VIEW ###\n\ndef initUI():\n global app\n app = gui(\"MakePH\", \"700x300\")\n\n app.setStretch('column')\n app.addButtons([\"Input Folder\"], press, 1, 0, 1) # Row 3,Column 0,Span 2\n app.addEntry(\"folder\", 1, 1) # Row 1,Column 1\n app.addButtons([\"Output File\"], press, 2, 0, 1) # Row 3,Column 0,Span 2\n app.addEntry(\"file\", 2, 1) # Row 1,Column 1\n app.setEntry(\"file\", os.getcwd()+'/powerhour.mp3')\n app.addLabel(\"status\", '', 3, 1)\n app.addButtons([\"Generate\"], press, 4, 0, 2) # Row 3,Column 0,Span 2\n app.disableButton(\"Generate\")\n app.setEntryFocus(\"folder\")\n\n app.go()\n\n# Start her up\n\nif __name__ == \"__main__\":\n logging.basicConfig(stream=sys.stderr, level=logging.INFO, format='%(levelname)s: %(message)s')\n\n if '-b' in str(sys.argv):\n # Check to make sure input and output are specified\n if not '-i' in str(sys.argv) or not '-o' in str(sys.argv):\n logging.error('Missing option! Use `phmaker.py` -h for help')\n sys.exit(2)\n\n batchmode = True\n parseInput(sys.argv[1:])\n\n else:\n initUI()\n"
},
{
"alpha_fraction": 0.7830188870429993,
"alphanum_fraction": 0.801886796951294,
"avg_line_length": 105,
"blob_id": "96720cdce7d51cb6340ac1a1a3cc0484f4bc013f",
"content_id": "1ece52896c43caab39bebd9fe31649d04cb55629",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 106,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 1,
"path": "/README.md",
"repo_name": "wtaylor45/power-hour-maker",
"src_encoding": "UTF-8",
"text": "Python tool to automatically create power hours from 60 songs. Does not encourage any kind of drinking...\n"
}
] | 2 |
parkskevin/cs325_project | https://github.com/parkskevin/cs325_project | cd8253c764e64dde31ca45e39d48e546c3a2355a | 36284fa61179486eb6061237b0872c4ca28e2097 | db54d1f01dad275daea1545a03666b2f6ddcd376 | refs/heads/master | 2021-01-18T14:19:10.379228 | 2015-06-08T03:26:46 | 2015-06-08T03:26:46 | 34,091,905 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7105262875556946,
"alphanum_fraction": 0.7368420958518982,
"avg_line_length": 43.55172348022461,
"blob_id": "8d5ac612b17df179f9aff2605f8623bc9c1f0e00",
"content_id": "9c4a2194ef559e31add04e423bd74b1c2df8be05",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 1292,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 29,
"path": "/project2/README.txt",
"repo_name": "parkskevin/cs325_project",
"src_encoding": "UTF-8",
"text": "#README FILE\n#Authors: Daniel Bonnin, Kevin Parks, Alex Thomas\n#Group: 11\n#Class: CS235 Spring 2015\n#Assgn: Project 2\n\nOur project consists of the following components:\n\t1. coin.py - primary project executable, does CoinChange work\n\t2. README - this file\n\t3. Report_Project2_Group11.pdf - documentation required for project\n\t\nTo run the program:\n\t1. Ensure all components are located in the same directory\n\t2. Run 'coin.py -f filename' from the command line. 'filename' should be the path to a valid input file.\n\t\t2a. Note: we expect the input file to be sorted, and well formed as this example shows:\n\t\t\t[1, 2, 3, 4]\n\t\t\t15\n\t\t\t\n\t\t\tNote that the coin denominations are presented first, the amount in question second. The\n\t\t\tfile is ended with a blank line return.\n\t\t2b. If python is not in your path, then run 'path/to/python coin.py -f filename'\n\t\t3b. ***ATTENTION***: if the Amount value > 31, algorithm 1 will not be run. This algorithm is\n\t\t\ttoo inefficient for values beyond 31.\n\t3. The program should output a file named '[filename]change.txt', where [filename] is the prefix of\n\t the input file selected in #2 above. This file contains solutions for each algorithm the project\n\t requires. It outputs in the following order:\n\t\t- slowchange solutions\n\t\t- changegreedy solutions\n\t\t- changedp solutions\n"
},
{
"alpha_fraction": 0.4642857015132904,
"alphanum_fraction": 0.5082417726516724,
"avg_line_length": 22.399999618530273,
"blob_id": "a008d397bae1d2f25319c2b04d2bea82c3c12c67",
"content_id": "0f19146f47d73a2e3b25f6c3902df530797b5ed1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 364,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 15,
"path": "/project2/testFiles/testGen.py",
"repo_name": "parkskevin/cs325_project",
"src_encoding": "UTF-8",
"text": "import random\r\nout = open('a2Problem8.txt', 'w')\r\ntestArr = []\r\ncurV = 1\r\nfor i in range(10, 110, 10):\r\n for j in range(i):\r\n testArr.append(curV)\r\n inc = random.randint(1, 5)\r\n curV += inc\r\n testArr.sort()\r\n for k in range(5):\r\n out.write(str(testArr) + \"\\n\")\r\n out.write(str(30) + \"\\n\")\r\n testArr = []\r\n curV = 1"
},
{
"alpha_fraction": 0.5099009871482849,
"alphanum_fraction": 0.5742574334144592,
"avg_line_length": 14.538461685180664,
"blob_id": "df118d0b5bf24f83f6cfa0e13aac254ca4e353f5",
"content_id": "fbc2b1ac604f39e7b2d9e58b2ddfaf7a537bf1fc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 202,
"license_type": "no_license",
"max_line_length": 34,
"num_lines": 13,
"path": "/project2/MakeAmounts.py",
"repo_name": "parkskevin/cs325_project",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python\n\nV = [1, 5, 10, 25, 50]\namount = 1\nincrement = 2\nf = open(\"Amount4_Small.txt\", 'w')\n\nwhile amount <= 31:\n\tf.write(\"%s\\n\" % V)\n\tf.write(\"%s\\n\" % amount)\n\tamount += increment\n\nf.close()\n"
},
{
"alpha_fraction": 0.6743252873420715,
"alphanum_fraction": 0.6858131289482117,
"avg_line_length": 30.55021858215332,
"blob_id": "770b2b6c317a01029bd2265b4a5ea90201c7cb85",
"content_id": "6f68fabf9edadddccff4781e19ee1135e2d493b1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7225,
"license_type": "no_license",
"max_line_length": 106,
"num_lines": 229,
"path": "/project4/turnIn/tsp.py",
"repo_name": "parkskevin/cs325_project",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python\n\n#Author: Daniel Bonnin, Kevin Parks, Alex Thomas\n#email: [email protected]\n#class: CS325\n#Assgn: Project 4\n#Descr: This program calculates a tour of minimum distance between points on\n# \t\t Cartesion plane. \n#\n#Input: This program takes a text file as input.\n#\n#Usage: Without arguments, the program returns an error on usage\n#\n# Usage: python tsp.py (<input filepath>)\n\nimport sys #for maxint\nimport timeit #for timings\nimport math #for sqrt and round\nimport argparse #for parsing args\nimport re #for regex\nimport operator #for prim sorting\nimport signal #for stopping\n\n\n#Source: tsp-verifier.py from supplied project files\ndef distance(a,b):\n\t# a and b are integer pairs (each representing a point in a 2D, integer grid)\n\t# Euclidean distance rounded to the nearest integer:\n\tdx = a[0]-b[0]\n\tdy = a[1]-b[1]\n\t#return int(math.sqrt(dx*dx + dy*dy)+0.5) # equivalent to the next line\n\treturn int(round(math.sqrt(dx*dx + dy*dy)))\n\t\n#Source: tsp-verifier.py from supplied project files\ndef readinstance(filename):\n\t# each line of input file represents a city given by three integers:\n\t# identifier x-coordinate y-coordinate (space separated)\n\t# city identifiers are always consecutive integers starting with 0\n\t# (although this is not assumed here explicitly,\n\t# it will be a requirement to match up with the solution file)\n\tf = open(filename,'r')\n\tline = f.readline()\n\tcities = []\n\twhile len(line) > 1:\n\t\tlineparse = re.findall(r'[^,;\\s]+', line)\n\t\tcities.append([int(lineparse[1]),int(lineparse[2])])\n\t\tline = f.readline()\n\tf.close()\n\treturn cities\n\ndef adjList(cities):\n\tn = len(cities)\n\tadj = []\n\tfor i in range(n):\n\t\tadj.append([])\n\t\tfor j in range(n):\n\t\t\tif i == j:\n\t\t\t\tadj[i].append((j, sys.maxint))\n\t\t\telse:\n\t\t\t\tadj[i].append((j, distance(cities[i], cities[j])))\n\t#greedy sorting, move shortest distances in general to front\n\tfor i in range(len(adj)):\n\t\tadj[i].sort(key = operator.itemgetter(1))\n\treturn adj\t\n\t\t\ndef prims(adj):\n\t#generate minimum spanning tree of coordinates in cities\n\ttreeV = []\n\ttreeE = []\n\ttreeV.append(0)\n\tuniqueV = set()\n\tuniqueV.add(0)\n\twhile len(treeV) < len(adj):\n\t\tminEdge = sys.maxint\n\t\tminIndexOut = 0 #in treeV\n\t\tminIndexIn = 0 #to add to treeV\n\t\t#Find shortest outgoing edge from current tree\n\t\t#Iterate through treeV\n\t\tfor i in range(len(treeV)):\n\t\t\t#grab the first matching vertex that meets the criteria, then break, we're done because they are sorted\n\t\t\tfor index, value in adj[treeV[i]]:\n\t\t\t\tif (index not in uniqueV):\n\t\t\t\t\tadj[treeV[i]] = [x for x in adj[treeV[i]] if adj[treeV[i]][0] == index]\n\t\t\t\t\tminEdge = value\n\t\t\t\t\tminIndexIn = index\n\t\t\t\t\tminIndexOut = treeV[i]\n\t\t\t\t\tbreak\n\t\ttreeV.append(minIndexIn)\n\t\tuniqueV.add(minIndexIn)\n\t\ttreeE.append((minIndexOut, minIndexIn))\n\treturn (treeV, treeE)\n\t\ndef outputResults(cities, cityOrder, outFile):\n\tdist = 0\n\tfor i in range(1, len(cityOrder), 1):\n\t\tdist += distance(cities[cityOrder[i]], cities[cityOrder[i - 1]])\n\t#need route to root added since can't be in cityOrder list for verifier\n\tdist += distance(cities[cityOrder[i]], cities[cityOrder[0]])\n\toutFile.write(str(dist) + \"\\n\")\n\n\tfor i in cityOrder:\n\t\toutFile.write(str(i) + \"\\n\")\n\ndef matlabGraph(cities, cityOrder):\n\tgraphFile = open(\"matlabGraph.txt\", 'w')\n\tgraphFile.write(\"x=[\")\n\tfor i in range(len(cities)):\n\t\tgraphFile.write(str(cities[i][0]) + \" \")\n\tgraphFile.write(\"];\\n\")\n\tgraphFile.write(\"y=[\")\n\tfor i in range(len(cities)):\n\t\tgraphFile.write(str(cities[i][1]) + \" \")\n\tgraphFile.write(\"];\\n\")\n\tgraphFile.write(\"hold on;\\n\")\n\tgraphFile.write(\"scatter(x, y)\\n\")\n\tx = []\n\ty = []\n\tfor i in range(1, len(cityOrder), 1):\n\t\tx.append([cities[cityOrder[i-1]][0],cities[cityOrder[i]][0]])\n\t\ty.append([cities[cityOrder[i-1]][1],cities[cityOrder[i]][1]])\n\tfor i in range(len(x)):\n\t\tgraphFile.write(\"plot([\" + str(x[i][0]) + \" \" + str(x[i][1]) + \\\n\t\t\t\"],[\" + str(y[i][0]) + \" \" + str(y[i][1]) + \"]);\\n\")\n\n\tgraphFile.close()\ndef triangleFunc(cities, order):\n\tfor i in range(len(order) - 3):\n\t\t#if distance i->i+2->i+1->i+3 < i->i+1->i+2->i+3,\n\t\t#swap i+1, i+2 \n\t\tif distance(cities[order[i]], cities[order[i + 2]]) + \\\n\t\t distance(cities[order[i + 2]], cities[order[i + 1]]) + \\\n\t\t distance(cities[order[i + 1]], cities[order[i + 3]]) < \\\n\t\t distance(cities[order[i]], cities[order[i + 1]]) + \\\n\t\t distance(cities[order[i + 1]], cities[order[i + 2]]) + \\\n\t\t distance(cities[order[i + 2]], cities[order[i + 3]]):\n\t\t swap = order[i + 1]\n\t\t order[i + 1] = order[i + 2]\n\t\t order[i + 2] = swap\n\treturn order\n\ndef totalDist(cities, inOrder):\n\tpathLength = 0\n\tfor i in range(1, len(inOrder), 1):\n\t\tpathLength += distance(cities[inOrder[i]], cities[inOrder[i - 1]])\n\tpathLength += distance(cities[inOrder[0]], cities[inOrder[len(inOrder)-1]])\n\treturn pathLength\n\ndef findLastStop(cities, inOrder):\n\tminDist = totalDist(cities, inOrder)\n\tminOrder = inOrder\n\tfor i in range(1, len(inOrder) - 2, 1):\n\t\tcurOrder = [x for x in inOrder]\n\t\tswap = curOrder[i]\n\t\tcurOrder[i] = curOrder[len(curOrder) - 1]\n\t\tcurOrder[len(curOrder) - 1] = swap\n\t\tcurDist = totalDist(cities, curOrder)\n\t\tif curDist < minDist:\n\t\t\tminDist = curDist\n\t\t\tminOrder = [x for x in curOrder]\n\treturn minOrder\n\n#does essentially the same as outputResults, but used as global handler for SIGTERM\n#not sure what happens if we invoke SIGTERM before these globals are allocated...\ndef handler(signum, frame):\n\tdist = 0\n\tfor i in range(1, len(lastGoodOrder), 1):\n\t\tdist += distance(lastCities[lastGoodOrder[i]], cities[lastGoodOrder[i - 1]])\n\t#need route to root added since can't be in cityOrder list for verifier\n\tdist += distance(lastCities[lastGoodOrder[i]], lastCities[lastGoodOrder[0]])\n\tlastFileOut.write(str(dist) + \"\\n\")\n\n\tfor i in lastGoodOrder:\n\t\tlastFileOut.write(str(i) + \"\\n\")\n\tsys.exit()\n\t\ndef calcTsp(cities, outFile):\n\t#Input: an array of x, y cartesian coordinates\n\t#Output: an approximate shortest path between input coordinates\n\tadj = adjList(cities)\n\tmst = prims(adj)\n\t\n\t#prepare for the optimization loop by setting locals to compare against,\n\t#each time we improve, overwrite global so it may be used\n\t#in signal handler of SIGTERM\n\tinOrder = mst[0]\n\tminDist = totalDist(cities, inOrder)\n\tstopFlag = 0\n\t#print str(minDist)\n\tglobal lastGoodOrder\n\tglobal lastCities\n\tglobal lastFileOut\n\tlastGoodOrder = inOrder\n\tlastCities = cities\n\tlastFileOut = outFile\n\t#configure signal handler\n\tsignal.signal(signal.SIGTERM, handler)\n\t\n\t#remove curly q's, optimizing routine\n\twhile (1):\n\t\tinOrder = triangleFunc(cities, inOrder)\n\t\tinOrder = findLastStop(cities, inOrder)\n\t\tnewDist = totalDist(cities, inOrder)\n\t\tif(newDist < minDist):\n\t\t\tminDist = newDist\n\t\t\tlastGoodOrder = inOrder\n\t\t\t#print minDist\n\t\telse:\n\t\t\tbreak\n\t\t\t#print \"stopped at: \", minDist\n\t#matlabGraph(cities, inOrder)\n\toutputResults(cities, lastGoodOrder, outFile)\n\n#cmd line args parser setup\nparser = argparse.ArgumentParser(description=\"Enter an input file path\")\nparser.add_argument(\"inputFile\", type=str, help=\"Path to input file\")\nargs = parser.parse_args()\n\n#setup output file\noutFileName = args.inputFile + \".tour\"\nout = open(outFileName, 'w')\n\n#parse cities into a list of lists.\ncities = readinstance(args.inputFile)\n\n#print(str(timeit.timeit(lambda:calcTsp(cities, out),number=1)))\ncalcTsp(cities, out)\n\nif (out):\n\tout.close()\n"
},
{
"alpha_fraction": 0.7567567825317383,
"alphanum_fraction": 0.8648648858070374,
"avg_line_length": 36,
"blob_id": "f94e44f56f975194bea3a95253620a3f810a7927",
"content_id": "c3568ee715258a32c233d6b74e8a7466f99604ca",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 37,
"license_type": "no_license",
"max_line_length": 36,
"num_lines": 1,
"path": "/project1/notes.txt",
"repo_name": "parkskevin/cs325_project",
"src_encoding": "UTF-8",
"text": "Directory housing project1 for CS325\n"
},
{
"alpha_fraction": 0.7092511057853699,
"alphanum_fraction": 0.7334801554679871,
"avg_line_length": 45.78947448730469,
"blob_id": "2e51d1e0bbb647a0a24765193d03346ca2775b3a",
"content_id": "ed71081e91bdbf0e67848724e7c12820620b0c90",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 908,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 19,
"path": "/project4/README.txt",
"repo_name": "parkskevin/cs325_project",
"src_encoding": "UTF-8",
"text": "#README FILE\r\n#Authors: Daniel Bonnin, Kevin Parks, Alex Thomas\r\n#Group: 11\r\n#Class: CS235 Spring 2015\r\n#Assgn: Project 4\r\n\r\nOur project consists of the following components:\r\n\t1. tsp.py - primary project executable\r\n\t2. README - this file\r\n\t3. Report_Project4_Group11.pdf - documentation required for project\r\n\t4. *.tour files - files generated from our code for verification of our minimum tour lengths computed\r\n\t\r\nTo run the program:\r\n\t1. Ensure all components are located in the same directory\r\n\t2. Run 'tsp.py filename' from the command line. 'filename' should be the path to a valid input file.\r\n\t\t2b. If python is not in your path, then run 'path/to/python tsp.py filename'\r\n\t3. The program should output a file named '[filename].tours', where [filename] is the entire name of\r\n\t the input file selected in #2 above. This file contains a solution tour for the input file\r\n\t and can be verified via tsp-verifier.\r\n"
},
{
"alpha_fraction": 0.4209115207195282,
"alphanum_fraction": 0.5227882266044617,
"avg_line_length": 19.16216278076172,
"blob_id": "6058935172b8e685f4d8170117fd44f4d99ef56f",
"content_id": "aaa924f51029e79b8e77f9437ec857debd1fdb9e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 746,
"license_type": "no_license",
"max_line_length": 52,
"num_lines": 37,
"path": "/project1/testCases/printKey.sh",
"repo_name": "parkskevin/cs325_project",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\n\necho \"***** Case 1 *****\"\necho \"Subarray: 8, 1, 3, 3, 1, -1, -4, -6, 2, 8, 19\"\necho \"Max sum: 34\"\necho\necho \"***** Case 2 *****\"\necho \"Subarray: 2, 9, 8, 6, 5\"\necho \"Max sum: 30\"\necho\necho \"***** Case 3 *****\"\necho \"Subarray: 23, 24, -1, -7, -8, 19\"\necho \"Max sum: 50\"\necho\necho \"***** Case 4 *****\"\necho \"Subarray: 59, 26, -53, 58, 97\"\necho \"Max sum: 187\"\necho\necho \"***** Case 5 *****\"\necho \"Subarray: 3, 2, 1, 1\"\necho \"Max sum: 7\"\necho\necho \"***** Case 6 *****\"\necho \"Subarray: 12, 99, 99\"\necho \"Max sum: 210\"\necho\necho \"***** Case 7 *****\"\necho \"Subarray: 4, -1, 2, 1\"\necho \"Max sum: 6\"\necho\necho \"***** Case 8 *****\"\necho \"Subarray: (empty)\"\necho \"Max sum: 0\"\necho\necho \"***** Case 9 *****\"\necho \"Subarray: 5\"\necho \"Max sum: 5\"\n"
},
{
"alpha_fraction": 0.6209506392478943,
"alphanum_fraction": 0.6311736702919006,
"avg_line_length": 28.537254333496094,
"blob_id": "928e1fe711d9592d7d4c96bdff0b2afebd09e28d",
"content_id": "4fc3a565990be1edc46c5b83901d15ed81c5ae3c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7532,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 255,
"path": "/project1/algo.py",
"repo_name": "parkskevin/cs325_project",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python\n\n#Author: Daniel Bonnin, Kevin Parks, Alex Thomas\n#email: [email protected]\n#class: CS325\n#Assgn: Project 1\n#Descr: This program calculates a maximum sum array using 1 of 4 algorithms. \n#\n#Input: The program takes a text file as input. The program reads\n# each line in the input file as a separate input. If no input file \n# is specified, the program will attempt to open MSS_Problems.txt\n#\n#Usage: Without arguments, the program reads from MSS_Problems.txt and\n# writes results to MSS_Results.txt\n#\n# The argument -a followed by a number 1-4 indicates an algorithm\n# to use to calculate the maximum sum array. \n#\n# The argument -f followed by a file name indicates the input text\n# file to use. \n#\n#\t\t The argument -r following by an integer > 0 indicated to use\n#\t\t a randomly generated file containing 'value' arrays as input.\n#\n#\t\t The argument -t turns off printing, and outputs Excel format of\n#\t 2 columns: array size and timing result. \n#\n# Usage: python algo.py [-a <1-4>] [-f <filepath> XOR -r <arrays>] [-t]\n\nimport sys #for maxint\nimport timeit #for timings\nimport argparse #cmd line arg parsing\nimport rand #random file generator\n\n#constants\nRANDFILE = \"rnums.txt\"\nMSSFILE = \"MSS_Problems.txt\"\nOUTPUTFILE = \"MSS_Results.txt\"\n\ndef a1(arr):\n\tcurMaxSubArray = -sys.maxint\n\tcurMaxStart = -1\n\tcurMaxEnd = -1\n\tfor i in range(len(arr)):\n\t for j in range(i, len(arr)):\n\t curSum = sum(arr[i : j + 1])\n\t if (curSum > curMaxSubArray):\n\t curMaxSubArray = curSum\n\t curMaxStart = i\n\t curMaxEnd = j\n\treturn arr[curMaxStart:curMaxEnd + 1]\n\ndef a2(arr):\n\tcurMaxSubArray = -sys.maxint\n\tcurMaxStart = -1\n\tcurMaxEnd = -1\n\tfor i in range(len(arr)):\n\t\tcurSum = 0\n\t\tfor j in range(i, len(arr)):\n\t\t\tcurSum += arr[j]\n\t\t\tif (curSum > curMaxSubArray):\n\t\t\t\tcurMaxSubArray = curSum\n\t\t\t\tcurMaxStart = i\n\t\t\t\tcurMaxEnd = j\n\treturn arr[curMaxStart:curMaxEnd + 1]\n\ndef a3(arr):\n\tdef recSubArr(arr, low, high):\n\t\tif high == low:\n\t\t\treturn (low, high, arr[low])\n\t\telse: \n\t\t\tmid = (low + high) / 2 \n\t\t\t(lLow, lHigh, lSum) = recSubArr(arr, low, mid)\n\t\t\t(rLow,rHigh,rSum) = recSubArr(arr, mid + 1, high)\n\t\t\t(cLow,cHigh,cSum) = crossSub(arr,low,mid,high)\n\t\tif lSum >= rSum and lSum >= cSum:\n\t\t\treturn (lLow, lHigh, lSum)\n\t\telif rSum >= lSum and rSum >= cSum:\n\t\t\treturn (rLow, rHigh, rSum)\n\t\telse:\n\t\t\treturn (cLow, cHigh, cSum)\n\t\n\tdef crossSub(arr, low, mid, high):\n\t\tlSum = -sys.maxint\n\t\trSum = -sys.maxint\n\t\tcurSum = 0\n\t\tmaxLeft = -sys.maxint\n\t\tmaxRight = -sys.maxint\n\t\tfor i in range(mid, low -1, -1):\n\t\t\t\tcurSum = curSum + arr[i]\n\t\t\t\tif (curSum > lSum):\n\t\t\t\t\tlSum = curSum\n\t\t\t\t\tmaxLeft = i\n\t\tcurSum = 0\n\t\tfor j in range(mid + 1, high + 1):\n\t\t\tcurSum = curSum + arr[j]\n\t\t\tif curSum > rSum:\n\t\t\t\trSum = curSum\n\t\t\t\tmaxRight = j\n\t\treturn (maxLeft, maxRight, lSum + rSum)\n\tresult = recSubArr(arr, 0, len(arr) - 1)\n\treturn arr[result[0] : result[1] + 1]\n\ndef a4(arr):\n\ttemp_sum = 0\n\tmax_sum = -sys.maxint\n\ttemp_start = 0#holds the start index of intermediate sum\n\tmax_start = 0#holds the start index of max sum\n\tmax_end = 0 #holds the end index of max sum\n\t\n\tfor x in xrange(0,len(arr)):\n\t\ttemp_sum = temp_sum + arr[x]\n\t\t\n\t\tif temp_sum > max_sum:\n\t\t\tmax_sum = temp_sum\n\t\t\tmax_start = temp_start\n\t\t\tmax_end = x\n\t\tif temp_sum < 0:\n\t\t\ttemp_sum = 0\n\t\t\ttemp_start = x+1\n\n\treturn arr[max_start:max_end + 1]\n\t\ndef printResults(arr, subArr, maxSum, mssTest, file):\n\tif not(mssTest):\n\t\tif(file):\n\t\t\tfile.write(\"Original Array: %s\\n\" % arr)\n\t\telse:\n\t\t\tprint(\"Original Array: %s\" % arr)\n\tif (maxSum > 0):\n\t\tif(file):\n\t\t\tfile.write(\"Subarray: %s\\n\" % subArr)\n\t\t\tfile.write(\"Max Sum: %d\\n\" % maxSum)\n\t\telse:\n\t\t\tprint(\"Subarray: %s\" % subArr)\n\t\t\tprint(\"Max Sum: %d\" % maxSum) \n\telse: \n\t\tif(file):\n\t\t\tfile.write(\"Subarray: (empty)\\n\")\n\t\t\tfile.write(\"Max Sum: 0 **** Note at least one value in the\" + \\\n\t\t\t\t \" array must be positive\\n\")\n\t\telse:\n\t\t\tprint \"Subarray: (empty)\"\n\t\t\tprint \"Max Sum: 0 **** Note at least one value in the\" + \\\n\t\t\t\t \" array must be positive\"\n\t\n#cmd line args parser setup\nparser = argparse.ArgumentParser(description=\"Find maximum sum sub-array. No args does MSS_Results.txt test\")\nparser.add_argument(\"-a\", \"--algo\", type=int, help=\"The choice of algorithm(1-4)\")\nparser.add_argument(\"-f\", \"--file\", help=\"Path to input file\")\nparser.add_argument(\"-r\", \"--rand\", type=int, help=\"Randomly generated\")\nparser.add_argument(\"-t\", \"--timing\", help=\"record timings\", action=\"store_true\")\nargs = parser.parse_args()\n\n#cmd line args logic\nmssTest = False #whether we're printing to the MSS_Results.txt\nout = False #file handle to MSS_Results.txt\n\n#if not cmd line args, do MSS_Results.txt action\nif not (len(sys.argv) > 1):\n\tmssTest = True\n\tout = file(OUTPUTFILE, 'w')\nelif not (args.algo):\n\tparser.error(\"No algorithm specified\")\nelif (args.algo > 4 or args.algo < 1):\n\tparser.error(\"Choose an algorithm 1-4\")\nif (args.file and args.rand):\n\tparser.error(\"Cannot do create random and open existing file. Choose one.\")\nelif (not args.file):\n\t#no file, so random is an option\n\tif(args.rand):\n\t\targs.file = RANDFILE\n\telse:\n\t\targs.file = MSSFILE\n\nif not (mssTest):\n\t#debug\n\tprint \"Input file: \" + args.file\n\tprint \"Selected algorithm: \" + str(args.algo)\n\n#if args.rand is used, make the file first\nif(args.rand):\n\t#needs some sanitizing funcs here\n\trand.make_rand(args.rand)\n\n#open whichever file as input\nf = open(args.file, 'r')\n\n#create the master list to hold each array as another list (2D array)\n#append each array as new list of ints for each line of text read from file\ntestArr = []\nfor i, line in enumerate(f):\n\ttestArr.append([])\n\ttestArr[i].append(map(int, line.replace(\"[\", \"\").replace(\"]\", \"\").replace(\"\\n\", \"\").split(',')))\nf.close()\n\n#for each algorithm, find the subarray, calculate the sum, then print\nif (args.algo == 1 or mssTest):\n\tif not (args.timing or isinstance(out, bool)):\n\t\tout.write(\"******************** Algorithm 1 ********************\\n\")\n\tfor i in testArr:\n\t\tfor j in i:\n\t\t\tif (args.timing):\n\t\t\t\tprint(str(len(j))+\", \"+str(timeit.timeit(lambda:a1(j),number=1)))\n\t\t\telse:\n\t\t\t\tsubArray = a1(j)\n\t\t\t\ttotalSum = sum(subArray)\n\t\t\t\tprintResults(j, subArray, totalSum, mssTest, out)\n\t\t\t\tif not (mssTest):\n\t\t\t\t\tprint(\"\")\n\nif (args.algo == 2 or mssTest):\n\tif not (args.timing or isinstance(out, bool)):\n\t\tout.write(\"******************** Algorithm 2 ********************\\n\")\n\tfor i in testArr:\n\t\tfor j in i:\n\t\t\tif (args.timing):\n\t\t\t\tprint(str(len(j))+\", \"+str(timeit.timeit(lambda:a2(j),number=1)))\n\t\t\telse:\n\t\t\t\tsubArray = a2(j)\n\t\t\t\ttotalSum = sum(subArray)\n\t\t\t\tprintResults(j, subArray, totalSum, mssTest, out)\n\t\t\t\tif not (mssTest):\n\t\t\t\t\tprint(\"\")\n\nif (args.algo == 3 or mssTest):\n\tif not (args.timing or isinstance(out, bool)):\n\t\tout.write(\"******************** Algorithm 3 ********************\\n\")\n\tfor i in testArr:\n\t\tfor j in i:\n\t\t\tif (args.timing):\n\t\t\t\tprint(str(len(j))+\", \"+str(timeit.timeit(lambda:a3(j),number=1)))\n\t\t\telse:\n\t\t\t\tsubArray = a3(j)\n\t\t\t\ttotalSum = sum(subArray)\n\t\t\t\tprintResults(j, subArray, totalSum, mssTest, out)\n\t\t\t\tif not (mssTest):\n\t\t\t\t\tprint(\"\")\n\nif (args.algo == 4 or mssTest):\n\tif not (args.timing or isinstance(out, bool)):\n\t\tout.write(\"******************** Algorithm 4 ********************\\n\")\n\tfor i in testArr:\n\t\tfor j in i:\n\t\t\tif (args.timing):\n\t\t\t\tprint(str(len(j))+\", \"+str(timeit.timeit(lambda:a4(j),number=1)))\n\t\t\telse:\n\t\t\t\tsubArray = a4(j)\n\t\t\t\ttotalSum = sum(subArray)\n\t\t\t\tprintResults(j, subArray, totalSum, mssTest, out)\n\t\t\t\tif not (mssTest):\n\t\t\t\t\tprint(\"\")\n\nif (out):\n\tout.close()\n"
},
{
"alpha_fraction": 0.60317462682724,
"alphanum_fraction": 0.6984127163887024,
"avg_line_length": 20,
"blob_id": "b5df0f1822b818d37766193891279e92e74d61dc",
"content_id": "6856b5b6d728bc49319ec25f399b6516b90e9caa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 63,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 3,
"path": "/README.md",
"repo_name": "parkskevin/cs325_project",
"src_encoding": "UTF-8",
"text": "# cs325_project\nCS325 Projects\nAuthors: Daniel Bonnin, Kevin Parks, Alex Thomas\n"
},
{
"alpha_fraction": 0.6356589198112488,
"alphanum_fraction": 0.6477987170219421,
"avg_line_length": 28.46982765197754,
"blob_id": "53d7ac58e0b61f3648b69d3ceb2daa269f887f6a",
"content_id": "07508830640c07bb6c5d4a04153fae6135c8e4c6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6837,
"license_type": "no_license",
"max_line_length": 102,
"num_lines": 232,
"path": "/project2/oldcoin.py",
"repo_name": "parkskevin/cs325_project",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python\n\n#Author: Daniel Bonnin, Kevin Parks, Alex Thomas\n#email: [email protected]\n#class: CS325\n#Assgn: Project 2\n#Descr: This program calculates the least amount of coins necessary\n#\t to fulfill a given integer value currency. \n#\n#Input: //TODO\n#\n#Usage: //TODO\n\nimport sys #for maxint\nimport timeit #for timings\nimport argparse #cmd line arg parsing\n\n#constants\nINPUTFILE = \"Amount.txt\"\nOUTPUTFILE = \"change.txt\"\n\n#helper\ndef makeChange(V, a):\n\tprint a\n\tSolutionArray = [0 for i in range(len(V))]\n\tfor i in range(len(V)):\n\t\tif a == V[i]:\n\t\t\tSolutionArray[i] += 1\n\t\t\treturn SolutionArray\n\n\tbestSolution = []\n\tcurMin = sys.maxint\n\tfor i in range(1, a):\n\t\tsubSolution = []\n\t\tsub1 = makeChange(V, i)\n\t\tsub2 = makeChange(V, a - i)\n\t\tfor j in range(len(V)):\n\t\t\tsubSolution.append(sub1[j] + sub2[j])\n\t\tif (curMin > sum(subSolution)):\n\t\t\tcurMin = sum(subSolution)\n\t\t\tbestSolution = subSolution\n\treturn bestSolution\t\t\n\n\n\n\n\n\treturn SolutionArray\n\n#slowchange recursive\ndef a1(arr, value):\n\treturn makeChange(arr, value)\n\n#slowchange iterative version\n# def a1(arr, value):\n# \tSolutionArray = [0 for i in range(len(arr))]\n# \tcount = sys.maxint #track min coins overall\n# \tfor o_idx in range(len(arr) - 1, -1, -1): #count from end of array, backwards to start\n# \t\tTempArray = [0 for i in range(len(arr))]\n# \t\tm_value = value\n# \t\tm_count = 0 #track internal count\n# \t\t#for each coin index, find max # of coins, keep going until m_value <= 0\n# \t\tfor i_idx in range(o_idx, -1, -1):\n# \t\t\twhile(m_value >= arr[i_idx]):\n# \t\t\t\tm_value -= arr[i_idx]\n# \t\t\t\tm_count += 1\n# \t\t\t\tTempArray[i_idx] += 1 #keep track of # of coins used\n# \t\t#only care about exact change\n# \t\tif(m_value == 0):\n# \t\t\t#new count check\n# \t\t\tif(m_count < count):\n# \t\t\t\tcount = m_count\n# \t\t\t\t#assign this solution to our SolutionArray\n# \t\t\t\tSolutionArray = list(TempArray)\n# \treturn SolutionArray\n\n#changegreedy\ndef a2(arr, value):\n\tarrlength = len(arr)\n\tSolutionArray = [0 for i in range(len(arr))]\n\twhile value > 0:\n\t\tfor i in range(arrlength, 0, -1):\n\t\t\tif(arr[i-1] <= value):\n\t\t\t\tSolutionArray[i-1] += 1\n\t\t\t\tvalue -= arr[i-1]\n\t\t\t\tbreak\n\treturn SolutionArray\n\n#changedp\ndef a3(arr, value):\n\tTable = [0 for i in range(value + 1)] #tracks subsolutions\n\tArray = [0 for i in range(value + 1)] #tracks coins used\n\t#if we do an object method, replace SolutionArray and pass in Obj\n\tSolutionArray = [0 for i in range(len(arr))]\n\n\tTable[0] = 0 #amount 0 requires 0 coins\n\t\n\t#In an array of length Amount+1, set each index to a maxint\n\t# value, then when index >= coin value, check if the\n\t# index - coin_value < current value. If so, set current\n\t# value to index-coin_value. Also add the CoinArray index\n\t# to another array to track coins used.\n\tfor i in range(1, value+1):\n\t\tTable[i] = sys.maxint\n\t\tfor j in range(len(arr)):\n\t\t\tif(i >= arr[j]):\n\t\t\t\tif(Table[i - arr[j]] + 1 < Table[i]):\n\t\t\t\t\tTable[i] = Table[i - arr[j]] + 1\n\t\t\t\t\tArray[i] = j\n\t#SolutionArray[len(arr)] = Table[value]\n\tcoins = value\n\twhile(coins):\n\t\tSolutionArray[Array[coins]] += 1\n\t\tcoins = coins - arr[Array[coins]]\n\t\t\n\treturn SolutionArray\n\n#rough rewrite, will probably need update\ndef printResults(arr, minCoins, outputDebug, file):\n\tif(file):\n\t\tfile.write(\"Coins: %s\\n\" % arr)\n\tif(outputDebug):\n\t\tprint(\"Coins: %s\" % arr)\n\tif (minCoins > 0):\n\t\tif(file):\n\t\t\tfile.write(\"Min Coins: %d\\n\" % minCoins)\n\t\tif(outputDebug):\n\t\t\tprint(\"Min Coins: %d\" % minCoins) \n\telse: \n\t\tif(file):\n\t\t\tfile.write(\"Min Coins: 0 **** Value less than min coin\");\n\t\tif(outputDebug):\n\t\t\tprint \"Min Coins: 0 **** Value less than min coin\"\n\t\n#TODO: reuse most of this, rename as necessary\n#cmd line args parser setup\nparser = argparse.ArgumentParser(description=\"Find minimum coins\")\nparser.add_argument(\"-a\", \"--algo\", type=int, help=\"The choice of algorithm(1-3)\")\nparser.add_argument(\"-f\", \"--file\", help=\"Path to input file\")\nparser.add_argument(\"-t\", \"--timing\", help=\"record timings\", action=\"store_true\")\nparser.add_argument(\"-d\", \"--debug\", help=\"turn debug messages on\", action=\"store_true\")\nargs = parser.parse_args()\n\n#cmd line args logic\noutputDebug = True #whether we're printing debug\nout = False #file handle to change.txt\n\n#handle cmd line args\nif not (len(sys.argv) > 2):\n\tparser.error(\"No input file and/or algorithm specified\")\nelif not (args.algo):\n\tparser.error(\"No algorithm specified\")\nelif (args.algo > 3 or args.algo < 1):\n\tparser.error(\"Choose an algorithm 1-3\")\nelif (not args.file):\n\targs.file = INPUTFILE\nif (not args.debug):\n\toutputDebug = False\n\n#setup output file\noutFileName = args.file.replace(\".txt\", \"\") + OUTPUTFILE\nout = open(outFileName, 'w')\n\t\nif(outputDebug):\n\t#debug\n\tprint \"Input file: \" + args.file\n\tprint \"Selected algorithm: \" + str(args.algo)\n\n#open whichever file as input\nf = open(args.file, 'r')\n\n#create the master list to hold each array as another list (2D array)\n#append each array as new list of ints for each line of text read from file\n#append the value we're interested in realizing to another array, the\n#same inde matching the demonination array and value\ntestArr = []\nvalueArr = []\nfor i, line in enumerate(f):\n\tif(i % 2 is 0):\n\t\ttestArr.append([])\n\t\ttestArr[i / 2].append(map(int, line.replace(\"[\", \"\").replace(\"]\", \"\").replace(\"\\n\", \"\").split(',')))\n\telse:\n\t\tvalueArr.append([])\n\t\tvalueArr[i / 2].append(int(line.replace(\"\\n\", \"\")))\nf.close()\n\n#for each algorithm, find the min coin per denomination value, calculate the sum, then print\nif (args.algo == 1):\n\tif not (args.timing or isinstance(out, bool)):\n\t\tout.write(\"******************** changeslow ********************\\n\")\n\tfor k, i in enumerate(testArr):\n\t\tfor j in i:\n\t\t\tif (args.timing):\n\t\t\t\tprint(str(len(j))+\", \"+str(timeit.timeit(lambda:a1(j, valueArr[k][0]),number=1)))\n\t\t\telse:\n\t\t\t\tsubArray = a1(j, valueArr[k][0])\n\t\t\t\tprint subArray\n\t\t\t\tminCoins = sum(subArray)\n\t\t\t\tprintResults(subArray, minCoins, outputDebug, out)\n\t\t\t\tif not (outputDebug):\n\t\t\t\t\tout.write(\"\")\n\nif (args.algo == 2):\n\tif not (args.timing or isinstance(out, bool)):\n\t\tout.write(\"******************** changegreedy ********************\\n\")\n\tfor k, i in enumerate(testArr):\n\t\tfor j in i:\n\t\t\tif (args.timing):\n\t\t\t\tprint(str(len(j))+\", \"+str(timeit.timeit(lambda:a2(j, valueArr[k][0]),number=1)))\n\t\t\telse:\n\t\t\t\tsubArray = a2(j, valueArr[k][0])\n\t\t\t\tminCoins = sum(subArray)\n\t\t\t\tprintResults(subArray, minCoins, outputDebug, out)\n\t\t\t\tif not (outputDebug):\n\t\t\t\t\tout.write(\"\")\n\nif (args.algo == 3):\n\tif not (args.timing or isinstance(out, bool)):\n\t\tout.write(\"******************** changedp ********************\\n\")\n\tfor k, i in enumerate(testArr):\n\t\tfor j in i:\n\t\t\tif (args.timing):\n\t\t\t\tprint(str(len(j))+\", \"+str(timeit.timeit(lambda:a3(j, valueArr[k][0]),number=1)))\n\t\t\telse:\n\t\t\t\tsubArray = a3(j, valueArr[k][0])\n\t\t\t\tminCoins = sum(subArray)\n\t\t\t\tprintResults(subArray, minCoins, outputDebug, out)\n\t\t\t\tif not (outputDebug):\n\t\t\t\t\tout.write(\"\")\n\nif (out):\n\tout.close()\n"
},
{
"alpha_fraction": 0.5721572041511536,
"alphanum_fraction": 0.5883588194847107,
"avg_line_length": 24.895160675048828,
"blob_id": "dca58b2f321bf3db6f37ba110aceafdbefa12401",
"content_id": "6492247fd7bc369008423c846606cd2e8b72d040",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3333,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 124,
"path": "/project1/rand.py",
"repo_name": "parkskevin/cs325_project",
"src_encoding": "UTF-8",
"text": "#Author: Daniel Bonnin, Kevin Parks, Alex Thomas\r\n#email: [email protected], [email protected]\r\n#class: CS325\r\n#Assgn: Project 1\r\n#Descr: This program creates a random output to file for testing purposes. \r\n#\r\n#Input: The program takes an integer as an argument. The program creates\r\n#\t\t this number of arrays in the same format as MSS_Problems.txt\r\n#\r\n#Usage: The argument -n followed by an integer will cause 'n' arrays\r\n# to be generated, each increasing in length from 1 to n-1\r\n\r\nimport random\r\nimport sys\r\n\r\n#********************Daniel modified this for testing. Original is commented out below**********************\r\n\r\ndef make_rand(arrays):\r\n\t#max and min values to generate random values between\r\n\tMAXVAL = 100\r\n\tMINVAL = -100\r\n\r\n\t#value to increment array size by\r\n\tINCREMENT = arrays\r\n\r\n\t#Number of arrays of each size to generate\r\n\tNUM_ARRAYS = 10 \r\n\r\n\t#Number of different n values\r\n\tNUM_NVALS = 10\r\n\r\n\t#name of rand file\r\n\tFILENAME = \"rnums.txt\"\r\n\r\n\t#some sanitizing\r\n\t# arrays = int(arrays)\r\n\t# if(not isinstance(arrays, int)):\r\n\t# \tsys.exit(\"Value not supported\")\r\n\t# if(arrays > sys.maxint or arrays < 0):\r\n\t# \tsys.exit(\"Value not supported.\")\r\n\trandoms = []\r\n\tfor k in range(0, NUM_NVALS):\r\n\t\t#create the random values\r\n\t\tfor i in range(0, NUM_ARRAYS):\r\n\t\t\trandoms.append([])\r\n\t\t\tfor j in range(0, INCREMENT):\t\t\t\t\t\t\t\t\r\n\t\t\t\trandoms[i + (k * NUM_ARRAYS)].append(random.randint(MINVAL, MAXVAL))\r\n\t\tINCREMENT = arrays + INCREMENT\r\n\r\n\t#make sure there's at least 1 positive value\r\n\t# flag = 0\r\n\t# for index, i in enumerate(randoms):\r\n\t# \tfor j in i:\r\n\t# \t\tif(j > 0):\r\n\t# \t\t\tflag = 1\r\n\t# \tif(flag == 0):\r\n\t# \t\trandoms[index][random.randint(0, ARRSIZE - 1)] *= -1\r\n\r\n\t#write to file\r\n\tnum_string = \"\"\r\n\tfor i in randoms:\r\n\t\tfor index, item in enumerate(i):\r\n\t\t\tif(len(i) == 1):\r\n\t\t\t\tnum_string += \"[%d]\\n\" % item\r\n\t\t\t\tbreak\r\n\t\t\tif(index == 0):\r\n\t\t\t\tnum_string += \"[%d, \" % item\r\n\t\t\telif(index < len(i) - 1):\r\n\t\t\t\tnum_string += \"%d, \" % item\r\n\t\t\telse:\r\n\t\t\t\tnum_string += \"%d]\\n\" % item\r\n\tf = open(FILENAME, 'w')\r\n\tf.write(num_string)\r\n\tf.close()\r\n\r\n\t# def make_rand(arrays):\r\n\t# #max and min values to generate random values between\r\n\t# MAXVAL = 100\r\n\t# MINVAL = -100\r\n\t# #size of each array to be generated\r\n\t# ARRSIZE = random.randint(0, 10)\r\n\r\n\t# #name of rand file\r\n\t# FILENAME = \"rnums.txt\"\r\n\r\n\t# #some sanitizing\r\n\t# arrays = int(arrays)\r\n\t# if(not isinstance(arrays, int)):\r\n\t# \tsys.exit(\"Value not supported\")\r\n\t# if(arrays > sys.maxint or arrays < 0):\r\n\t# \tsys.exit(\"Value not supported.\")\r\n\t\r\n\t# #create the random values\r\n\t# randoms = []\r\n\t# for i in range(0, arrays):\r\n\t# \trandoms.append([])\r\n\t# \tfor j in range(0, ARRSIZE):\t\t\t\t\t\t\t\t\r\n\t# \t\trandoms[i].append(random.randint(MINVAL, MAXVAL))\r\n\r\n\t# #make sure there's at least 1 positive value\r\n\t# flag = 0\r\n\t# for index, i in enumerate(randoms):\r\n\t# \tfor j in i:\r\n\t# \t\tif(j > 0):\r\n\t# \t\t\tflag = 1\r\n\t# \tif(flag == 0):\r\n\t# \t\trandoms[index][random.randint(0, ARRSIZE - 1)] *= -1\r\n\r\n\t# #write to file\r\n\t# num_string = \"\"\r\n\t# for i in randoms:\r\n\t# \tfor index, item in enumerate(i):\r\n\t# \t\tif(len(i) == 1):\r\n\t# \t\t\tnum_string += \"[%d]\\n\" % item\r\n\t# \t\t\tbreak\r\n\t# \t\tif(index == 0):\r\n\t# \t\t\tnum_string += \"[%d, \" % item\r\n\t# \t\telif(index < ARRSIZE - 1):\r\n\t# \t\t\tnum_string += \"%d, \" % item\r\n\t# \t\telse:\r\n\t# \t\t\tnum_string += \"%d]\\n\" % item\r\n\t# f = open(FILENAME, 'w')\r\n\t# f.write(num_string)\r\n\t# f.close()"
},
{
"alpha_fraction": 0.6458869576454163,
"alphanum_fraction": 0.6571351289749146,
"avg_line_length": 30.806034088134766,
"blob_id": "78bfb146dd85eed6dbbaee54b6f90a2b315e0e6b",
"content_id": "e89018bafc06ad4d4a1617f982428bfe31b2b2ee",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7379,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 232,
"path": "/project2/coin.py",
"repo_name": "parkskevin/cs325_project",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python\n\n#Author: Daniel Bonnin, Kevin Parks, Alex Thomas\n#email: [email protected]\n#class: CS325\n#Assgn: Project 2\n#Descr: This program calculates the least amount of coins necessary\n#\t to fulfill a given integer value currency. \n#\n#Input: This program takes a text file as input. The program reads\n#\t\t each pair of lines in the file as a separate input. If no\n#\t\t input file is specified, an error will be generated. The\n#\t\t program outputs its results in a file named [inputfile]change.txt.\n#\t\t The [inputfile] prefix is set equal to the input filename provided.\n#\n#Usage: Without arguments, the program returns an error on usage\n#\n# The argument -a followed by a number 1-3 indicates an algorithm\n# to use to calculate the minimum coins. \n#\n# The argument -f followed by a file name indicates the input text\n# file to use. \n#\n#\t\t The argument -t performs timing output to stdout \n#\n#\t\t The argument -d prints output to stdout instead of to a file\n#\n# Usage: python coin.py (-f <filepath>) [-a <1-3>] [-t] [-d]\n\nimport sys #for maxint\nimport timeit #for timings\nimport argparse #cmd line arg parsing\n\n#constants\nINPUTFILE = \"Amount.txt\"\nOUTPUTFILE = \"change.txt\"\nSLOWMAX = 31 #maximum amount we allow for slowchange\n\n#slowchange helper\ndef a1(arr, value):\n\tSolutionArray = [0 for i in range(len(arr))]\n\t#apply the same principle as we use in changedp for TempArray\n\tTempArray = [0 for i in range(value + 1)]\n\tmysum = makeChange(arr, value, TempArray);\n\n\tcoins = value\n\twhile(coins):\n\t\tSolutionArray[TempArray[coins]] += 1\n\t\tcoins = coins - arr[TempArray[coins]]\n\treturn SolutionArray\n\t\n#slowchange recursive\ndef makeChange(V, a, TempArray):\n\t#amount is 0, base case\n\tif(a <= 0):\n\t\treturn 0\n\t\t\n\t#set count to max, helps checks for min\n\tcount = sys.maxint\n\t\n\t#check every coin value\n\tfor i in range(len(V)):\n\t\tif(V[i] <= a):\n\t\t\ttmpCount = makeChange(V, a-V[i], TempArray) + 1\n\t\t\tif (tmpCount < count):\n\t\t\t\tcount = tmpCount\n\t\t\t\t#add the coin index to TempArray when this occurs\n\t\t\t\tTempArray[a] = i\n\t\n\treturn count\n\n#changegreedy\ndef a2(arr, value):\n\tarrlength = len(arr)\n\tSolutionArray = [0 for i in range(len(arr))]\n\twhile value > 0:\n\t\tfor i in range(arrlength, 0, -1):\n\t\t\tif(arr[i-1] <= value):\n\t\t\t\tSolutionArray[i-1] += 1\n\t\t\t\tvalue -= arr[i-1]\n\t\t\t\tbreak\n\treturn SolutionArray\n\n#changedp\ndef a3(arr, value):\n\tTable = [0 for i in range(value + 1)] #tracks subsolutions\n\tArray = [0 for i in range(value + 1)] #tracks coins used\n\t#if we do an object method, replace SolutionArray and pass in Obj\n\tSolutionArray = [0 for i in range(len(arr))]\n\n\tTable[0] = 0 #amount 0 requires 0 coins\n\t\n\t#In an array of length Amount+1, set each index to a maxint\n\t# value, then when index >= coin value, check if the\n\t# index - coin_value < current value. If so, set current\n\t# value to index-coin_value. Also add the CoinArray index\n\t# to another array to track coins used.\n\tfor i in range(1, value+1):\n\t\tTable[i] = sys.maxint\n\t\tfor j in range(len(arr)):\n\t\t\tif(i >= arr[j]):\n\t\t\t\tif(Table[i - arr[j]] + 1 < Table[i]):\n\t\t\t\t\tTable[i] = Table[i - arr[j]] + 1\n\t\t\t\t\tArray[i] = j\n\tcoins = value\n\twhile(coins):\n\t\tSolutionArray[Array[coins]] += 1\n\t\tcoins = coins - arr[Array[coins]]\n\t\t\n\treturn SolutionArray\n\n#rough rewrite, will probably need update\ndef printResults(arr, minCoins, outputDebug, file):\n\tif(file):\n\t\tfile.write(\"Coins: %s\\n\" % arr)\n\tif(outputDebug):\n\t\tprint(\"Coins: %s\" % arr)\n\tif (minCoins > 0):\n\t\tif(file):\n\t\t\tfile.write(\"Min Coins: %d\\n\" % minCoins)\n\t\tif(outputDebug):\n\t\t\tprint(\"Min Coins: %d\" % minCoins) \n\telse: \n\t\tif(file):\n\t\t\tfile.write(\"Min Coins: 0 **** Value less than min coin\");\n\t\tif(outputDebug):\n\t\t\tprint \"Min Coins: 0 **** Value less than min coin\"\n\t\n#cmd line args parser setup\nparser = argparse.ArgumentParser(description=\"Find minimum coins\")\nparser.add_argument(\"-a\", \"--algo\", type=int, help=\"The choice of algorithm(1-3)\")\nparser.add_argument(\"-f\", \"--file\", help=\"Path to input file\")\nparser.add_argument(\"-t\", \"--timing\", help=\"record timings\", action=\"store_true\")\nparser.add_argument(\"-d\", \"--debug\", help=\"turn debug messages on\", action=\"store_true\")\nargs = parser.parse_args()\n\n#cmd line args logic\noutputDebug = True #whether we're printing debug\nout = False #file handle to change.txt\ncoinTest = False #whether this is a test of all algos\ncanDoSlow = True #whether we can perform slowchange algo\n\n#handle cmd line args\nif not (len(sys.argv) > 2):\n\tparser.error(\"Too few arguments\")\nelif not (args.algo):\n\tcoinTest = True #do all the algorithms then\nelif (args.algo and args.algo > 3 or args.algo < 1):\n\tparser.error(\"Choose an algorithm 1-3\")\nelif (not args.file):\n\tparser.error(\"Missing file argument\")\nif (not args.debug):\n\toutputDebug = False\n\n#setup output file\noutFileName = args.file.replace(\".txt\", \"\") + OUTPUTFILE\nout = open(outFileName, 'w')\n\t\nif(outputDebug):\n\t#debug\n\tprint \"Input file: \" + args.file\n\tprint \"Selected algorithm: \" + str(args.algo)\n\n#open whichever file as input\nf = open(args.file, 'r')\n\n#create the master list to hold each array as another list (2D array)\n#append each array as new list of ints for each line of text read from file\n#append the value we're interested in realizing to another array, the\n#same index matching the demonination array and value\ntestArr = []\nvalueArr = []\nfor i, line in enumerate(f):\n\tif(i % 2 is 0):\n\t\ttestArr.append([])\n\t\ttestArr[i / 2].append(map(int, line.replace(\"[\", \"\").replace(\"]\", \"\").replace(\"\\n\", \"\").split(',')))\n\telse:\n\t\tvalueArr.append([])\n\t\tvalueArr[i / 2].append(int(line.replace(\"\\n\", \"\")))\nf.close()\n\n#for each algorithm, find the min coin per denomination value, calculate the sum, then print\nif (args.algo == 1 or coinTest == True):\n\tif not (args.timing or isinstance(out, bool)):\n\t\tout.write(\"******************** changeslow ********************\\n\")\n\tfor k, i in enumerate(testArr):\n\t\tfor j in i:\n\t\t\tif (valueArr[k][0] > SLOWMAX):\n\t\t\t\tif(outputDebug):\n\t\t\t\t\tprint \"Output %d too large\" % valueArr[k][0]\n\t\t\t\tif(file):\n\t\t\t\t\tout.write(\"Output %d too large\\n\" % valueArr[k][0])\n\t\t\t\tcontinue\n\t\t\tif (args.timing):\n\t\t\t\tprint(str(valueArr[k][0])+\", \"+str(len(j))+\", \"+str(timeit.timeit(lambda:a1(j, valueArr[k][0]),number=1)))\n\t\t\telse:\n\t\t\t\tsubArray = a1(j, valueArr[k][0])\n\t\t\t\tminCoins = sum(subArray)\n\t\t\t\tprintResults(subArray, minCoins, outputDebug, out)\n\t\t\t\tif not (outputDebug):\n\t\t\t\t\tout.write(\"\")\n\nif (args.algo == 2 or coinTest == True):\n\tif not (args.timing or isinstance(out, bool)):\n\t\tout.write(\"******************** changegreedy ********************\\n\")\n\tfor k, i in enumerate(testArr):\n\t\tfor j in i:\n\t\t\tif (args.timing):\n\t\t\t\tprint(str(valueArr[k][0])+\", \"+str(len(j))+\", \"+str(timeit.timeit(lambda:a2(j, valueArr[k][0]),number=1)))\n\t\t\telse:\n\t\t\t\tsubArray = a2(j, valueArr[k][0])\n\t\t\t\tminCoins = sum(subArray)\n\t\t\t\tprintResults(subArray, minCoins, outputDebug, out)\n\t\t\t\tif not (outputDebug):\n\t\t\t\t\tout.write(\"\")\n\nif (args.algo == 3 or coinTest == True):\n\tif not (args.timing or isinstance(out, bool)):\n\t\tout.write(\"******************** changedp ********************\\n\")\n\tfor k, i in enumerate(testArr):\n\t\tfor j in i:\n\t\t\tif (args.timing):\n\t\t\t\tprint(str(valueArr[k][0])+\", \"+str(len(j))+\", \"+str(timeit.timeit(lambda:a3(j, valueArr[k][0]),number=1)))\n\t\t\telse:\n\t\t\t\tsubArray = a3(j, valueArr[k][0])\n\t\t\t\tminCoins = sum(subArray)\n\t\t\t\tprintResults(subArray, minCoins, outputDebug, out)\n\t\t\t\tif not (outputDebug):\n\t\t\t\t\tout.write(\"\")\n\nif (out):\n\tout.close()\n"
}
] | 12 |
cash2one/data_eye | https://github.com/cash2one/data_eye | 454c30180d12e6c6aa034140b4699ccc1546ca3d | 0ffdb53961a094550acec2732da80a9862b61662 | b83e068c5687a1bf659d11ca083e3f52be584402 | refs/heads/master | 2020-05-21T15:59:50.617125 | 2016-10-14T12:07:29 | 2016-10-14T12:07:29 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5949088335037231,
"alphanum_fraction": 0.6140791773796082,
"avg_line_length": 28.462963104248047,
"blob_id": "f0ac41ea430b13b0d68ca202555d008e1a41955f",
"content_id": "95c4e3f71eddd15cdaa41c9d5381b9f30d5eaac3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3182,
"license_type": "no_license",
"max_line_length": 137,
"num_lines": 108,
"path": "/spider/get_proxy_list.py",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#encoding=utf-8\n\nimport sys\nimport requests\nimport json\nimport urllib\nimport traceback\nimport re\nimport sys\nfrom bs4 import BeautifulSoup\nimport time\n\nfrom config import *\nmylogger = get_logger('proxy_list')\n\ns = requests.session()\ndb_conn = new_session()\n\nheaders = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36'}\n\n\ndef get_xici_nn_proxy_list(page):\n\tURL = \"http://www.xicidaili.com/nn/%s\" % page\n\ttry:\n\t\tresponse = s.get(URL, timeout=10, headers=headers)\n\t\tif response.status_code == 200:\n\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\ttb = soup.find('table', id='ip_list')\n\t\t\tif tb is not None:\n\t\t\t\tfor tr in tb.find_all('tr')[1:]:\n\t\t\t\t\ttds = [i.text.strip() for i in tr.find_all('td')]\n\t\t\t\t\tif len(tds) == 10:\n\t\t\t\t\t\ta, b, ip, port, location, is_anonymity, type, c, d, check_time = tds\n\t\t\t\t\t\t#print ip, port\n\t\t\t\t\t\tins = db_conn.query(ProxyList).filter(ProxyList.ip==ip).filter(ProxyList.port==port).first()\n\t\t\t\t\t\tif not ins:\n\t\t\t\t\t\t\titem = ProxyList(**{\n\t\t\t\t\t\t\t\t\t\t\t\"ip\": ip,\n\t\t\t\t\t\t\t\t\t\t\t\"port\": port,\n\t\t\t\t\t\t\t\t\t\t\t\"location\": location,\n\t\t\t\t\t\t\t\t\t\t\t\"is_anonymity\": is_anonymity,\n\t\t\t\t\t\t\t\t\t\t\t\"type\": type,\n\t\t\t\t\t\t\t\t\t\t\t\"check_time\": u\"20\" + check_time,\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tdb_conn.merge(item)\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\tdb_conn.commit()\n\ndef get_kd_proxy_list(page):\n\tURL = \"http://www.kuaidaili.com/free/intr/%s/\" % page\n\ttry:\n\t\tresponse = s.get(URL, timeout=10, headers=headers)\n\t\tif response.status_code == 200:\n\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\ttb = soup.find('table', class_='table table-bordered table-striped')\n\t\t\tif tb is not None:\n\t\t\t\tfor tr in tb.find_all('tr')[1:]:\n\t\t\t\t\ttds = [i.text.strip() for i in tr.find_all('td')]\n\t\t\t\t\tif len(tds) == 7:\n\t\t\t\t\t\tip, port, is_anonymity, type, location, _, check_time = tds\n\t\t\t\t\t\tins = db_conn.query(ProxyList).filter(ProxyList.ip==ip).filter(ProxyList.port==port).first()\n\t\t\t\t\t\tif not ins:\n\t\t\t\t\t\t\titem = ProxyList(**{\n\t\t\t\t\t\t\t\t\t\t\t\"ip\": ip,\n\t\t\t\t\t\t\t\t\t\t\t\"port\": port,\n\t\t\t\t\t\t\t\t\t\t\t\"location\": location,\n\t\t\t\t\t\t\t\t\t\t\t\"is_anonymity\": is_anonymity,\n\t\t\t\t\t\t\t\t\t\t\t\"type\": type,\n\t\t\t\t\t\t\t\t\t\t\t\"check_time\": check_time,\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tdb_conn.merge(item)\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\tdb_conn.commit()\n\ndef get_proxies():\n\treturn [{rc.type: u\"%s:%s\" % (rc.ip, rc.port)} for rc in db_conn.query(ProxyList)]\n\t\t\n\ndef check_proxy(proxy):\n\tstart = time.time()\n\ttry:\n\t\tr = requests.get(\"http://www.sogou.com/\", headers=headers)\n\t\t#r = requests.get(\"http://www.douban.com/\", headers=headers, proxies = proxy)\n\t\tif r.status_code == 200:\n\t\t\tend = time.time()\n\t\t\tprint proxy, end - start\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\" % (traceback.format_exc()))\n\t\t\n\ndef test():\n\tcount = 0\n\tURL = \"http://zhushou.360.cn/list/index/cid/2/order/newest/?page=1\"\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\t\tresponse = T(404)\n\nif __name__ == '__main__':\n\tmylogger.info('get proxy start ...')\n\tget_xici_nn_proxy_list(1)\n\tget_kd_proxy_list(1)\n\t#for p in get_proxies():\n\t#\tcheck_proxy(p)\n"
},
{
"alpha_fraction": 0.7067564725875854,
"alphanum_fraction": 0.7291618585586548,
"avg_line_length": 43.859375,
"blob_id": "5bee08ab27f2cf49d12c2b542bdd2449a68ee920",
"content_id": "88284d425e7ccb546718e9f3deaffd79c6e17c6c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8772,
"license_type": "no_license",
"max_line_length": 96,
"num_lines": 192,
"path": "/common/model.py",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#! /usr/bin/env python\n#coding=utf-8\nfrom sqlalchemy import MetaData, Column, Integer, String, Float, CHAR\nfrom sqlalchemy import DateTime, func, Unicode, UnicodeText, Boolean, Date, Text\nimport sqlalchemy\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import UniqueConstraint\n#from sqlalchemy import create_engine\nfrom sqlalchemy.ext.declarative import declared_attr\nfrom datetime import *\n\nBase = declarative_base()\n\n\nclass KC_LIST(Base):\n\n\t__tablename__ = 'kc_list'\n\n\tid = Column(Integer, primary_key=True, autoincrement=True)\n\ttime = Column(Unicode(50), nullable=False, default=u'')\n\ttitle = Column(Unicode(50), nullable=False, default=u'')\n\ttitle2 = Column(Unicode(50), nullable=False, default=u'')\n\timg = Column(Unicode(100), nullable=False, default=u'')\n\turl = Column(Unicode(100), nullable=False, default=u'')\n\tdevice = Column(Unicode(50), nullable=False, default=u'')\n\tpublish_status = Column(Unicode(50), nullable=False, default=u'')\n\tgame_type = Column(Unicode(50), nullable=False, default=u'')\n\tgame_id = Column(Unicode(50), nullable=False, default=u'')\n\tpkg_name = Column(Unicode(100), nullable=False, default=u'')\n\tpopular = Column(Unicode(50), nullable=False, default=u'')\n\tpublish_date = Column(Unicode(50), nullable=False, default=u'')\n\tsource = Column(Integer, nullable=False, default=0)\n\tstatus = Column(Integer, nullable=False, default=0)\n\tcreate_date = Column(DateTime,nullable=False,default=datetime.now())#创建时间\n\tlast_update = Column(DateTime,nullable=False,default=datetime.now())#最后更新时间\n\nclass HotGames(Base):\n\t\n\t__tablename__ = 'hot_games'\n\t\n\tid = Column(Integer, primary_key=True, autoincrement=True)\n\tname = Column(Unicode(100), nullable=False, default=u'', index=True)\n\tsrc = Column(Unicode(200), nullable=False, default=u'')\n\tdownload_count = Column(Unicode(50), nullable=False, default=u'')\n\tsize = Column(Unicode(100), nullable=False, default=u'')\n\trank = Column(Integer, nullable=False, default=0)\n\turl = Column(Unicode(100), nullable=False, default=u'')\n\tstatus = Column(Unicode(50), nullable=False, default=u'')\n\tgame_type = Column(Unicode(50), nullable=False, default=u'')\n\tpopular = Column(Unicode(50), nullable=False, default=u'')\n\tsource = Column(Integer, nullable=False, default=-1, index=True)\n\tdt = Column(Unicode(100), nullable=False, default=u'')\n\tcreate_date = Column(DateTime,nullable=False,default=datetime.now())#创建时间\n\tlast_update = Column(DateTime,nullable=False,default=datetime.now())#最后更新时间\n\n\nclass PageSource(Base):\n\t\n\t__tablename__ = 'page_source'\n\t\n\tid = Column(Integer, primary_key=True, autoincrement=True)\n\turl = Column(Unicode(200), nullable=False, default=u'', index=True)\n\tcode = Column(UnicodeText, nullable=False, default=u'')\n\tsource = Column(Integer, nullable=False, default=-1, index=True)\n\tcreate_date = Column(DateTime,nullable=False,default=date.today())#创建时间\n\tlast_update = Column(DateTime,nullable=False,default=date.today())#最后更新时间\n\nclass GameDetailByDay(Base):\n\t\n\t__tablename__ = 'game_detail_by_day'\n\t\n\tid = Column(Integer, primary_key=True, autoincrement=True)\n\tkc_id = Column(Integer, nullable=False, default=0, index=True)\n\tname = Column(Unicode(100), nullable=False, default=u'', index=True)\n\timgs = Column(UnicodeText, nullable=False, default=u'')\n\tgame_type = Column(Unicode(100), nullable=False, default=u'')\n\tsummary = Column(UnicodeText, nullable=False, default=u'')\n\tdownload_num = Column(Unicode(50), nullable=False, default=u'')\n\tcomment_num = Column(Unicode(50), nullable=False, default=u'')\n\trating = Column(Unicode(50), nullable=False, default=u'')\n\trank = Column(Unicode(50), nullable=False, default=u'')\n\ttopic_num_day = Column(Unicode(50), nullable=False, default=u'')\n\ttopic_num_total = Column(Unicode(50), nullable=False, default=u'')\n\tpkg_size = Column(Unicode(50), nullable=False, default=u'')\n\tcompany = Column(Unicode(100), nullable=False, default=u'')\n\tversion = Column(Unicode(100), nullable=False, default=u'')\n\tauthor = Column(Unicode(100), nullable=False, default=u'')\n\tdt = Column(Unicode(100), nullable=False, default=u'')\n\tupdate_time = Column(Unicode(100), nullable=False, default=u'')\n\tcreate_date = Column(DateTime, nullable=False, default=datetime.now())#创建时间\n\tlast_update = Column(DateTime, nullable=False, default=datetime.now())#最后更新时间\n\nclass Course(Base):\n\n __tablename__ = 'course'\n\n cid = Column(Integer, primary_key=True, autoincrement=True)\n name = Column(Unicode(50), nullable=False, default=u'', info={'comment':'Segregation Code'})\n t = Column(Integer, nullable=False, default=0)\n\n\n\nclass ProxyList(Base):\n\n\t__tablename__ = 'proxy_list'\n\n\tid = Column(Integer, primary_key=True, autoincrement=True)\n\tip = Column(Unicode(100), nullable=False, default=u'', index=True)\n\tport = Column(Unicode(20), nullable=False, default=u'', index=True)\n\tlocation = Column(Unicode(100), nullable=False, default=u'')\n\tis_anonymity = Column(Unicode(20), nullable=False, default=u'')\n\ttype = Column(Unicode(20), nullable=False, default=u'')\n\tstatus = Column(Integer, nullable=False, default=0)\n\tcheck_time = Column(Unicode(100), nullable=False, default=u'')\n\tcreate_time = Column(DateTime, nullable=False, default=datetime.now())#创建时间\n\tlast_update = Column(DateTime, nullable=False, default=datetime.now())#最后更新时间\n\n\nclass PublishGame(Base):\n\n\t__tablename__ = 'publish_game'\n\n\tid = Column(Integer, primary_key=True, autoincrement=True)\n\tname = Column(Unicode(100), nullable=False, default=u'', index=True)\n\timgs = Column(UnicodeText, nullable=False, default=u'')\n\tgame_type = Column(Unicode(100), nullable=False, default=u'')\n\tsummary = Column(UnicodeText, nullable=False, default=u'')\n\tdownload_num = Column(Unicode(50), nullable=False, default=u'')\n\tcomment_num = Column(Unicode(50), nullable=False, default=u'')\n\trating = Column(Unicode(50), nullable=False, default=u'')\n\trank = Column(Unicode(50), nullable=False, default=u'')\n\ttopic_num = Column(Unicode(50), nullable=False, default=u'')\n\tpkg_size = Column(Unicode(50), nullable=False, default=u'')\n\tversion = Column(Unicode(100), nullable=False, default=u'')\n\tauthor = Column(Unicode(100), nullable=False, default=u'')\n\tdevice = Column(Unicode(100), nullable=False, default=u'')\n\tpublish_status = Column(Unicode(100), nullable=False, default=u'')\n\tkc_list_ids = Column(Unicode(200), nullable=False, default=u'')\n\tchannels = Column(UnicodeText, nullable=False, default=u'')\n\tpublish_dates = Column(UnicodeText, nullable=False, default=u'')\n\tdt = Column(Unicode(100), nullable=False, default=u'')\n\tcreate_date = Column(DateTime, nullable=False, default=datetime.now())#创建时间\n\tlast_update = Column(DateTime, nullable=False, default=datetime.now())#最后更新时间\n\n\nclass HotGameDetailByDay(Base):\n\t\n\t__tablename__ = 'hot_game_detail_by_day'\n\t\n\tid = Column(Integer, primary_key=True, autoincrement=True)\n\tname = Column(Unicode(100), nullable=False, default=u'', index=True)\n\timgs = Column(UnicodeText, nullable=False, default=u'')\n\tgame_type = Column(Unicode(100), nullable=False, default=u'')\n\tsummary = Column(UnicodeText, nullable=False, default=u'')\n\tdownload_num = Column(Unicode(50), nullable=False, default=u'')\n\tcomment_num = Column(Unicode(50), nullable=False, default=u'')\n\trating = Column(Unicode(50), nullable=False, default=u'')\n\trank = Column(Unicode(50), nullable=False, default=u'')\n\tdownload_num_day = Column(Unicode(50), nullable=False, default=u'')\n\ttopic_num_total = Column(Unicode(50), nullable=False, default=u'')\n\tpkg_size = Column(Unicode(50), nullable=False, default=u'')\n\tcompany = Column(Unicode(100), nullable=False, default=u'')\n\tversion = Column(Unicode(100), nullable=False, default=u'')\n\tauthor = Column(Unicode(100), nullable=False, default=u'')\n\tdt = Column(Unicode(100), nullable=False, default=u'', index=True)\n\tchannel = Column(Integer, nullable=False, default=0, index=True)\n\tupdate_time = Column(Unicode(100), nullable=False, default=u'')\n\tcreate_date = Column(DateTime, nullable=False, default=datetime.now())#创建时间\n\tlast_update = Column(DateTime, nullable=False, default=datetime.now())#最后更新时间\n\nclass ChannelToRanking(Base):\n\t\n\t__tablename__ = 'channel_to_ranking'#渠道与榜单映射关系\n\t\n\tchannel_id = Column(Integer, primary_key=True, autoincrement=False)\n\tranking_id = Column(Integer, primary_key=True, autoincrement=False)\n\n\nclass Channel(Base):\n\n\t__tablename__ = 'channel'\n\n\tid = Column(Integer, primary_key=True, autoincrement=False)\n\tname = Column(Unicode(100), nullable=False, default=u'', index=True)\n\n\nclass RankingChannel(Base):\n\n\t__tablename__ = 'ranking_channel'\n\n\tid = Column(Integer, primary_key=True, autoincrement=False)\n\tname = Column(Unicode(100), nullable=False, default=u'', index=True)\n\n"
},
{
"alpha_fraction": 0.6963249444961548,
"alphanum_fraction": 0.719535768032074,
"avg_line_length": 24.850000381469727,
"blob_id": "b6233c157798a829a5e497e31abb44baa346714c",
"content_id": "1596f2bc1b0f88dd67f1cf8c66347d8551673350",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 529,
"license_type": "no_license",
"max_line_length": 141,
"num_lines": 20,
"path": "/spider/config.py",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#encoding=utf-8\n\nimport sys\nimport socket\n\nlocalIP = socket.gethostbyname(socket.gethostname())#这个得到本地ip\n\nif localIP == u'192.168.1.215':\n\tsys.path.append('/root/yanpengchen/data_eye/common')\nelse:\n\tsys.path.append('/home/cyp/data_eye/common')\n\nfrom get_logger import *\nfrom define import *\nfrom model import *\n\ncheck_date = date.today()+timedelta(-3)\n\nproxies = [{rc.type: u\"%s:%s\" % (rc.ip, rc.port)} for rc in new_session().query(ProxyList).filter(ProxyList.check_time>=unicode(check_date))]\n"
},
{
"alpha_fraction": 0.5856972336769104,
"alphanum_fraction": 0.6400476694107056,
"avg_line_length": 40.68473434448242,
"blob_id": "18e14e68162955b31108b6d2672effbd26f0b33e",
"content_id": "dd3f928424b8138a453b30bc64825f9269ac5598",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 46294,
"license_type": "no_license",
"max_line_length": 788,
"num_lines": 1107,
"path": "/spider/get_hot_game.py",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#encoding=utf-8\n\nimport requests\nimport json\nimport urllib\nimport traceback\nimport re\nfrom bs4 import BeautifulSoup\nimport time\nimport xmltodict\nfrom config import *\nimport datetime\n\nmylogger = get_logger('hot_game')\n\ns = requests.session()\ndb_conn = new_session()\n\nimport random\nproxies = [{rc.type: u\"%s:%s\" % (rc.ip, rc.port)} for rc in db_conn.query(ProxyList)]\n\nsource_map = {\n\t\t\t\"baidu\"\t: 0,\n\t\t\t\"xiaomi_active\": 1,\n\t\t\t\"360_webgame\"\t: 2,\n\t\t\t\"9game\"\t: 3,\n\t\t\t\"9game_hot_wanted\"\t: 4,\n\t\t\t\"360_app_single\"\t: 5,\n\t\t\t\"360_app_webgame\"\t: 6,\n\t\t\t\"360_app_new_game\"\t: 7,\n\t\t\t\"m5_qq_single\"\t: 8,#应用宝PC\n\t\t\t\"m5_qq_webgame\"\t: 9,#应用宝PC\n\t\t\t\"m5_qq_new_game\"\t: 10,#应用宝PC\n\t\t\t\"m_baidu_single\"\t: 11,\n\t\t\t\"m_baidu_webgame\"\t: 12,\n\t\t\t\"m_baidu_new_game\"\t: 13,\n\t\t\t\"dangle_new_game\"\t: 14,\n\t\t\t\"xiaomi_new_game\"\t: 15,\n\t\t\t\"vivo_single\"\t: 16,\n\t\t\t\"vivo_webgame\"\t: 17,\n\t\t\t\"vivo_new_game\"\t: 18,\n\t\t\t\"gionee_active\"\t: 19,\n\t\t\t\"gionee_hot\"\t: 20,\n\t\t\t\"coolpad_hot\"\t: 21,\n\t\t\t\"coolpad_webgame\"\t: 22,\n\t\t\t\"coolpad_new_game\"\t: 23,\n\t\t\t\"open_play_download\"\t: 24,#爱游戏榜单\n\t\t\t\"open_play_free\"\t: 25,#爱游戏榜单\n\t\t\t\"open_play_webgame\"\t: 26,#爱游戏榜单\n\t\t\t\"wandoujia_single\"\t: 27,\n\t\t\t\"wandoujia_webgame\"\t: 28,\n\t\t\t\"iqiyi_download\"\t: 29,\n\t\t\t\"iqiyi_hot\"\t: 30,\n\t\t\t\"youku_single\"\t: 31,\n\t\t\t\"youku_webgame\"\t: 32,\n\t\t\t\"sogou_single\"\t: 33,\n\t\t\t\"sogou_webgame\"\t: 34,\n\t\t\t\"i4_hot\"\t: 35,\n\t\t\t\"pp_hot\"\t: 36,\n\t\t\t\"kuaiyong_hot\"\t: 37,\n\t\t\t\"itools_hot\"\t: 38,\n\t\t\t\"xyzs_hot\"\t: 39,\n\t\t\t\"91play_hot\"\t: 40,\n\t\t\t\"360_gamebox_single\"\t: 41,\n\t\t\t\"360_gamebox_webgame\"\t: 42,\n\t\t\t\"m5_qq_download\"\t: 43,\n\t\t\t\"m_baidu_top\"\t: 44,\n\t\t\t\"open_play_rise\"\t: 45,\n\t\t\t\"18183_top\"\t: 46,\n\t\t\t\"18183_hot\"\t: 47,\n\t\t\t\"360_app_expect\"\t: 48,\n\t\t\t\"xiaomi_downloads\": 49,\n\t\t\t\"xiaomi_new_webganme\": 50,\n\t\t\t\"sogou_download\"\t: 51,\n\t\t\t\"360_child\"\t\t: \"52\", \n\t\t\t\"360_rpg\"\t\t: \"53\", \n\t\t\t\"360_act\"\t\t: \"54\", \n\t\t\t\"360_puz\"\t\t: \"55\", #休闲益智\n\t\t\t\"360_sport\"\t\t: \"56\", \n\t\t\t\"360_stg\"\t\t: \"57\", #飞行射击\n\t\t\t\"360_strategy\"\t: \"58\", \n\t\t\t\"360_chess\"\t\t: \"59\", \n\t\t\t\"xiaomi_app_download\"\t\t: \"60\", \n\t\t\t\"xiaomi_app_hot\"\t\t: \"61\", #畅销榜 \n\t\t\t\t}\n\ndef get_baidu_hot_games():\n\turl = \"http://shouji.baidu.com/game\"\n\tr = s.get(url)\n\tif r.status_code == 200:\n\t\tsoup = BeautifulSoup(r.text)\n\t\thot = soup.find(\"div\", class_=\"sec-hot tophot\")\n\t\tif hot is not None:\n\t\t\tfor k in hot.find_all(\"li\")[:]:\n\t\t\t\tpopular \t= u\"\"\n\t\t\t\tgame_type \t= u\"\"\n\t\t\t\tstatus \t\t= u\"\"\n\t\t\t\turl \t\t= u\"\"\n\t\t\t\tsource \t\t= source_map.get('baidu')\n\t\t\t\turl_a = k.find(\"a\",class_=\"app-box\")\n\t\t\t\tif url_a is not None:\n\t\t\t\t\turl = \"http://shouji.baidu.com%s\" % url_a.get('href')\n\t\t\t\tdetail = k.find(\"div\",class_=\"app-detail\")\n\t\t\t\tif detail is not None:\n\t\t\t\t\tgame_name = detail.find(\"p\").text\n\t\t\t\t\timg = detail.find(\"div\", class_=\"icon\").find(\"img\").get(\"src\")\n\t\t\t\t\tdown_size = detail.find(\"p\", class_=\"down-size\")\t\n\t\t\t\t\tdownloads = down_size.find(\"span\", class_=\"down\").text\n\t\t\t\t\tsize = down_size.find(\"span\", class_=\"size\").text\n\t\t\t\t\tyield game_name, img, downloads, size, source, popular, game_type, status, url\n\ndef download_pic(url, name):\n\ttry:\n\t\tif not os.path.isfile(\"/home/cyp/data_eye/spider/ttt/%s\" % (name)):\n\t\t\tprint '**'\n\t\t\turllib.urlretrieve(url, \"/home/cyp/data_eye/spider/ttt/%s\" % name)\n\texcept Exception,e:\n\t\tprint traceback.format_exc()\n\ndef download_pic2(args):\n\ttry:\n\t\turl, name = args\n\t\tif not os.path.isfile(\"/home/cyp/data_eye/spider/pics/%s\" % (name)):\n\t\t\tmylogger.info(\"downloading pic ... %s\" % name)\n\t\t\turllib.urlretrieve(url, \"/home/cyp/data_eye/spider/pics/%s\" % name)\n\texcept Exception,e:\n\t\tmylogger.error(traceback.format_exc())\n\ndef get_appannie_icons():\n\timport multiprocessing\n\tfrom multiprocessing.dummy import Pool as ThreadPool\n\ttry:\n\t\tpool = multiprocessing.Pool(processes=multiprocessing.cpu_count())\n\t\turls = [(ret.src, ret.name+\"_\"+str(ret.source)) for ret in db_conn.query(HotGames).filter(HotGames.create_date==\"2015-09-02\").filter(HotGames.source!=4)]\t\n\t\tpool.map_async(download_pic2, urls)\n\t\tpool.close()\n\t\tpool.join()\n\texcept Exception,e:\n\t\tprint traceback.format_exc()\n\t\n\ndef get_icons(f):\n\timport multiprocessing\n\tfrom multiprocessing.dummy import Pool as ThreadPool\n\ttry:\n\t\tpool = multiprocessing.Pool(processes=multiprocessing.cpu_count())\n\t\turls = []\n\t\tfor ret in f():\n\t\t\tapp_name, src, download_count, size, source = ret\n\t\t\turl = src \n\t\t\tname = app_name.encode(\"utf-8\")+\"_\"+str(source)\n\t\t\turls.append((url, name))\n\t\t\t#pool.apply_async(download_pic, (url, name))\n\t\tpool.map_async(download_pic2, urls)\n\t\tpool.close()\n\t\tpool.join()\n\texcept Exception,e:\n\t\tmylogger.error(traceback.format_exc())\n\ndef get_xiaomi_game_rank(page, rank_id):\n\turl = \"http://game.xiaomi.com/index.php?c=app&a=ajaxPage&type=rank\"\n\tpayload = {\n\t\t\t\t\"page\"\t\t\t:page,\n\t\t\t\t\"category_id\"\t:\"\",\n\t\t\t\t\"total_page\"\t:60,\n\t\t\t\t\"rank_id\"\t\t:rank_id,\n\t\t\t\t\"type\"\t\t\t:\"rank\"\n\t\t\t\t}\n\tr = s.post(url, data=payload)\n\tif r.status_code == 200:\n\t\treturn r.json()\n\treturn None\n\n\ndef get_xiaomi_web_rank(gtype, rank_id):\n\trank = 0\n\tfor page in xrange(1):\n\t\tdetail = get_xiaomi_game_rank(page, rank_id)\n\t\tif detail is not None:\n\t\t\tfor d in detail:\n\t\t\t\trank += 1\n\t\t\t\tpopular \t= u\"\"\n\t\t\t\tgame_type \t= u\"\"\n\t\t\t\tstatus \t\t= u\"\"\n\t\t\t\turl \t\t= u\"http://game.xiaomi.com/app-appdetail--app_id__%s.html\" % d.get(\"ext_id\")\n\t\t\t\tgame_name = d.get(\"game_name\")\n\t\t\t\timg = d.get(\"icon\")\n\t\t\t\tdownloads = d.get(\"download_count\")\n\t\t\t\tsize = d.get(\"apk_size\")\n\t\t\t\tsource = source_map.get(gtype)\n\t\t\t\tyield rank, game_name, img, downloads, size, source, popular, game_type, status, url\n\ndef store_xiaomi_web_rank():\n\ttype_2_source = {\n\t\t\t\t\t\t\"xiaomi_active\": 12,\n\t\t\t\t\t\t\"xiaomi_new_webganme\": 13,\n\t\t\t\t\t\t\"xiaomi_downloads\": 2,\n\t\t\t\t\t\t\"xiaomi_new_game\": 3,\n\t\t\t\t\t}\n\tfor gtype, rank_id in type_2_source.iteritems():\n\t\tfor data in get_xiaomi_web_rank(gtype, rank_id):\n\t\t\tstore_data(data)\n\n\ndef get_360zhushou_web_rank():\n\t_dict = {\n\t\t\t\t\"360_webgame\"\t: \"100451\", \n\t\t\t\t\"360_child\"\t\t: \"102238\", \n\t\t\t\t\"360_rpg\"\t\t: \"101587\", \n\t\t\t\t\"360_act\"\t\t: \"20\", \n\t\t\t\t\"360_puz\"\t\t: \"19\", #休闲益智\n\t\t\t\t\"360_sport\"\t\t: \"51\", \n\t\t\t\t\"360_stg\"\t\t: \"52\", #飞行射击\n\t\t\t\t\"360_strategy\"\t: \"53\", \n\t\t\t\t\"360_chess\"\t\t: \"54\", \n\t\t\t}\n\tfor gtype, id in _dict.iteritems():\n\t\ttry:\n\t\t\tr = s.get('http://zhushou.360.cn/list/index/cid/%s/order/download/?page=1' % id)\n\t\t\tif r.status_code == 200:\n\t\t\t\tsoup = BeautifulSoup(r.text)\n\t\t\t\ticon_list = soup.find(\"ul\", class_=\"iconList\")\n\t\t\t\tif icon_list is not None:\n\t\t\t\t\trank = 0\n\t\t\t\t\tfor i in icon_list.find_all(\"li\"):\n\t\t\t\t\t\trank += 1\n\t\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\t\tif i.find('h3') is not None and i.find('h3').find('a') is not None:\n\t\t\t\t\t\t\titem = i.find('h3').find('a')\n\t\t\t\t\t\t\turl \t\t= u\"http://zhushou.360.cn/detail/index/soft_id/%s\" % item.get('sid')\n\t\t\t\t\t\t\tgame_name = item.text\n\t\t\t\t\t\t\timg = i.find(\"a\", sid=\"%s\" % item.get(\"sid\")).find(\"img\").get(\"_src\")\n\t\t\t\t\t\t\tdownloads = i.find(\"span\").text\n\t\t\t\t\t\t\tsize \t\t= u\"\"\n\t\t\t\t\t\t\tsource \t\t= source_map.get(gtype)\n\t\t\t\t\t\t\t#print rank, game_name, img, downloads, size, source, popular, game_type, status, url\n\t\t\t\t\t\t\tstore_data((rank, game_name, img, downloads, size, source, popular, game_type, status, url))\n\t\texcept Exception,e:\n\t\t\tmylogger.error(\"%s\\t%s\" % (url, traceback.format_exc()))\n\tmylogger.info(\"get 360zhushou web done!\")\n\t\t\t\n\ndef store_9game_web_app_rank():\n\t_dict = {'9game': \"http://www.9game.cn/xyrb/\", '9game_hot_wanted':\"http://www.9game.cn/xyqdb/\"}\n\tfor gtype, url in _dict.iteritems():\n\t\tget_9game_web_app_rank(gtype, url)\n\ndef get_9game_web_app_rank(gtype, url):\n\ttry:\t\n\t\tp = proxies[random.randrange(len(proxies))]\n\t\tr = requests.get(url, timeout=10)\n\t\tif r.status_code == 200:\n\t\t\tsoup = BeautifulSoup(r.text)\n\t\t\tt = soup.find(\"div\", class_=\"box-text\").find(\"table\").find_all(\"tr\")\n\t\t\tfor i in t[1:]:\n\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\ttd_list = i.find_all(\"td\")\n\t\t\t\trank = td_list[0].find(\"span\").text\n\t\t\t\tgame_name = td_list[1].find(\"a\").get(\"title\")\n\t\t\t\turl = u\"http://www.9game.cn%s\" % td_list[1].find(\"a\").get(\"href\")\n\t\t\t\tgame_type = td_list[2].text.rstrip()\n\t\t\t\tstatus = td_list[3].text.strip()\n\t\t\t\tpopular = td_list[4].text.strip()\n\t\t\t\tsource = source_map.get(gtype)\n\t\t\t\tdownloads = popular\n\t\t\t\tstore_data((rank, game_name, img, downloads, size, source, popular, game_type, status, url))\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (url, traceback.format_exc()))\n\n\nheaders = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36'}\n\ndef get_appannie_hot_list():\n\tr = s.get(\"https://www.appannie.com/apps/ios/top/china/games/?device=iphone\", headers=headers, timeout=10)\n\tif r.status_code == 200:\n\t\tsoup = BeautifulSoup(r.text)\n\t\tt = soup.find(\"div\", class_=\"region-main-inner\").find(\"table\").find_all(\"tr\")\n\t\tfor i in t[1:]:\n\t\t\thot = i.find_all(\"td\")[2]\n\t\t\td = hot.find(\"div\", class_=\"main-info\").find(\"a\")\n\t\t\tyield d.text, d.get(\"href\")\n\ndef get_appannie_detail():\n\tfor i in get_appannie_hot_list():\n\t\tapp_name, url = i\n\t\tr = s.get(\"https://www.appannie.com/cn%s\" % url, headers=headers)\n\t\tif r.status_code == 200:\n\t\t\tsoup = BeautifulSoup(r.text)\n\t\t\timg_div = soup.find(\"div\", class_=\"col-lg-3 col-md-3 col-sm-4 text-center-mobile app-logo\")\n\t\t\tyield app_name, img_div.find(\"img\").get(\"src\"), u\"\", u\"\", 4\n\n\ndef get_360_app_rank(gtype):\n\trank = 0\n\ttype_2_source = {'single': '360_app_single',\n\t\t\t\t\t\t'webgame': '360_app_webgame',\n\t\t\t\t\t\t'expect': '360_app_expect',\n\t\t\t\t\t\t'new': '360_app_new_game'}\n\t_url = 'http://openboxcdn.mobilem.360.cn//app/rank?from=game&type=%s&page=1' % gtype\n\ttry:\n\t\tr = requests.get(_url, timeout=10)\n\t\tif r.status_code == 200:\n\t\t\tj = r.json()\n\t\t\tif j['errno'] == u'0':\n\t\t\t\tfor app in j['data']:\n\t\t\t\t\trank += 1\n\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\tgame_name = app.get('name', u'')\n\t\t\t\t\timg = app.get('logo_url', u'')\n\t\t\t\t\tdownloads = app.get('download_times', u'')\n\t\t\t\t\tsize = app.get('size', u'')\n\t\t\t\t\tgame_type = app.get('category_name', u'')\n\t\t\t\t\turl = app.get('apkid', u'') + \"\\t\" + app.get('id', u'')\n\t\t\t\t\tsource = source_map.get(type_2_source.get(gtype))\n\t\t\t\t\tyield rank, game_name, img, downloads, size, source, popular, game_type, status, url\n\texcept Exception,e:\n\t\tmylogger.error(\"%s====>\\t%s\" % (_url, traceback.format_exc()))\n\ndef store_360_app_rank():\n\tfor gtype in ['single', 'webgame', 'new', 'expect']:\n\t\tmylogger.info(\"360 %s rank start... \" % gtype)\n\t\tfor data in get_360_app_rank(gtype):\n\t\t\tstore_data(data)\n\n\ndef get_m5qq_app_rank(gtype):\n\t#应用宝 PC\n\trank = 0\n\ttype_2_source = {\n\t\t\t\t\t\t'16': 'm5_qq_download',\n\t\t\t\t\t\t'19': 'm5_qq_single',\n\t\t\t\t\t\t'20': 'm5_qq_webgame',\n\t\t\t\t\t\t'18': 'm5_qq_new_game',\n\t\t\t\t\t}\n\t_url = 'http://m5.qq.com/app/applist.htm?listType=%s&pageSize=50&contextData=' % gtype\n\ttry:\n\t\tr = requests.get(_url, timeout=10)\n\t\tif r.status_code == 200:\n\t\t\tj = r.json()\n\t\t\tif 'obj' in j and 'appList' in j['obj']:\n\t\t\t\tfor app in j['obj']['appList']:\n\t\t\t\t\trank += 1\n\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\tgame_name = app.get('appName', u'')\n\t\t\t\t\timg = app.get('iconUrl', u'')\n\t\t\t\t\tdownloads = app.get('appDownCount', u'')\n\t\t\t\t\tsize = app.get('fileSize', u'')\n\t\t\t\t\tgame_type = app.get('categoryName', u'')\n\t\t\t\t\turl = u\"%s\\t%s\" % (app.get('pkgName', u''), app.get('appId', u''))\n\t\t\t\t\tsource = source_map.get(type_2_source.get(gtype))\n\t\t\t\t\tyield rank, game_name, img, downloads, size, source, popular, game_type, status, url\n\texcept Exception,e:\n\t\tmylogger.error(\"%s====>\\t%s\" % (_url, traceback.format_exc()))\n\ndef store_m5qq_app_rank():\n\tfor gtype in ['16', '18', '19', '20']:\n\t\tmylogger.info(\"get_m5qq_app_rank %s rank start... \" % gtype)\n\t\tfor data in get_m5qq_app_rank(gtype):\n\t\t\tstore_data(data)\n\n\nBAIDU_SINGLE_RANK = 0\nBAIDU_WEBGAME_RANK = 0 \nBAIDU_NEW_GAME_RANK = 0 \n\n\ndef get_m_baidu_rank(gtype, _url):\n\tglobal BAIDU_SINGLE_RANK\n\tglobal BAIDU_WEBGAME_RANK\n\tglobal BAIDU_NEW_GAME_RANK\n\n\ttry:\n\t\tp = proxies[random.randrange(len(proxies))]\n\t\tr = requests.get(_url, timeout=10, proxies=p)\n\t\tif r.status_code == 200:\n\t\t\tj = r.json()\n\t\t\tif 'result' in j and 'data' in j['result']:\n\t\t\t\tfor item in j['result']['data']:\n\t\t\t\t\tif 'itemdata' in item:\n\t\t\t\t\t\tif gtype == 'm_baidu_single':\n\t\t\t\t\t\t\tBAIDU_SINGLE_RANK += 1\n\t\t\t\t\t\t\trank = BAIDU_SINGLE_RANK\n\t\t\t\t\t\telif gtype == 'm_baidu_webgame':\n\t\t\t\t\t\t\tBAIDU_WEBGAME_RANK += 1\n\t\t\t\t\t\t\trank = BAIDU_WEBGAME_RANK\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tBAIDU_NEW_GAME_RANK += 1\n\t\t\t\t\t\t\trank = BAIDU_NEW_GAME_RANK\n\t\t\t\t\t\tapp = item.get('itemdata', {})\n\t\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\t\tgame_name = app.get('sname', u'')\n\t\t\t\t\t\timg = app.get('icon', u'')\n\t\t\t\t\t\tdownloads = app.get('display_download', u'')\n\t\t\t\t\t\tsize = app.get('size', u'')\n\t\t\t\t\t\tgame_type = app.get('catename', u'')\n\t\t\t\t\t\turl = u\"%s\\t%s\" % (app.get('package', u''), app.get('docid', u''))\n\t\t\t\t\t\tsource = source_map.get(gtype)\n\t\t\t\t\t\t#print rank, game_name, source\n\t\t\t\t\t\tyield rank, game_name, img, downloads, size, source, popular, game_type, status, url\n\texcept Exception,e:\n\t\tmylogger.error(\"%s====>\\t%s\" % (_url, traceback.format_exc()))\n\n\ndef store_m_baidu_app_rank():\n\tprefix_single_url = \"http://m.baidu.com/appsrv?uid=YPvuu_PqvfgkiHf30uS88liwHulTiSiQYiHPfgiOB8qLuHf3_PvoigaX2ig5uBiN3dqqC&native_api=1&psize=3&abi=armeabi-v7a&cll=_hv19g8O2NAVA&usertype=0&is_support_webp=true&ver=16786356&from=1011454q&board_id=board_102_736&operator=460015&network=WF&pkname=com.dragon.android.pandaspace&country=CN&cen=cuid_cut_cua_uid&gms=false&platform_version_id=19&firstdoc=&name=game&action=ranklist&pu=cua%40_a-qi4uq-igBNE6lI5me6NIy2I_UC-I4juDpieLqA%2Cosname%40baiduappsearch%2Cctv%401%2Ccfrom%401010680f%2Ccuid%40YPvuu_PqvfgkiHf30uS88liwHulTiSiQYiHPfgiOB86QuviJ0O2lfguGv8_Huv8uja20fqqqB%2Ccut%405fXCirktSh_Uh2IJgNvHtyN6moi5pQqAC&language=zh&apn=&native_api=1&f=gameranklist%40tab%401&bannert=26%4027%4028%4029%4030%4031%4032%4043\" \n\tsingle_url = [prefix_single_url + \"&pn=%s\" %p for p in xrange(5)]\n\tprefix_new_games_url = 'http://m.baidu.com/appsrv?uid=YPvuu_PqvfgkiHf30uS88liwHulTiSiQYiHPfgiOB8qLuHf3_PvoigaX2ig5uBiN3dqqC&native_api=1&psize=3&abi=armeabi-v7a&cll=_hv19g8O2NAVA&usertype=0&is_support_webp=true&ver=16786356&from=1011454q&board_id=board_102_737&operator=460015&network=WF&pkname=com.dragon.android.pandaspace&country=CN&cen=cuid_cut_cua_uid&gms=false&platform_version_id=19&firstdoc=&name=game&action=ranklist&pu=cua%40_a-qi4uq-igBNE6lI5me6NIy2I_UC-I4juDpieLqA%2Cosname%40baiduappsearch%2Cctv%401%2Ccfrom%401010680f%2Ccuid%40YPvuu_PqvfgkiHf30uS88liwHulTiSiQYiHPfgiOB86QuviJ0O2lfguGv8_Huv8uja20fqqqB%2Ccut%405fXCirktSh_Uh2IJgNvHtyN6moi5pQqAC&language=zh&apn=&&native_api=1&f=gameranklist%40tab%403&bannert=26%4027%4028%4029%4030%4031%4032%4043'\n\tnew_games_url = [prefix_new_games_url+ \"&pn=%s\" %p for p in xrange(5)]\n\tprefix_web_game_url = 'http://m.baidu.com/appsrv?uid=YPvuu_PqvfgkiHf30uS88liwHulTiSiQYiHPfgiOB8qLuHf3_PvoigaX2ig5uBiN3dqqC&native_api=1&psize=3&abi=armeabi-v7a&cll=_hv19g8O2NAVA&usertype=0&is_support_webp=true&ver=16786356&from=1011454q&board_id=board_102_735&operator=460015&network=WF&pkname=com.dragon.android.pandaspace&country=CN&cen=cuid_cut_cua_uid&gms=false&platform_version_id=19&firstdoc=&name=game&action=ranklist&pu=cua%40_a-qi4uq-igBNE6lI5me6NIy2I_UC-I4juDpieLqA%2Cosname%40baiduappsearch%2Cctv%401%2Ccfrom%401010680f%2Ccuid%40YPvuu_PqvfgkiHf30uS88liwHulTiSiQYiHPfgiOB86QuviJ0O2lfguGv8_Huv8uja20fqqqB%2Ccut%405fXCirktSh_Uh2IJgNvHtyN6moi5pQqAC&language=zh&apn=&&native_api=1&f=gameranklist%40tab%402&bannert=26%4027%4028%4029%4030%4031%4032%4043'\n\tweb_game_url = [prefix_web_game_url+\"&pn=%s\" %p for p in xrange(5)]\n\tprefix_top_url = 'http://m.baidu.com/appsrv?uid=YPvuu_PqvfgkiHf30uS88liwHulTiSiQYiHPfgiOB8qLuHf3_PvoigaX2ig5uBiN3dqqC&native_api=1&psize=3&abi=armeabi-v7a&cll=_hv19g8O2NAVA&usertype=0&is_support_webp=true&ver=16786356&from=1011454q&board_id=board_102_139&operator=460015&network=WF&pkname=com.dragon.android.pandaspace&country=CN&cen=cuid_cut_cua_uid&gms=false&platform_version_id=19&firstdoc=&name=game&action=ranklist&pu=cua%40_a-qi4uq-igBNE6lI5me6NIy2I_UC-I4juDpieLqA%2Cosname%40baiduappsearch%2Cctv%401%2Ccfrom%401010680f%2Ccuid%40YPvuu_PqvfgkiHf30uS88liwHulTiSiQYiHPfgiOB86QuviJ0O2lfguGv8_Huv8uja20fqqqB%2Ccut%405fXCirktSh_Uh2IJgNvHtyN6moi5pQqAC&language=zh&apn=&&native_api=1&f=gameranklist%40tab%400&bannert=26%4027%4028%4029%4030%4031%4032%4043'\n\ttop_game_url = [prefix_top_url+\"&pn=%s\" %p for p in xrange(5)]\n\t_dict = {'m_baidu_top': top_game_url, 'm_baidu_single': single_url, 'm_baidu_webgame': web_game_url, 'm_baidu_new_game': new_games_url}\n\tfor gtype, urls in _dict.iteritems():\n\t\tfor _url in urls:\n\t\t\tfor data in get_m_baidu_rank(gtype, _url):\n\t\t\t\tstore_data(data)\n\t\t\ndef get_dangle_app_rank():\n\t_url = 'http://api2014.digua.d.cn/newdiguaserver/game/rank?pn=1&type=16&ps=50'\n\theaders = {'HEAD': {\"stamp\":1448610575430,\"verifyCode\":\"78492ba9e8569f3b9d9173ac4e4b6cb9\",\"it\":2,\"resolutionWidth\":1080,\"imei\":\"865931027730878\",\"clientChannelId\":\"100327\",\"versionCode\":750,\"mac\":\"34:80:b3:4d:69:87\",\"vender\":\"Qualcomm\",\"vp\":\"\",\"version\":\"7.5\",\"sign\":\"2ec90f723384b1ec\",\"dd\":480,\"sswdp\":\"360\",\"hasRoot\":0,\"glEsVersion\":196608,\"device\":\"MI_4LTE\",\"ss\":2,\"local\":\"zh_CN\",\"language\":\"2\",\"sdk\":19,\"resolutionHeight\":1920,\"osName\":\"4.4.4\",\"gpu\":\"Adreno (TM) 330\"}}\n\trank = 0\n\ttry:\n\t\tr = requests.post(_url, timeout=10, headers=headers)\n\t\tif r.status_code == 200:\n\t\t\tj = r.json()\n\t\t\tif 'list' in j:\n\t\t\t\tfor app in j['list']:\n\t\t\t\t\trank += 1\n\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\tgame_name = app.get('name', u'')\n\t\t\t\t\timg = app.get('iconUrl', u'')\n\t\t\t\t\tdownloads = app.get('downs', u'')\n\t\t\t\t\tgame_type = app.get('categoryName', u'')\n\t\t\t\t\tsource = source_map.get('dangle_new_game')\n\t\t\t\t\turl = u\"%s\\t%s\" % (app.get('resourceType', u''), app.get('id', u''))\n\t\t\t\t\tstore_data((rank, game_name, img, downloads, size, source, popular, game_type, status, url))\n\texcept Exception,e:\n\t\tmylogger.error(\"%s====>\\t%s\" % (_url, traceback.format_exc()))\n\n\n\ndef get_data(f):\n\tfor i in enumerate(f()):\n\t\trank, ret = i\n\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = ret\n\t\tins = db_conn.query(HotGames).filter(HotGames.name==game_name).filter(HotGames.source==source).filter(HotGames.create_date==date.today()).first()\n\t\tif ins is None:\n\t\t\titem = HotGames(**{\n\t\t\t\t\t\t\t\"name\"\t\t\t: game_name,\n\t\t\t\t\t\t\t\"src\"\t\t\t: img,\n\t\t\t\t\t\t\t\"download_count\"\t\t: downloads,\n\t\t\t\t\t\t\t\"size\"\t\t\t: size,\n\t\t\t\t\t\t\t\"source\"\t\t: source,\n\t\t\t\t\t\t\t\"rank\"\t\t\t: rank+1,\n\t\t\t\t\t\t\t\"popular\"\t\t: popular,\n\t\t\t\t\t\t\t\"game_type\"\t\t: game_type,\n\t\t\t\t\t\t\t\"status\"\t\t: status,\n\t\t\t\t\t\t\t\"url\"\t\t\t: url\n\t\t\t\t\t\t\t})\n\t\t\tdb_conn.merge(item)\n\tdb_conn.commit()\n\tmylogger.info(\"%s done!\" % f.__name__)\n\n\ndef get_vivo_app_rank(gtype, _url):\n\trank = 0\n\ttry:\n\t\tr = requests.get(_url, timeout=10)\n\t\tif r.status_code == 200:\n\t\t\tj = r.json()\n\t\t\tif 'msg' in j:\n\t\t\t\tfor app in j['msg']:\n\t\t\t\t\trank += 1\n\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\tgame_name = app.get('name', u'')\n\t\t\t\t\timg = app.get('icon', u'')\n\t\t\t\t\tdownloads = app.get('download', u'')\n\t\t\t\t\tsize = app.get('size', u'')\n\t\t\t\t\tgame_type = app.get('type', u'')\n\t\t\t\t\turl = u\"%s\\t%s\" % (app.get('pkgName', u''), app.get('id', u''))\n\t\t\t\t\tsource = source_map.get(gtype)\n\t\t\t\t\tyield rank, game_name, img, downloads, size, source, popular, game_type, status, url\n\t\t\t\t\t#for k, v in app.iteritems():\n\t\t\t\t\t#\tprint k, v\n\t\t\t\t\t#print \n\texcept Exception,e:\n\t\tmylogger.error(\"%s====>\\t%s\" % (_url, traceback.format_exc()))\n\ndef store_vivo_app_rank():\n\tnew_games_url = 'http://main.gamecenter.vivo.com.cn/clientRequest/rankList?appVersionName=2.0.0&model=MI+4LTE&e=11010030313647453200da18b1312200&page_index=1&pixel=3.0&imei=865931027730878&origin=527&type=new&av=19&patch_sup=1&cs=0&adrVerName=4.4.4&appVersion=37&elapsedtime=18535194&s=2%7C1363799553'\n\tsingle_url = 'http://main.gamecenter.vivo.com.cn/clientRequest/rankList?appVersionName=2.0.0&model=MI+4LTE&e=11010030313647453200da18b1312200&page_index=1&pixel=3.0&imei=865931027730878&origin=528&type=Alone20150916173741&av=19&patch_sup=1&cs=0&adrVerName=4.4.4&appVersion=37&elapsedtime=18658164&s=2%7C1323451747'\n\tweb_game_url = 'http://main.gamecenter.vivo.com.cn/clientRequest/rankList?appVersionName=2.0.0&model=MI+4LTE&e=11010030313647453200da18b1312200&page_index=1&pixel=3.0&imei=865931027730878&origin=529&type=Compr20150916173717&av=19&patch_sup=1&cs=0&adrVerName=4.4.4&appVersion=37&elapsedtime=18675505&s=2%7C2756240867'\n\t_dict = {'vivo_single': single_url, 'vivo_webgame': web_game_url, 'vivo_new_game': new_games_url}\t\n\tfor gtype, _url in _dict.iteritems():\n\t\tfor data in get_vivo_app_rank(gtype, _url):\n\t\t\tstore_data(data)\n\ndef get_gionee_app_rank(gtype, param):\n\trank = 0\n\ttry:\n\t\tfor page in xrange(1, 6):\n\t\t\t_url = 'http://game.gionee.com/Api/Local_Clientrank/%s/?&page=%s' % (param, page)\n\t\t\tr = requests.get(_url, timeout=10)\n\t\t\tif r.status_code == 200:\n\t\t\t\tj = r.json()\n\t\t\t\tif 'data' in j and 'list' in j['data']:\n\t\t\t\t\tfor app in j['data']['list']:\n\t\t\t\t\t\trank += 1\n\t\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\t\tgame_name = app.get('name', u'')\n\t\t\t\t\t\timg = app.get('img', u'')\n\t\t\t\t\t\tdownloads = app.get('downloadCount', u'')\n\t\t\t\t\t\tsize = app.get('size', u'')\n\t\t\t\t\t\tgame_type = app.get('category', u'')\n\t\t\t\t\t\turl = u\"%s\\t%s\" % (app.get('package', u''), app.get('gameid', u''))\n\t\t\t\t\t\tsource = source_map.get(gtype)\n\t\t\t\t\t\tyield rank, game_name, img, downloads, size, source, popular, game_type, status, url\n\texcept Exception,e:\n\t\tmylogger.error(\"%s====>\\t%s\" % (_url, traceback.format_exc()))\n\ndef store_gionee_app_rank():\n\t_map = {\n\t\t\t\t\t\t\"gionee_active\": 'olactiveRankIndex',\n\t\t\t\t\t\t\"gionee_hot\": 'soaringRankIndex',\n\t\t\t\t\t}\n\tfor gtype, param in _map.iteritems():\n\t\tfor data in get_gionee_app_rank(gtype, param):\n\t\t\tstore_data(data)\n\t\t\n\ndef get_coolpad_app_rank(gtype, fd):\n\trank = 0\n\t_url = \"http://gamecenter.coolyun.com/gameAPI/API/getResList?key=0\"\n\ttry:\n\t\tr = requests.post(_url, timeout=10, data=fd, headers=headers)\n\t\tif r.status_code == 200:\n\t\t\tt = re.sub(u'\\r|\\n', '', r.text)\n\t\t\tdoc = xmltodict.parse(t)\n\t\t\tif '@msg' in doc['response'] and doc['response']['@msg'] == u'成功':\n\t\t\t\tfor app in doc['response']['reslist']['res']:\n\t\t\t\t\trank += 1\n\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\tgame_name = app.get('@name', u'')\n\t\t\t\t\timg = app.get('icon', u'')\n\t\t\t\t\tdownloads = app.get('downloadtimes', u'')\n\t\t\t\t\tgame_type = app.get('levelname', u'')\n\t\t\t\t\tsource = source_map.get(gtype)\n\t\t\t\t\tsize = app.get('size', u'')\n\t\t\t\t\turl = u\"%s\\t%s\" % (app.get('package_name', u''), app.get('@rid', u''))\n\t\t\t\t\tyield rank, game_name, img, downloads, size, source, popular, game_type, status, url\n\texcept Exception,e:\n\t\tmylogger.error(\"%s====>\\t%s\" % (gtype, traceback.format_exc()))\n\n\n\ndef store_coolpad_app_rank():\n\twebgame_raw_data=\"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?><request username=\"\" cloudId=\"\" openId=\"\" sn=\"865931027730878\" platform=\"1\" platver=\"19\" density=\"480\" screensize=\"1080*1920\" language=\"zh\" mobiletype=\"MI4LTE\" version=\"4\" seq=\"0\" appversion=\"3350\" currentnet=\"WIFI\" channelid=\"coolpad\" networkoperator=\"46001\" simserianumber=\"89860115851040101064\" ><rankorder>0</rankorder><syncflag>0</syncflag><start>1</start><categoryid>1</categoryid><iscoolpad>0</iscoolpad><level>0</level><querytype>5</querytype><max>30</max></request>\"\"\"\n\n\tnew_game_raw_data=\"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?><request username=\"\" cloudId=\"\" openId=\"\" sn=\"865931027730878\" platform=\"1\" platver=\"19\" density=\"480\" screensize=\"1080*1920\" language=\"zh\" mobiletype=\"MI4LTE\" version=\"4\" seq=\"0\" appversion=\"3350\" currentnet=\"WIFI\" channelid=\"coolpad\" networkoperator=\"46001\" simserianumber=\"89860115851040101064\" ><rankorder>0</rankorder><syncflag>0</syncflag><start>1</start><categoryid>1</categoryid><iscoolpad>0</iscoolpad><level>0</level><querytype>3</querytype><max>30</max></request>\"\"\"\n\n\thot_game_raw_data=\"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?><request username=\"\" cloudId=\"\" openId=\"\" sn=\"865931027730878\" platform=\"1\" platver=\"19\" density=\"480\" screensize=\"1080*1920\" language=\"zh\" mobiletype=\"MI4LTE\" version=\"4\" seq=\"0\" appversion=\"3350\" currentnet=\"WIFI\" channelid=\"coolpad\" networkoperator=\"46001\" simserianumber=\"89860115851040101064\" ><rankorder>0</rankorder><syncflag>0</syncflag><start>1</start><categoryid>1</categoryid><iscoolpad>0</iscoolpad><level>0</level><querytype>6</querytype><max>30</max></request>\"\"\"\n\n\t_dict = {'coolpad_hot': hot_game_raw_data, 'coolpad_webgame': webgame_raw_data, 'coolpad_new_game': new_game_raw_data}\t\n\tfor gtype, rd in _dict.iteritems():\n\t\tfor data in get_coolpad_app_rank(gtype, rd):\n\t\t\tstore_data(data)\n\ndef get_open_play_app_rank(gtype, _url):\n\trank = 0\n\ttry:\n\t\tr = requests.get(_url, timeout=10)\n\t\tif r.status_code == 200:\n\t\t\tj = r.json()\n\t\t\tif j['code'] == 0:\n\t\t\t\tfor app in j['ext']['main']['content']['game_list']:\n\t\t\t\t\trank += 1\n\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\tgame_name = app.get('game_name', u'')\n\t\t\t\t\timg = app.get('game_icon', u'')\n\t\t\t\t\tdownloads = app.get('game_download_count', u'')\n\t\t\t\t\tsize = app.get('game_size', u'')\n\t\t\t\t\tgame_type = app.get('class_name', u'')\n\t\t\t\t\turl = app.get('game_detail_url', u'')\n\t\t\t\t\tsource = source_map.get(gtype)\n\t\t\t\t\tyield rank, game_name, img, downloads, size, source, popular, game_type, status, url\n\texcept Exception,e:\n\t\tmylogger.error(\"%s====>\\t%s\" % (_url, traceback.format_exc()))\n\n\n\ndef store_open_play_app_rank():\n\tdownload_page \t= \"http://open.play.cn/api/v2/mobile/channel/content.json?channel_id=911&terminal_id=18166¤t_page=0&rows_of_page=50\"\n\tfree_page\t\t= \"http://open.play.cn/api/v2/mobile/channel/content.json?channel_id=914&terminal_id=18166¤t_page=0&rows_of_page=50\"\n\twebgame_page \t= \"http://open.play.cn/api/v2/mobile/channel/content.json?channel_id=917&terminal_id=18166¤t_page=0&rows_of_page=50\"\n\trise_page \t\t= \"http://open.play.cn/api/v2/mobile/channel/content.json?channel_id=916&terminal_id=18166¤t_page=0&rows_of_page=50\"\n\t_dict = {'open_play_download': download_page, 'open_play_free': free_page, 'open_play_webgame': webgame_page, 'open_play_rise': rise_page}\t\n\tfor gtype, _url in _dict.iteritems():\n\t\tfor data in get_open_play_app_rank(gtype, _url):\n\t\t\tstore_data(data)\n\ndef get_wandoujia_app_rank(gtype, _url):\n\trank = 0\n\ttry:\n\t\tr = requests.get(_url, timeout=10)\n\t\tif r.status_code == 200:\n\t\t\tj = r.json()\n\t\t\tif j['entity'] is not None:\n\t\t\t\tfor item in j['entity']:\n\t\t\t\t\trank += 1\n\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\tgame_name = item.get('title', u'')\n\t\t\t\t\timg = item.get('icon', u'')\n\t\t\t\t\tsource = source_map.get(gtype)\n\t\t\t\t\tif item['action'] is not None:\n\t\t\t\t\t\tinfo = get_wandoujia_detail(item['action']['url'])\n\t\t\t\t\t\tif info is not None:\n\t\t\t\t\t\t\tgame_type, downloads = info \n\t\t\t\t\t\turl = item['action'].get('url', u'')\n\t\t\t\t\tyield rank, game_name, img, downloads, size, source, popular, game_type, status, url\n\t\t\t\t\t#for k, v in item['detail']['appDetail'].iteritems():\n\t\t\t\t\t#\tprint k, v\n\texcept Exception,e:\n\t\tmylogger.error(\"%s====>\\t%s\" % (_url, traceback.format_exc()))\n\ndef store_wandoujia_app_rank():\n\tsingle_url \t\t= \"http://apis.wandoujia.com/five/v2/games/tops/TOP_WEEKLY_DOWNLOAD_CONSOLE_GAME?max=20\"\n\tweb_game_url \t= \"http://apis.wandoujia.com/five/v2/games/tops/TOP_WEEKLY_DOWNLOAD_ONLINE_GAME?start=0&max=20\"\n\t_dict = {'wandoujia_single': single_url, 'wandoujia_webgame': web_game_url}\t\n\tfor gtype, _url in _dict.iteritems():\n\t\tfor data in get_wandoujia_app_rank(gtype, _url):\n\t\t\tstore_data(data)\n\n\ndef get_wandoujia_detail(url):\n\ttry:\n\t\tr = requests.get(url, timeout=10)\n\texcept Exception,e:\n\t\tr = T(404)\n\t\tmylogger.error(\"### %s ### %s\" % (url.encode('utf-8'), traceback.format_exc()))\n\tif r.status_code == 200:\n\t\td = r.json()\n\t\tentity = d['entity']\n\t\tif entity:\n\t\t\tdetail = entity[0]['detail']['appDetail']\n\t\t\tif detail is not None:\n\t\t\t\tcategories = detail.get('categories', [])\n\t\t\t\tgame_type = u\",\".join([c['name'] for c in categories if c['level']==1])\n\t\t\t\tpopular = detail.get('downloadCount', u'')\n\t\t\t\treturn game_type, popular\n\treturn None\n\n\ndef get_iqiyi_app_rank(gtype, _url):\n\trank = 0\n\ttry:\n\t\tr = requests.get(_url, timeout=10)\n\t\tif r.status_code == 200:\n\t\t\tm = re.search(u'rs\\\\(([\\s\\S]*)\\\\)\\\\;', r.text)\n\t\t\tif m is not None:\n\t\t\t\td = json.loads(m.group(1))\n\t\t\t\tif d['apps'] is not None:\n\t\t\t\t\tfor app in d['apps']:\n\t\t\t\t\t\trank += 1\n\t\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\t\tgame_name = app.get('name', u'')\n\t\t\t\t\t\timg = app.get('icon', u'')\n\t\t\t\t\t\tsize = app.get('size', u'')\n\t\t\t\t\t\tdownloads = app.get('cnt', u'')\n\t\t\t\t\t\turl = app.get('qipu_id', u'')\n\t\t\t\t\t\tgame_type = app.get('cate_name', u'')\n\t\t\t\t\t\tsource = source_map.get(gtype)\n\t\t\t\t\t\tyield rank, game_name, img, downloads, size, source, popular, game_type, status, url\n\texcept Exception, e:\n\t\tmylogger.error(\"### %s ###\\n%s\" % (_url, traceback.format_exc()))\n\ndef store_iqiyi_app_rank():\n\t_dict = {'iqiyi_download': \"http://store.iqiyi.com/gc/top//download?callback=rs&id=download&no=1\", 'iqiyi_hot' : \"http://store.iqiyi.com/gc/top/up?callback=rs&t=1445585439376\"}\t\n\tfor gtype, _url in _dict.iteritems():\n\t\tfor data in get_iqiyi_app_rank(gtype, _url):\n\t\t\tstore_data(data)\n\n\ndef get_youku_app_rank(gtype, _url):\n\trank = 0\n\ttry:\n\t\tr = requests.get(_url, timeout=10)\n\t\tif r.status_code == 200:\n\t\t\tj = r.json()\n\t\t\tif j['status'] == u'success':\n\t\t\t\tfor app in j['games']:\n\t\t\t\t\trank += 1\n\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\tgame_name = app.get('appname', u'')\n\t\t\t\t\timg = app.get('logo', u'')\n\t\t\t\t\tdownloads = app.get('total_downloads', u'')\n\t\t\t\t\tsize = app.get('size', u'')\n\t\t\t\t\turl = app.get('id', u'')\n\t\t\t\t\tsource = source_map.get(gtype)\n\t\t\t\t\tyield rank, game_name, img, downloads, size, source, popular, game_type, status, url\n\t\t\t\t\t#for k,v in app.iteritems():\n\t\t\t\t\t#\tprint k,v\n\texcept Exception,e:\n\t\tmylogger.error(\"%s====>\\t%s\" % (_url, traceback.format_exc()))\n\n\ndef store_youku_app_rank():\n\t_dict = {\"youku_single\": 'http://api.gamex.mobile.youku.com/app/rank/classified?product_id=1&pz=40&pg=1&type=1', 'youku_webgame': 'http://api.gamex.mobile.youku.com/app/rank/classified?product_id=1&pz=40&pg=1&type=0'}\n\tfor gtype, _url in _dict.iteritems():\n\t\tfor data in get_youku_app_rank(gtype, _url):\n\t\t\tstore_data(data)\n\ndef get_sogou_app_rank(gtype, _url):\n\trank = 0\n\ttry:\n\t\tr = requests.get(_url, timeout=10)\n\t\tif r.status_code == 200:\n\t\t\tj = r.json()\n\t\t\tif j['recommend_app'] is not None:\n\t\t\t\tfor app in j['recommend_app']:\n\t\t\t\t\trank += 1\n\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\tgame_name = app.get('name', u'')\n\t\t\t\t\timg = app.get('icon', u'')\n\t\t\t\t\tsize = app.get('size', u'')\n\t\t\t\t\tdownloads = app.get('downloadCount', u'')\n\t\t\t\t\tsize = app.get('size', u'')\n\t\t\t\t\tsource = source_map.get(gtype)\n\t\t\t\t\turl = u\"%s\\t%s\" % (app.get('packagename', u''), app.get('appid', u''))\n\t\t\t\t\tyield rank, game_name, img, downloads, size, source, popular, game_type, status, url\n\t\t\t\t\t#for k,v in app.iteritems():\n\t\t\t\t\t#\tprint k,v\n\texcept Exception,e:\n\t\tmylogger.error(\"%s====>\\t%s\" % (_url, traceback.format_exc()))\n\n\ndef store_sogou_app_rank():\n\t_dict = {\"sogou_single\": 'http://mobile.zhushou.sogou.com/android/rank/toplist.html?id=12&limit=25&group=2&start=0&iv=41&uid=f3c2ed94d7d2272de87a8ef3abab2409&vn=4.1.3&channel=baidu&sogouid=a7f30d60a6b1aed168a8c9d7c46bbac5&stoken==SnxL9KjGT6sBvQ7ZJD4Ghw&cellid=&sc=0', 'sogou_webgame': 'http://mobile.zhushou.sogou.com/android/rank/toplist.html?id=11&limit=25&group=2&start=0&iv=41&uid=f3c2ed94d7d2272de87a8ef3abab2409&vn=4.1.3&channel=baidu&sogouid=a7f30d60a6b1aed168a8c9d7c46bbac5&stoken==SnxL9KjGT6sBvQ7ZJD4Ghw&cellid=&sc=0', 'sogou_download':'http://mobile.zhushou.sogou.com/android/rank/toplist.html?id=10&limit=25&group=2&start=0&iv=41&uid=f3c2ed94d7d2272de87a8ef3abab2409&vn=4.1.3&channel=baidu&sogouid=a7f30d60a6b1aed168a8c9d7c46bbac5&stoken==SnxL9KjGT6sBvQ7ZJD4Ghw&cellid=&sc=0'}\n\tfor gtype, _url in _dict.iteritems():\n\t\tfor data in get_sogou_app_rank(gtype, _url):\n\t\t\tstore_data(data)\n\tmylogger.info(\"get sogou app rank end... \")\n\ndef get_i4_app_rank():\n\trank = 0\n\t_url = 'http://app3.i4.cn/controller/action/online.go?store=3&module=3&rows=50&sort=2&submodule=5&model=101&id=0&reqtype=3&page=1'\n\ttry:\n\t\tr = requests.get(_url, timeout=10)\n\t\tif r.status_code == 200:\n\t\t\tj = r.json()\n\t\t\tif j['result'] is not None and j['result']['list']:\n\t\t\t\tfor app in j['result']['list']:\n\t\t\t\t\trank += 1\n\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\tgame_name = app.get('appName', u'')\n\t\t\t\t\timg = u'http://d.image.i4.cn/image/%s' % app.get('icon', u'')\n\t\t\t\t\tsize = app.get('size', u'')\n\t\t\t\t\tgame_type = app.get('typeName', u'')\n\t\t\t\t\tdownloads = app.get('downCount', u'')\n\t\t\t\t\tsize = app.get('size', u'')\n\t\t\t\t\tsource = source_map.get('i4_hot')\n\t\t\t\t\turl = u\"%s\\t%s\" % (app.get('sourceId', u''), app.get('id', u''))\n\t\t\t\t\tstore_data((rank, game_name, img, downloads, size, source, popular, game_type, status, url))\n\texcept Exception,e:\n\t\tmylogger.error(\"%s====>\\t%s\" % (_url, traceback.format_exc()))\n\n\ndef get_pp_app_rank():\n\trank = 0\n\theaders = {'tunnel-command':4261421088}\n\ttry:\n\t\td = {\"dcType\":0, \"resType\":2, \"listType\":5, \"catId\":0, \"clFlag\":1, \"perCount\":50, \"page\":0}\n\t\tr = requests.post('http://jsondata.25pp.com/index.html', data=json.dumps(d), headers=headers)\n\t\tif r.status_code == 200:\n\t\t\tcontent = re.sub(u'\\ufeff', u'', r.text)\n\t\t\tj = json.loads(content)\n\t\t\tif j['content'] is not None:\n\t\t\t\tfor app in j['content']:\n\t\t\t\t\trank += 1\n\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\tgame_name = app.get('title', u'')\n\t\t\t\t\timg = app.get('thumb', u'')\n\t\t\t\t\tdownloads = app.get('downloads', u'')\n\t\t\t\t\tsize = app.get('fsize', u'')\n\t\t\t\t\tsource = source_map.get('pp_hot')\n\t\t\t\t\turl = u\"%s\\t%s\" % (app.get('buid', u''), app.get('id', u''))\n\t\t\t\t\tout = [rank, game_name, img, downloads, size, source, popular, game_type, status, url]\n\t\t\t\t\tstore_data(out)\n\texcept Exception,e:\n\t\tmylogger.error(\"get pp app rank\\t%s\" % (traceback.format_exc()))\n\n\n\ndef get_kuaiyong_app_rank():\n\trank = 0\n\tURL = \"http://app.kuaiyong.com/ranking/index/appType/game\"\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\tfor item in soup.find_all('div', class_=\"app-item-info\"):\n\t\t\t\tinfo = item.find('a', class_='app-name')\n\t\t\t\tif info is not None:\n\t\t\t\t\tdetail_url = u\"http://app.kuaiyong.com%s\" % info.get('href')\n\t\t\t\t\tapp = get_kuaiyong_detail(detail_url)\n\t\t\t\t\tif app:\n\t\t\t\t\t\trank += 1\n\t\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\t\tgame_name = app.get('title', u'')\n\t\t\t\t\t\timg = app.get('img', u'')\n\t\t\t\t\t\tsize = app.get(u'大 小', u'')\n\t\t\t\t\t\tdownloads = app.get(u'下载', u'')\n\t\t\t\t\t\tgame_type = app.get(u'类 别', u'')\n\t\t\t\t\t\tsource = source_map.get('kuaiyong_hot')\n\t\t\t\t\t\turl = detail_url\n\t\t\t\t\t\tout = [rank, game_name, img, downloads, size, source, popular, game_type, status, url]\n\t\t\t\t\t\tstore_data(out)\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\n\ndef get_kuaiyong_detail(URL):\n\tmydict = {}\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\t\tresponse = T(404)\n\tif response.status_code == 200:\n\t\tsoup = BeautifulSoup(response.text)\n\t\tbase_left = soup.find('div', class_='base-left')\n\t\tif base_left is not None:\n\t\t\timg = base_left.find('img')\n\t\t\tif img is not None:\n\t\t\t\tmydict['img'] = img.get('src')\n\t\tbase_right = soup.find('div', class_='base-right')\n\t\tif base_right is not None:\n\t\t\tif base_right.find('h1') is not None:\n\t\t\t\tmydict[u'title'] = base_right.find('h1').text\n\t\t\tbase_list = base_right.find('div', class_='base-list')\n\t\t\tif base_list is not None:\n\t\t\t\tfor ret in base_list.find_all('p'):\n\t\t\t\t\tif ret.text:\n\t\t\t\t\t\tsegs = ret.text.split(u':')\n\t\t\t\t\t\tif len(segs) == 2:\n\t\t\t\t\t\t\tmydict[segs[0]] = segs[1]\n\t\t\t\t\t\telif len(segs)==1 and u'次下载' in ret.text:\n\t\t\t\t\t\t\tmydict[u'下载'] = re.sub(u'次下载|\\n|\\r', u'', ret.text)\n\treturn mydict\n\n\ndef get_itools_app_rank():\n\trank = 0\n\tURL = \"http://ios.itools.cn/game/iphone/gameall_1\"\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\tul = soup.find('ul', class_='ios_app_list')\n\t\t\tif ul is not None:\n\t\t\t\tfor app in ul.find_all('li')[:50]:\n\t\t\t\t\tapp_on = app.find('div', class_='ios_app_on')\n\t\t\t\t\tif app_on is not None:\n\t\t\t\t\t\tdetail_url = app_on.find('a').get('href') if app_on.find('a') is not None else u''\n\t\t\t\t\t\tif detail_url:\n\t\t\t\t\t\t\tdetail_url = u\"http://ios.itools.cn%s\" % detail_url\n\t\t\t\t\t\t\tapp = get_itools_detail(detail_url)\n\t\t\t\t\t\t\tif app:\n\t\t\t\t\t\t\t\trank += 1\n\t\t\t\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\t\t\t\tgame_name = app.get('title', u'')\n\t\t\t\t\t\t\t\timg = app.get('img', u'')\n\t\t\t\t\t\t\t\tsize = app.get(u'大 小', u'')\n\t\t\t\t\t\t\t\tsource = source_map.get('itools_hot')\n\t\t\t\t\t\t\t\turl = detail_url\n\t\t\t\t\t\t\t\tout = [rank, game_name, img, downloads, size, source, popular, game_type, status, url]\n\t\t\t\t\t\t\t\tstore_data(out)\n\t\t\t\t\t\t\t#for k, v in detail.iteritems():\n\t\t\t\t\t\t\t#\tprint k, v\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\tmylogger.info(\"get itools app rank end... \")\n\n\ndef get_itools_detail(URL):\n\tmydict = {}\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\tdetails_app = soup.find('div', class_=\"details_app\")\n\t\t\tif details_app is not None:\n\t\t\t\timg_div = details_app.find('div', class_='fl w140')\n\t\t\t\tif img_div is not None:\n\t\t\t\t\timg = img_div.find('p').find('img').get('src') if img_div.find('p') is not None else u''\n\t\t\t\t\tmydict['img'] = img\n\t\t\t\tinfo_div = details_app.find('dl', class_='fl')\n\t\t\t\tif info_div is not None:\n\t\t\t\t\tmydict['title'] = info_div.find('dt').text\n\t\t\t\t\tfor info in info_div.find_all('span'):\n\t\t\t\t\t\tsegs = info.text.split(u':')\n\t\t\t\t\t\tif len(segs) == 2:\n\t\t\t\t\t\t\tmydict[segs[0]] = segs[1]\n\t\t\t\t\tfor info in info_div.find_all('dd'):\n\t\t\t\t\t\tsegs = info.text.split(u':')\n\t\t\t\t\t\tif len(segs) == 2:\n\t\t\t\t\t\t\tmydict[segs[0]] = segs[1]\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\treturn mydict\n\n\ndef get_xyzs_app_rank():\n\trank = 0\n\tURL = \"http://interface.xyzs.com/v2/ios/c01/rank/game?p=1&ps=20\"\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tj = response.json()\n\t\t\tif j['code'] == 200:\n\t\t\t\tfor app in j['data']['result']:\n\t\t\t\t\trank += 1\n\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\tgame_name = app.get('title', u'')\n\t\t\t\t\timg = app.get('icon', u'')\n\t\t\t\t\tsize = app.get('size', u'')\n\t\t\t\t\tgame_type = app.get('cus_desc', u'')\n\t\t\t\t\tdownloads = app.get('downloadnum', u'')\n\t\t\t\t\tsource = source_map.get('xyzs_hot')\n\t\t\t\t\turl = u\"%s\\t%s\" % (app.get('bundleid', u''), app.get('itunesid', u''))\n\t\t\t\t\tstore_data((rank, game_name, img, downloads, size, source, popular, game_type, status, url))\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\n\ndef get_91play_app_rank():\n\trank = 0\n\tURL = \"http://play.91.com/api.php/Api/index\"\n\ttry:\n\t\traw_data = {\"firmware\":\"19\",\"time\":1449459810294,\"device\":1,\"action\":30011,\"app_version\":302,\"action_version\":4,\"mac\":\"7b715ce093480b34d6987\",\"debug\":0}\n\t\tresponse = requests.post(URL, data=raw_data, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tj = response.json()\n\t\t\tif j['data'] is not None:\n\t\t\t\tfor app in json.loads(j['data']):\n\t\t\t\t\trank += 1\n\t\t\t\t\t#for k, v in app.iteritems():\n\t\t\t\t\t#\tprint k, v\n\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\tgame_name = app.get('name', u'')\n\t\t\t\t\timg = app.get('icon_url', u'')\n\t\t\t\t\tsize = app.get('app_size', u'')\n\t\t\t\t\tgame_type = app.get('type_name', u'')\n\t\t\t\t\tdownloads = app.get('download_count', u'')\n\t\t\t\t\tsource = source_map.get('91play_hot')\n\t\t\t\t\turl = u\"%s\\t%s\" % (app.get('package_name', u''), app.get('id', u''))\n\t\t\t\t\tstore_data((rank, game_name, img, downloads, size, source, popular, game_type, status, url))\n\texcept Exception,e:\n\t\tmylogger.error(\"91play app rank\\t%s\" % (traceback.format_exc()))\n\n\ndef get_360_gamebox_app_rank(gtype, url):\n\trank = 0\n\ttry:\n\t\tresponse = requests.get(url, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tj = response.json()\n\t\t\tif j['data'] is not None:\n\t\t\t\tfor app in j['data']:\n\t\t\t\t\trank += 1\n\t\t\t\t\t#for k, v in app.iteritems():\n\t\t\t\t\t#\tprint k, v\n\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\tgame_name = app.get('name', u'')\n\t\t\t\t\timg = app.get('logo_url', u'')\n\t\t\t\t\tsize = app.get('size', u'')\n\t\t\t\t\tgame_type = app.get('category_name', u'')\n\t\t\t\t\tdownloads = app.get('download_times', u'')\n\t\t\t\t\tsource = source_map.get(gtype)\n\t\t\t\t\turl = u\"%s\\t%s\" % (app.get('apkid', u''), app.get('id', u''))\n\t\t\t\t\tyield rank, game_name, img, downloads, size, source, popular, game_type, status, url\n\texcept Exception,e:\n\t\tmylogger.error(\"360_gamebox app rank\\t%s\" % (traceback.format_exc()))\n\ndef store_360_gamebox_app_rank():\n\t_dict = {\n\t\t\t\"360_gamebox_single\" : \"http://next.gamebox.360.cn/7/xgamebox/rank?count=20&start=0&typeid=2&type=download\", \t\n\t\t\t\"360_gamebox_webgame\": \"http://next.gamebox.360.cn/7/xgamebox/rank?count=20&start=0&typeid=1&type=download\", \t\n\t\t\t}\n\tfor gtype, url in _dict.iteritems():\n\t\tfor data in get_360_gamebox_app_rank(gtype, url):\n\t\t\tstore_data(data)\n\ndef store_xiaomi_app_rank():\n\t_dict = {\"xiaomi_app_download\": \"http://app.migc.xiaomi.com/cms/interface/v5/rankgamelist1.php?uid=20150905_132380697&platform=android&os=V6.7.1.0.KXDCNCH&stampTime=1449557687000&density=480&imei=865931027730878&pageSize=20&versionCode=1822&cid=gamecenter_100_1_android%7C865931027730878&clientId=40b53f3e316bda9f83c2e0c094d5b7f6&vn=MIGAMEAPPSTAND_1.8.22&co=CN&page=1&macWifi=3480B34D6987&la=zh&ua=Xiaomi%257CMI%2B4LTE%257C4.4.4%257CKTU84P%257C19%257Ccancro&carrier=unicom&rankId=17&mnc=46001&fuid=&mid=&imsi=460015776509846&sdk=19&mac3g=&bid=701\",\n\t\t\t\"xiaomi_app_hot\": \"http://app.migc.xiaomi.com/cms/interface/v5/rankgamelist1.php?uid=20150905_132380697&platform=android&os=V6.7.1.0.KXDCNCH&stampTime=1449557980000&density=480&imei=865931027730878&pageSize=20&versionCode=1822&cid=gamecenter_100_1_android%7C865931027730878&clientId=40b53f3e316bda9f83c2e0c094d5b7f6&vn=MIGAMEAPPSTAND_1.8.22&co=CN&page=1&macWifi=3480B34D6987&la=zh&ua=Xiaomi%257CMI%2B4LTE%257C4.4.4%257CKTU84P%257C19%257Ccancro&carrier=unicom&rankId=18&mnc=46001&fuid=&mid=&imsi=460015776509846&sdk=19&mac3g=&bid=701\"}\n\tfor gtype, url in _dict.iteritems():\n\t\tget_xiaomi_app_rank(gtype, url)\n\t\t\n\ndef get_xiaomi_app_rank(gtype, url):\n\trank = 0\n\ttry:\n\t\tresponse = requests.get(url, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tj = response.json()\n\t\t\tif j['gameList'] is not None:\n\t\t\t\tfor app in j['gameList']:\n\t\t\t\t\trank += 1\n\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\tgame_name = app.get('displayName', u'')\n\t\t\t\t\timg = app.get('icon', u'')\n\t\t\t\t\tsize = app.get('apkSize', u'')\n\t\t\t\t\tgame_type = app.get('className', u'')\n\t\t\t\t\tdownloads = app.get('downloadCount', u'')\n\t\t\t\t\tsource = source_map.get(gtype)\n\t\t\t\t\turl = app.get('packageName', u'')\n\t\t\t\t\tstore_data((rank, game_name, img, downloads, size, source, popular, game_type, status, url))\n\texcept Exception,e:\n\t\tmylogger.error(\"xiaomi game app rank\\t%s\" % (traceback.format_exc()))\n\ndef store_18183_top_app_rank():\n\t_dict = {'18183_top': 'http://top.18183.com/', '18183_hot': 'http://top.18183.com/hot.html'}\n\tfor gtype, url in _dict.iteritems():\n\t\tget_18183_top_app_rank(gtype, url)\n\n\ndef get_18183_top_app_rank(gtype, url):\n\trank = 0\n\ttry:\n\t\tresponse = requests.get(url, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\tranking_mod = soup.find('div', class_='ranking-mod')\n\t\t\tif ranking_mod is not None:\n\t\t\t\tfor app in ranking_mod.find_all('li'):\n\t\t\t\t\tnum_fl = app.find('div', class_='num fl')\n\t\t\t\t\tif num_fl is not None:\n\t\t\t\t\t\tgame_name, img, downloads, size, source, popular, game_type, status, url = [u''] * 9\n\t\t\t\t\t\trank = num_fl.text\n\t\t\t\t\t\tdt = app.find('dt')\n\t\t\t\t\t\tif dt is not None and dt.find('a') is not None:\n\t\t\t\t\t\t\tgame_name = dt.find('a').get('title')\n\t\t\t\t\t\t\turl = dt.find('a').get('href')\n\t\t\t\t\t\t\timg = dt.find('img').get('src')\n\t\t\t\t\t\trank_fl = app.find('div', class_='rank fl')\n\t\t\t\t\t\tif rank_fl is not None and rank_fl.find('p') is not None:\n\t\t\t\t\t\t\tdownloads = rank_fl.find('p').text \n\t\t\t\t\t\tsource = source_map.get(gtype)\n\t\t\t\t\t\tstore_data((rank, game_name, img, downloads, size, source, popular, game_type, status, url))\n\t\t\t\t\t\t#print rank, game_name, source, url, downloads\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (url, traceback.format_exc()))\n\ndef store_data(ret):\n\trank, game_name, img, downloads, size, source, popular, game_type, status, url = ret\n\tdt = unicode(datetime.date.today())\n\tins = db_conn.query(HotGames).filter(HotGames.name==game_name).filter(HotGames.source==source).filter(HotGames.dt==dt).filter(HotGames.rank==rank).first()\n\tif ins is None:\n\t\titem = HotGames(**{\n\t\t\t\t\t\t\"name\"\t\t\t: game_name,\n\t\t\t\t\t\t\"src\"\t\t\t: img,\n\t\t\t\t\t\t\"download_count\"\t\t: downloads,\n\t\t\t\t\t\t\"size\"\t\t\t: size,\n\t\t\t\t\t\t\"source\"\t\t: source,\n\t\t\t\t\t\t\"rank\"\t\t\t: rank,\n\t\t\t\t\t\t\"popular\"\t\t: popular,\n\t\t\t\t\t\t\"game_type\"\t\t: game_type,\n\t\t\t\t\t\t\"status\"\t\t: status,\n\t\t\t\t\t\t\"url\"\t\t\t: url,\n\t\t\t\t\t\t\"dt\"\t\t\t: dt\n\t\t\t\t\t\t})\n\t\tdb_conn.merge(item)\n\telse:\n\t\tins.url = url\n\tdb_conn.commit()\n\ndef main():\n\tget_data(get_baidu_hot_games)\n\tstore_360_app_rank()\n\tstore_m5qq_app_rank()\n\tstore_m_baidu_app_rank()\n\tget_dangle_app_rank()\n\tstore_xiaomi_web_rank()\n\tstore_vivo_app_rank()\n\tstore_gionee_app_rank()\n\tstore_coolpad_app_rank()\n\tstore_open_play_app_rank()\n\tstore_wandoujia_app_rank()\n\tstore_iqiyi_app_rank()\n\tstore_youku_app_rank()\n\tstore_sogou_app_rank()\n\tget_pp_app_rank()\n\tget_i4_app_rank()\n\tget_kuaiyong_app_rank()\n\tget_itools_app_rank()\n\tget_xyzs_app_rank()\n\tget_91play_app_rank()\n\tstore_360_gamebox_app_rank()\n\tstore_18183_top_app_rank()\n\tstore_9game_web_app_rank()\n\tget_360zhushou_web_rank()\n\tstore_xiaomi_app_rank()\n\nif __name__ == '__main__':\n\tmain()\n"
},
{
"alpha_fraction": 0.5920822024345398,
"alphanum_fraction": 0.6104986071586609,
"avg_line_length": 44.94117736816406,
"blob_id": "f09623600354521b7ef8bfb2f75a92cd6a4d76d7",
"content_id": "a8c24cd93e638a05115a86c0d152631d5401cd6d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8104,
"license_type": "no_license",
"max_line_length": 275,
"num_lines": 170,
"path": "/bi_report/get_h5_summary.py",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python\r\n#-*- coding:utf-8 -*-\r\nimport pandas as pd\r\nimport pandas.io.sql as sql\r\nimport datetime\r\nimport time\r\nimport sys\r\nfrom define import *\r\nfrom get_logger import *\r\nimport traceback\r\n\r\nmylogger = get_logger('h5_report')\r\n\r\ndef get_id_map():\r\n id_map = {}\r\n with open('de_app') as f:\r\n for line in f.readlines():\r\n company_id, appid, server_id = line.rstrip().split('\\t')\r\n if server_id in ['206', '208']:\r\n conn = conn1 if server_id == '206' else conn2\r\n id_map[appid] = (company_id, conn)\r\n return id_map\r\n\r\ndef get_game_type_summary():\r\n d = {'appid':[], 'typename':[]}\r\n for line in open('h5_apps').readlines():\r\n appid, typename = line.rstrip().split('\\t')\r\n d['appid'].append(appid)\r\n d['typename'].append(typename)\r\n df = pd.DataFrame(d)\r\n gb = df.groupby('typename').size()\r\n for k, v in gb.iteritems():\r\n print k, v\r\n\r\ndef get_h5_summary_by_appid(company_id, appid, typename, start_date, end_date, conn):\r\n\r\n \"\"\"\r\n Appid_dc_everyday_h5:TotalPv1/TotalPv(首页跳出率) \r\n childNodeCount/parentNodeCount (活跃k系数)\r\n \"\"\"\r\n df = pd.DataFrame()\r\n _sql = \"select StatiTime, sum(TotalPv) as TotalPv,sum(TotalUv) as TotalUv, sum(UniqIP) as UniqIP, \\\r\n sum(TotalSession) as TotalSession, IF(sum(TotalPv)>0, round(sum(TotalPv1)/sum(TotalPv),4), 0) as run_off_rate, \\\r\n IF(sum(ParentNodeCount)>0, round(sum(ChildNodeCount)/sum(ParentNodeCount), 4), 0) as active_k_rate \\\r\n from dc_%s.%s_dc_everyday_h5 where PlayerType=2 and StatiTime>=%s and StatiTime<=%s \\\r\n group by StatiTime\" % (company_id, appid, start_date, end_date)\r\n df = sql.read_sql(_sql, conn)\r\n df['AppId'] = appid\r\n df['TypeName'] = typename\r\n dt = [datetime.date.fromtimestamp(int(i)) for i in df['StatiTime']]\r\n df['dt'] = dt\r\n del df['StatiTime']\r\n return df\r\n\r\ndef get_duration_by_appid(company_id, appid, typename, start_date, end_date, conn):\r\n\r\n \"\"\"\r\n 对应活跃用户页面\r\n 每次游戏时长分布, 每日累计游戏时长分布\r\n \"\"\"\r\n\r\n df = pd.DataFrame()\r\n _sql = \"select a.StatiTime, b.new_user_num, a.activet_user_num, a.activet_user_num-b.new_user_num as old_user_num, a.TotalSession, a.cost_per_uv, a.cost_per_sess \\\r\n from (select StatiTime, sum(TotalUv) as activet_user_num, sum(TotalSession) as TotalSession,sum(TotalOnlineTime)/sum(TotalUv)/60 as cost_per_uv, \\\r\n sum(TotalOnlineTime)/sum(TotalSession)/60 as cost_per_sess from dc_%s.%s_dc_everyday_h5 where PlayerType=2 and StatiTime>=%s and StatiTime<=%s group by StatiTime) a \\\r\n join (select StatiTime, sum(TotalUv) as new_user_num from dc_%s.%s_dc_everyday_h5 where PlayerType=1 and StatiTime>=%s and StatiTime<=%s group by StatiTime) b on a.StatiTime=b.StatiTime\" % (company_id, appid, start_date, end_date, company_id, appid, start_date, end_date)\r\n df = sql.read_sql(_sql, conn)\r\n df['AppId'] = appid\r\n df['TypeName'] = typename\r\n dt = [datetime.date.fromtimestamp(int(i)) for i in df['StatiTime']]\r\n df['dt'] = dt\r\n del df['StatiTime']\r\n return df\r\n\r\n\r\ndef get_payamount_by_appid(company_id, appid, typename, start_date, end_date, conn):\r\n \r\n \"\"\"\r\n 每日付费率, \r\n Appid_dc_payment_by_day_h5中的PayNum;\r\n 活跃是Appid_dc_everyday_h5中的TotalUv\r\n ARPPU\r\n \"\"\"\r\n\r\n df = pd.DataFrame()\r\n _sql = \"select a.*, b.TotalUv, a.PayNum/b.TotalUv as payment_rate, a.PayAmount/a.PayNum as arppu \\\r\n from (select StatiTime, PayAmount, PayTimes, PayNum from dc_%s.%s_dc_payment_by_day_h5 \\\r\n where StatiTime>=%s and StatiTime<=%s) a join (select StatiTime, sum(TotalUv) as TotalUv \\\r\n from dc_%s.%s_dc_everyday_h5 where PlayerType=2 and StatiTime>=%s and StatiTime<=%s group by StatiTime) b on a.StatiTime=b.StatiTime\" % (company_id, appid, start_date, end_date, company_id, appid, start_date, end_date)\r\n df = sql.read_sql(_sql, conn)\r\n df['AppId'] = appid\r\n df['TypeName'] = typename\r\n dt = [datetime.date.fromtimestamp(int(i)) for i in df['StatiTime']]\r\n df['dt'] = dt\r\n del df['StatiTime']\r\n return df\r\n\r\n\r\ndef get_retain_summary_by_appid(company_id, appid, typename, start_date, end_date, conn):\r\n\r\n \"\"\"\r\n Front_Appid_dc_retain_by_day_h5(新增留存)/Appid_dc_everyday_h5(新增)\r\n \"\"\"\r\n\r\n df = pd.DataFrame()\r\n _sql = \"select a.StatiTime, if(a.TotalUv>0, round(b.RetainedNum_1/a.TotalUv, 4), 0) as retain_rate_1, if(a.TotalUv>0, round(b.RetainedNum_7/a.TotalUv, 4), 0) as retain_rate_7, if(a.TotalUv>0, round(b.RetainedNum_3/a.TotalUv, 4), 0) as retain_rate_3 from \\\r\n (select StatiTime, sum(TotalUv) as TotalUv from dc_%s.%s_dc_everyday_h5 where StatiTime>=%s and StatiTime<=%s and PlayerType=1 group by StatiTime) a join \\\r\n (select StatiTime, sum(RetainedNum_1) as RetainedNum_1, sum(RetainedNum_7) as RetainedNum_7, sum(RetainedNum_3) as RetainedNum_3 from dc_%s.Front_%s_dc_retain_by_day_h5 where StatiTime>=%s \\\r\n and StatiTime<=%s and PlayerType=1 group by StatiTime) b on a.StatiTime=b.StatiTime\" % (company_id, appid, start_date, end_date, company_id, appid, start_date, end_date)\r\n df = sql.read_sql(_sql, conn)\r\n df['TypeName'] = typename\r\n df['AppId'] = appid\r\n dt = [datetime.date.fromtimestamp(int(i)) for i in df['StatiTime']]\r\n df['dt'] = dt\r\n del df['StatiTime']\r\n return df\r\n\r\ndef get_new_user_num_by_appid(company_id, appid, start_date, end_date, conn):\r\n df = pd.DataFrame()\r\n _sql = \"select StatiTime, PlatformType, sum(num) as total_new_user_num\\\r\n from dc_%s.Front_%s_dc_everyday \\\r\n where StatiTime >= %s and StatiTime <= %s and PlayerType=1 \\\r\n and GameRegionID in (select Seqno from dc_%s.dc_custom_id where AppID = \\'%s\\' and type = 2 and vkey = '_ALL_GS') \\\r\n group by StatiTime, PlatformType;\"% (company_id, appid, start_date, end_date, company_id, appid)\r\n df = sql.read_sql(_sql, conn)\r\n df['appid'] = appid\r\n return df\r\n\r\n\r\ndef main():\r\n df = pd.DataFrame()\r\n start_date = '2015-07-01'\r\n end_date = '2015-09-30'\r\n start_date = int(time.mktime(time.strptime('%s 00:00:00' % start_date, '%Y-%m-%d %H:%M:%S')))\r\n end_date = int(time.mktime(time.strptime('%s 00:00:00' % end_date, '%Y-%m-%d %H:%M:%S')))\r\n id_map = get_id_map()\r\n valid_apps = set([j.rstrip() for j in open('valid_apps').readlines()])\r\n with open('h5_apps') as f:\r\n for line in f.readlines()[:]:\r\n appid, typename = line.rstrip().split('\\t')\r\n #appid = \"5CB577BE32F5C89EF50C84269C30AA07\"\r\n if appid in id_map and appid in valid_apps:\r\n company_id, conn = id_map.get(appid)\r\n mylogger.info(\"%s\\t%s\\t%s\" % (appid, company_id, conn))\r\n for dt in range(start_date, end_date, 86400 * 30):\r\n try:\r\n dt2 = end_date if dt+86400*29 > end_date else dt+86400*29\r\n #retain_df = get_retain_summary_by_appid(company_id, appid, typename, dt, dt2, conn)\r\n #summary_df = get_h5_summary_by_appid(company_id, appid, typename, dt, dt2, conn)\r\n #_df = get_duration_by_appid(company_id, appid, typename, dt, dt2, conn)\r\n _df = get_payamount_by_appid(company_id, appid, typename, dt, dt2, conn)\r\n df = pd.concat([df, _df])\r\n time.sleep(1)\r\n except Exception,e:\r\n mylogger.error(traceback.format_exc())\r\n df.to_csv(\"h5_payamount_day\")\r\n #company_id, conn = id_map.get(appid)\r\n #retain_df = get_retain_summary_by_appid(company_id, appid, start_date, end_date, conn)\r\n #print retain_df\r\n #print get_duration_by_appid(company_id, appid, start_date, end_date, conn)\r\n #print get_payamount_by_appid(company_id, appid, start_date, end_date, conn)\r\n \r\ndef func():\r\n payamount_df = pd.read_csv(\"h5_payamount_day\")\r\n print len(payamount_df)\r\n\r\n\r\nif __name__==\"__main__\":\r\n #main()\r\n func()\r\n\r\n"
},
{
"alpha_fraction": 0.5589128732681274,
"alphanum_fraction": 0.5787211656570435,
"avg_line_length": 35.279537200927734,
"blob_id": "2009c10ccf54609011586b1d6977f4e83cb1fee2",
"content_id": "b175a04a14655576bad0433ebe1c0fdb38939587",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 59848,
"license_type": "no_license",
"max_line_length": 298,
"num_lines": 1642,
"path": "/spider/get_kc_list.py",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#encoding=utf-8\n\nimport requests\nimport json\nimport re\nfrom bs4 import BeautifulSoup\nfrom time import sleep\nimport traceback\nfrom config import *\nimport random\nimport datetime\nimport xmltodict\n\ndb_conn = new_session()\ns = requests.session()\nmylogger = get_logger('kc')\n\nsource_map = {\n\t\t\t\"9game\": 0,\n\t\t\t\"18183\": 2,\n\t\t\t\"u360\": 1,\n\t\t\t\"appicsh\": 3,#应用宝app\n\t\t\t\"360zhushou\": 4,#360助手app\n\t\t\t\"xiaomi_new\": 5,#小米app 最新\n\t\t\t\"xiaomi_rpg\": 6,#小米app rpg\n\t\t\t\"open_play\": 7,#爱游戏app\n\t\t\t\"vivo\": 8,\n\t\t\t\"coolpad\": 9,\n\t\t\t\"gionee\": 10,\n\t\t\t\"lenovo\": 11,\n\t\t\t\"iqiyi\": 12,\n\t\t\t\"youku\": 13,\n\t\t\t\"sogou\": 14,\n\t\t\t\"dangle\": 15,\n\t\t\t\"i4\": 16,\n\t\t\t\"muzhiwan\": 17,\n\t\t\t\"huawei\": 18,\n\t\t\t\"kuaiyong\": 19,\n\t\t\t\"itools\": 20,\n\t\t\t\"anzhi\": 21,\n\t\t\t\"360zhushou_web\": 22,#360助手web\n\t\t\t\"wandoujia\": 23,\n\t\t\t\"pp\": 24,\n\t\t\t\"meizu\": 25,\n\t\t\t\"xyzs\": 26,\n\t\t\t\"91play\": 27,#酷玩汇\n\t\t\t\"360_gamebox\": 28,\n\t\t\t\"m_baidu_app\": 29,#百度手机助手\n\t\t\t\t}\n\nclass T:\n\t\n\tdef __init__(self, status_code):\n\t\tself.status_code = status_code\n\ndef get_9game_today_kc():\n\tURL = u\"http://www.9game.cn/kc/\"\n\tmylogger.info(\"9game gogo\")\n\ttry:\n\t\tr = s.get(URL, timeout=10)\n\t\tsoup = BeautifulSoup(r.text)\n\t\tpublish_date = unicode(datetime.date.today())\n\t\ttime \t\t= u\"\"\n\t\ttitle \t\t= u\"\"\n\t\ttitle2 \t\t= u\"\"\n\t\timg \t\t= u\"\"\n\t\turl \t\t= u\"\"\n\t\tdevice \t\t= u\"\"\n\t\tpublish_status \t\t= u\"\"\n\t\tgame_type \t= u\"\"\n\t\tpopular \t= u\"\"\n\t\ttoday_list = soup.find(\"ul\", class_=\"today-server-list\").find_all(\"li\")\n\t\t#today_list = soup.find(\"ul\", class_=\"today-server-list\").find_all(\"li\", class_='timeli')\n\t\tif today_list is not None:\n\t\t\tmylogger.info(\"kc games : %s\" %len(today_list))\n\t\t\tfor t in today_list:\n\t\t\t\ttry:\n\t\t\t\t\ttime_div = t.find(\"div\", class_=\"time\")\n\t\t\t\t\ttime = time_div.text if time_div is not None else time\n\t\t\t\t\t#print '****', time\n\t\t\t\t\tpic_div = t.find(\"div\", class_=\"pic\")\n\t\t\t\t\tif pic_div is not None:\n\t\t\t\t\t\timg = pic_div.find(\"img\").get(\"src\")\n\t\t\t\t\t\t#img = pic_div.find(\"a\").find(\"img\").get(\"src\")\n\t\t\t\t\trt = t.find(\"div\", class_=\"right-text\")\n\t\t\t\t\tif rt is not None:\n\t\t\t\t\t\ttit_p = rt.find(\"p\", class_=\"tit\")\n\t\t\t\t\t\tif tit_p is not None:\n\t\t\t\t\t\t\ttitle \t= tit_p.find(\"a\").get(\"title\")\n\t\t\t\t\t\t\ttitle2 \t= tit_p.find(\"a\").text\n\t\t\t\t\t\t\turl \t= tit_p.find(\"a\").get(\"href\")\n\t\t\t\t\t\t\tdevice \t= tit_p.find(\"span\").get(\"class\")\n\t\t\t\t\t\t\tpopular \t= tit_p.find(\"span\", class_=\"type-con\").find(\"span\").text\n\t\t\t\t\t\ttype_div = rt.find(\"div\", class_=\"type\").find_all(\"span\", class_=\"type-con\")\n\t\t\t\t\t\tif type_div is not None:\n\t\t\t\t\t\t\ttime \t\t= type_div[0].text\n\t\t\t\t\t\t\tpublish_status \t\t= type_div[0].find(\"span\").text\n\t\t\t\t\t\t\t#game_type \t= type_div[1].find('td')\n\t\t\t\t\t\t\t#print type_div\n\t\t\t\t\t\t\t#print re.split(u\":| \", time)[1], status, game_type\n\t\t\t\t\tif title and url:\n\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.source==source_map.get('9game')).filter(KC_LIST.url==url).filter(KC_LIST.publish_date==publish_date).first()\n\t\t\t\t\t\t#ins = db_conn.query(KC_LIST).filter(KC_LIST.source==source_map.get('9game')).filter(KC_LIST.title==title).filter(KC_LIST.publish_date==publish_date).first()\n\t\t\t\t\t\tif not ins:\n\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\"time\"\t\t: re.split(u\":| \", time)[1],\n\t\t\t\t\t\t\t\t\"title\" \t\t: title,\n\t\t\t\t\t\t\t\t\"title2\" \t\t: title2, \n\t\t\t\t\t\t\t\t\"img\" \t\t: img, \n\t\t\t\t\t\t\t\t\"url\" \t\t: url, \t\t\n\t\t\t\t\t\t\t\t\"device\" \t\t: u\",\".join(device), \t\t\n\t\t\t\t\t\t\t\t\"publish_status\" \t\t: publish_status, \t\t\n\t\t\t\t\t\t\t\t\"game_type\" \t: game_type, \t\n\t\t\t\t\t\t\t\t\"popular\" \t: popular,\n\t\t\t\t\t\t\t\t\"source\" \t: source_map.get('9game'),\n\t\t\t\t\t\t\t\t\"publish_date\" \t: unicode(datetime.date.today()) \t\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\texcept Exception,e:\n\t\t\t\t\tdb_conn.rollback()\n\t\t\t\t\tmylogger.error(\"--------%s\" % (traceback.format_exc()))\n\t\telse:\n\t\t\tmylogger.info(\"no kc games....\")\n\texcept Exception,e:\n\t\tmylogger.error(\"====>\\t%s\" % (traceback.format_exc()))\n\tdb_conn.commit()\n\n\n\ndef get_18183_kc():\n\tURL = \"http://xin.18183.com/ceshi/\"\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\t\tr = response.text.encode('ISO-8859-1').decode(requests.utils.get_encodings_from_content(response.text)[0])\n\t\tsoup = BeautifulSoup(r)\n\t\tpublish_dates = soup.find(\"ul\", class_=\"tab_menu\").find_all(\"li\")\n\t\ttabs = soup.find_all(\"div\", class_=\"tab_main\")\n\t\tcount = 0\n\t\tfor j in xrange(len(tabs)):\n\t\t\tif publish_dates[j].find(\"a\").text == u\"今日\": \n\t\t\t\tpublish_date = u\"2015-%s\" % publish_dates[j].find(\"a\").text if publish_dates[j].find(\"a\").text!=u\"今日\" else datetime.date.today().strftime(\"%Y-%m-%d\") \n\t\t\t\ttab = tabs[j]\n\t\t\t\tkc_div = tab.find_all(\"div\")\n\t\t\t\tfor i in xrange(0, len(kc_div), 2):\n\t\t\t\t\ttype_div = kc_div[i:i+2][0]\n\t\t\t\t\tif type_div.text == u\"开测游戏\":\n\t\t\t\t\t\tcontent = kc_div[i:i+2][1]\n\t\t\t\t\t\tfor t in content.find(\"ul\").find_all(\"li\"):\n\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\ttitle = t.find(\"div\", class_=\"tait\").find(\"h4\").text\n\t\t\t\t\t\t\turl = t.find(\"div\", class_=\"down\").find(\"a\").get('href')\n\t\t\t\t\t\t\timg = t.find(\"img\").get(\"src\")\n\t\t\t\t\t\t\ttime = t.find(\"div\", class_=\"pt\").find(\"div\", class_=\"time fl\").find(\"i\").text\n\t\t\t\t\t\t\tdevices = [i.get(\"class\")[0] for i in t.find(\"div\", class_=\"pt\").find(\"div\", class_=\"xy fl\").find_all(\"span\") if i.get(\"class\") is not None]\n\t\t\t\t\t\t\tpublish_status = t.find(\"div\", class_=\"pt m6\").find(\"code\").text\n\t\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.url==url).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('18183')).first()\n\t\t\t\t\t\t\t#ins = db_conn.query(KC_LIST).filter(KC_LIST.title==title).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.status==status).filter(KC_LIST.source==source_map.get('18183')).first()\n\t\t\t\t\t\t\tif not ins:\n\t\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\"title\"\t\t: \ttitle,\n\t\t\t\t\t\t\t\t\t\t\"url\"\t\t: \turl,\n\t\t\t\t\t\t\t\t\t\t\"img\" \t\t:\timg,\n\t\t\t\t\t\t\t\t\t\t\"time\" \t\t:\ttime,\n\t\t\t\t\t\t\t\t\t\t\"device\" \t:\t\",\".join(devices),\n\t\t\t\t\t\t\t\t\t\t\"publish_status\"\t:\tpublish_status,\n\t\t\t\t\t\t\t\t\t\t\"publish_date\"\t:\tpublish_date,\n\t\t\t\t\t\t\t\t\t\t\"source\"\t:\tsource_map.get('18183')\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\tdb_conn.merge(item)\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\tdb_conn.commit()\n\tmylogger.info(\"get %s records from 18183 kc\" % count)\n\ndef get_360_kc():\n\tcount = 0\n\tURL = \"http://u.360.cn/xin/ceshi/\"\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\t\tr = response.text.encode('ISO-8859-1').decode(requests.utils.get_encodings_from_content(response.text)[0])\n\t\tsoup = BeautifulSoup(r)\n\t\tc = soup.find_all(\"div\", class_=\"content\")\n\t\tfor content in c:\n\t\t\ttable = content.find(\"table\", class_=\"tablists tablists_green\")\n\t\t\tif table is not None:\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\tpublish_date = u\"\"\n\t\t\t\tdate_h3 = content.find(\"h3\")\n\t\t\t\tif date_h3 is not None:\n\t\t\t\t\tpublish_date = date_h3.text[5:-1]\n\t\t\t\t\tpublish_date = re.sub(u\"月\", u\"-\", publish_date)\n\t\t\t\t\tpublish_date = re.sub(u\"日\", u\"\", publish_date)\n\t\t\t\t\tpublish_date = u\"2015-%s\" % publish_date\n\t\t\t\ttablists = content.find(\"table\", class_=\"tablists\").find_all(\"tr\")\n\t\t\t\tif tablists is not None:\n\t\t\t\t\tfor tr in tablists[1:]:\n\t\t\t\t\t\ttime \t= u\"\"\n\t\t\t\t\t\ttitle \t= u\"\"\n\t\t\t\t\t\timg \t= u\"\"\n\t\t\t\t\t\tpublish_status\t= u\"\"\n\t\t\t\t\t\tgame_type = u\"\"\n\t\t\t\t\t\ttds = tr.find_all(\"td\")\n\t\t\t\t\t\tif tds is not None:\n\t\t\t\t\t\t\ttitle = re.sub(u\"\\xa0\", u\"\", tds[0].text)\n\t\t\t\t\t\t\timg = u\"\" if tds[0].find(\"img\") is None else tds[0].find(\"img\").get(\"src\")\n\t\t\t\t\t\t\turl = u\"\" if tds[0].find(\"a\") is None else tds[0].find(\"a\").get(\"href\")\n\t\t\t\t\t\t\tpublish_status = tds[1].text\n\t\t\t\t\t\t\tgame_type = tds[3].text\n\t\t\t\t\t\t\tif url and publish_date:\n\t\t\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.url==url).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('u360')).first()\n\t\t\t\t\t\t\t\t#ins = db_conn.query(KC_LIST).filter(KC_LIST.title==title).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.status==status).filter(KC_LIST.source==source_map.get('u360')).first()\n\t\t\t\t\t\t\t\tif not ins:\n\t\t\t\t\t\t\t\t\tcount += 1\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\t\t\"publish_date\": publish_date,\n\t\t\t\t\t\t\t\t\t\t\t\t\"time\": time,\n\t\t\t\t\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\t\t\t\t\"url\": url,\n\t\t\t\t\t\t\t\t\t\t\t\t\"publish_status\": publish_status,\n\t\t\t\t\t\t\t\t\t\t\t\t\"game_type\": game_type,\n\t\t\t\t\t\t\t\t\t\t\t\t\"img\": img,\n\t\t\t\t\t\t\t\t\t\t\t\t\"source\": source_map.get('u360')\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\tdb_conn.merge(item)\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\tmylogger.info(\"get %s records from 360 kc\" % count)\n\tdb_conn.commit()\t\t\t\t\n\ndef get_appicsh_kc():\n\tcount = 0\n\t#url = \"http://m5.qq.com/app/applist.htm?listType=18&pageSize=150\" #pc url\n\turl = \"http://appicsh.qq.com/cgi-bin/appstage/FirstPublishTab?type=3&index=0&pageSize=20\"\n\ttry:\n\t\tr = requests.get(url, timeout=10)\n\t\tif r.status_code == 200:\n\t\t\td = r.json()\n\t\t\tif d['msg'] == u'success':\n\t\t\t\tnew_games_list = d['new_games']['list']\n\t\t\t\t#new_games_list = d['obj']['appList']\n\t\t\t\tfor game in new_games_list:\n\t\t\t\t\ttitle = game.get('name', u\"\")\n\t\t\t\t\tgame_type = game.get('categor', u\"\")\n\t\t\t\t\timg = game.get('icon', u\"\")\n\t\t\t\t\tpublishtime = game.get('publishtime', u\"\")\n\t\t\t\t\tpkg_name = game.get('pkgname', u'')\n\t\t\t\t\turl = u\"http://m5.qq.com/app/getappdetail.htm?pkgName=%s&sceneId=0\" % pkg_name if pkg_name else u''\n\t\t\t\t\tpublish_date = unicode(datetime.date.fromtimestamp(publishtime)) if publishtime else u\"\"\n\t\t\t\t\tif pkg_name and publish_date:\n\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.pkg_name==pkg_name).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('appicsh')).first()\n\t\t\t\t\t\t#ins = db_conn.query(KC_LIST).filter(KC_LIST.title==title).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('appicsh')).first()\n\t\t\t\t\t\tif ins is None:\n\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\t\t\"game_type\": game_type,\n\t\t\t\t\t\t\t\t\t\t\"publish_date\": publish_date,\n\t\t\t\t\t\t\t\t\t\t\"img\": img,\n\t\t\t\t\t\t\t\t\t\t\"source\": source_map.get('appicsh'),\n\t\t\t\t\t\t\t\t\t\t\"url\": url,\n\t\t\t\t\t\t\t\t\t\t\"pkg_name\": pkg_name,\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tdb_conn.merge(item)\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (url, traceback.format_exc()))\n\tmylogger.info(\"get %s records from appicsh\" % count)\n\tdb_conn.commit()\n\ndef get_360zhushou_kc():\n\tcount = 0\n\tURL = \"http://openbox.mobilem.360.cn/gamestart/list?type=2\"\n\ttry:\n\t\tr = s.get(URL)\n\t\tif r.status_code == 200:\n\t\t\tsoup = BeautifulSoup(r.text)\n\t\t\titem_list = soup.find_all(\"div\", class_=\"app-item-list\")[0]\n\t\t\tif item_list is not None:\n\t\t\t\tapp_list = item_list.find_all('div', class_='app-main app-item')\n\t\t\t\t#print logo_list\n\t\t\t\t#app_list = item_list.find_all('div', class_='app-detail')\n\t\t\t\tfor app in app_list:\n\t\t\t\t\tlogo = app.find('div', class_='app-logo')\n\t\t\t\t\titem = app.find('div', class_='app-detail')\n\t\t\t\t\ttitle = u\"\"\n\t\t\t\t\tgame_type = u\"\"\n\t\t\t\t\tsize = u\"\"\n\t\t\t\t\tpublish_date = u\"\"\n\t\t\t\t\tpublish_status = u\"\"\n\t\t\t\t\ttime = u\"\"\n\t\t\t\t\timg = u\"\"\n\t\t\t\t\tif logo is not None:\n\t\t\t\t\t\tif logo.find('img') is not None:\n\t\t\t\t\t\t\timg = logo.find('img').get('src')\n\t\t\t\t\ttitle_h3 = item.find('h3')\n\t\t\t\t\tif title is not None:\n\t\t\t\t\t\ttitle = title_h3.text\n\t\t\t\t\t\tmeta = item.find('div', class_=\"app-meta text-over\")\n\t\t\t\t\t\tif meta is not None:\n\t\t\t\t\t\t\tm2 = re.search(u'[\\u4e00-\\u9fa5\\s]+', meta.text)\n\t\t\t\t\t\t\tgame_type = m2.group() if m2 is not None else u''\n\t\t\t\t\t\tmeta2 = item.find('div', class_=\"app-meta2 text-over\")\n\t\t\t\t\t\tif meta2 is not None:\n\t\t\t\t\t\t\tspans = meta2.find_all('span')\n\t\t\t\t\t\t\tif len(spans) == 2:\n\t\t\t\t\t\t\t\tdt, publish_status = [i.text for i in spans]\n\t\t\t\t\t\t\t\tpublish_date, time = dt.split(u' ')\n\t\t\t\t\t\t#print title, game_type, '****', publish_date, img\n\t\t\t\t\tpkg_id = app.get('data-sid', u'')\n\t\t\t\t\tpkg_name = app.get('data-pname', u'')\t\n\t\t\t\t\tif pkg_name and publish_date:\n\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.pkg_name==pkg_name).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('360zhushou')).first()\n\t\t\t\t\t\t#ins = db_conn.query(KC_LIST).filter(KC_LIST.title==title).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('360zhushou')).first()\n\t\t\t\t\t\tif ins is None:\n\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\t\t\"title\" : title,\n\t\t\t\t\t\t\t\t\t\t\t\t\"game_type\" : game_type,\n\t\t\t\t\t\t\t\t\t\t\t\t\"publish_date\" : publish_date,\n\t\t\t\t\t\t\t\t\t\t\t\t\"time\" : time,\n\t\t\t\t\t\t\t\t\t\t\t\t\"img\" : img,\n\t\t\t\t\t\t\t\t\t\t\t\t\"title2\" : pkg_name,\n\t\t\t\t\t\t\t\t\t\t\t\t\"pkg_name\" : pkg_name,\n\t\t\t\t\t\t\t\t\t\t\t\t\"game_id\" : pkg_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\"publish_status\" : publish_status,\n\t\t\t\t\t\t\t\t\t\t\t\t\"source\" : source_map.get('360zhushou'),\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tins.game_id = pkg_id\n\t\t\t\t\t\t\tins.pkg_name = pkg_name\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\tmylogger.info(\"get %s records from 360 zhushou app\" % count)\n\tdb_conn.commit()\n\ndef get_xiaomi_new_kc(page):\n\tcount = 0\n\turl = \"http://app.migc.xiaomi.com/cms/interface/v5/subjectgamelist1.php?pageSize=20&page=%s&subId=138\" % page\n\ttry:\n\t\tr = requests.get(url)\n\t\tif r.status_code == 200:\n\t\t\td = r.json()\n\t\t\tif d['errCode'] == 200:\n\t\t\t\tnew_games_list = d.get('gameList', [])\n\t\t\t\tfor g in new_games_list:\n\t\t\t\t\ttitle = g.get('displayName', u'')\n\t\t\t\t\timg = g.get('icon', u'')\n\t\t\t\t\tpopular = g.get('downloadCount', u'')\n\t\t\t\t\tgame_type = g.get('className', u'')\n\t\t\t\t\tpubTime = g.get('pubTime', u'')\n\t\t\t\t\tpublish_date = u\"\"\n\t\t\t\t\tpkg_name = g.get('packageName', u'')\n\t\t\t\t\tif pubTime:\n\t\t\t\t\t\tt = unicode(pubTime)[:10]\n\t\t\t\t\t\tpublish_date = unicode(datetime.date.fromtimestamp(int(t)))\n\t\t\t\t\tif pkg_name and publish_date :\n\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.pkg_name==pkg_name).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('xiaomi_new')).first()\n\t\t\t\t\t\tif ins is None:\n\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\t\t\"game_type\": game_type,\n\t\t\t\t\t\t\t\t\t\t\"publish_date\": publish_date,\n\t\t\t\t\t\t\t\t\t\t\"img\": img,\n\t\t\t\t\t\t\t\t\t\t\"game_id\": g.get('gameId', u''),\n\t\t\t\t\t\t\t\t\t\t\"pkg_name\": pkg_name,\n\t\t\t\t\t\t\t\t\t\t\"popular\": popular,\n\t\t\t\t\t\t\t\t\t\t\"source\": source_map.get('xiaomi_new')\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tins.game_id = g.get('gameId', u'')\n\t\t\t\t\t\t\tins.pkg_name = g.get('packageName', u'')\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (url, traceback.format_exc()))\n\tmylogger.info(\"get %s records from xiaomi_new\" % count)\n\tdb_conn.commit()\n\ndef get_xiaomi_rpg_kc(page):\n\tcount = 0\n\turl = \"http://app.migc.xiaomi.com/cms/interface/v5/subjectgamelist1.php?subId=203&pageSize=20&page=%s\" % page\n\ttry:\n\t\tr = requests.get(url)\n\t\tif r.status_code == 200:\n\t\t\td = r.json()\n\t\t\tif d['errCode'] == 200:\n\t\t\t\tnew_games_list = d.get('gameList', [])\n\t\t\t\tfor g in new_games_list:\n\t\t\t\t\ttitle = g.get('displayName', u'')\n\t\t\t\t\timg = g.get('icon', u'')\n\t\t\t\t\tpopular = g.get('downloadCount', u'')\n\t\t\t\t\tgame_type = g.get('className', u'')\n\t\t\t\t\tsummary = g.get('summary', u'')\n\t\t\t\t\tpubTime = g.get('pubTime', u'')\n\t\t\t\t\tpublish_status = u\"\"\n\t\t\t\t\tpublish_date = u\"\"\n\t\t\t\t\tpkg_name = g.get('packageName', u'')\n\t\t\t\t\tif pubTime:\n\t\t\t\t\t\tt = unicode(pubTime)[:10]\n\t\t\t\t\t\tpublish_date = unicode(datetime.date.fromtimestamp(int(t)))\n\t\t\t\t\tif summary:\n\t\t\t\t\t\tdt, publish_status = summary.split(u'|')\n\t\t\t\t\tif pkg_name and publish_date :\n\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.pkg_name==pkg_name).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('xiaomi_rpg')).first()\n\t\t\t\t\t\tif ins is None:\n\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\t\t\"game_type\": game_type,\n\t\t\t\t\t\t\t\t\t\t\"publish_date\": publish_date,\n\t\t\t\t\t\t\t\t\t\t\"game_id\": g.get('gameId', u''),\n\t\t\t\t\t\t\t\t\t\t\"pkg_name\": pkg_name,\n\t\t\t\t\t\t\t\t\t\t\"img\": img,\n\t\t\t\t\t\t\t\t\t\t\"popular\": popular,\n\t\t\t\t\t\t\t\t\t\t\"publish_status\": publish_status,\n\t\t\t\t\t\t\t\t\t\t\"source\": source_map.get('xiaomi_rpg')\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tins.game_id = g.get('gameId', u'')\n\t\t\t\t\t\t\tins.pkg_name = g.get('packageName', u'')\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (url, traceback.format_exc()))\n\tmylogger.info(\"get %s records from xiaomi_rpg\" % count)\n\tdb_conn.commit()\n\ndef get_open_play_kc():\n\tcount = 0\n\turl = \"http://open.play.cn/api/v2/mobile/channel/content.json?channel_id=702&terminal_id=18166¤t_page=0&rows_of_page=20\"\n\ttry:\n\t\tr = requests.get(url)\n\t\tif r.status_code == 200:\n\t\t\td = r.json()\n\t\t\tif d['code'] == 0:\n\t\t\t\tnew_games_list = d['ext']['main']['content']['game_list']\n\t\t\t\tfor g in new_games_list:\n\t\t\t\t\ttitle = g.get('game_name', u'')\n\t\t\t\t\timg = g.get('game_icon', u'')\n\t\t\t\t\tpopular = g.get('game_download_count', u'')\n\t\t\t\t\tgame_type = g.get('class_name', u'')\n\t\t\t\t\tpublish_date = u\"\"\n\t\t\t\t\tgame_id = g.get('game_id', u'')\n\t\t\t\t\tif game_id:\n\t\t\t\t\t\tonline_time = g.get('last_online_time', u'')\n\t\t\t\t\t\tif online_time:\n\t\t\t\t\t\t\tdt, time = online_time.split(u' ')\n\t\t\t\t\t\t\tpublish_date = dt\n\t\t\t\t\t\tif publish_date:\n\t\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.game_id==game_id).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('open_play')).first()\n\t\t\t\t\t\t\tif ins is None:\n\t\t\t\t\t\t\t\tcount+=1\n\t\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\t\t\t\"title2\": game_id,\n\t\t\t\t\t\t\t\t\t\t\t\"game_id\": game_id,\n\t\t\t\t\t\t\t\t\t\t\t\"game_type\": game_type,\n\t\t\t\t\t\t\t\t\t\t\t\"publish_date\": publish_date,\n\t\t\t\t\t\t\t\t\t\t\t\"img\": img,\n\t\t\t\t\t\t\t\t\t\t\t\"popular\": popular,\n\t\t\t\t\t\t\t\t\t\t\t\"source\": source_map.get('open_play')\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tins.game_id = game_id\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (url, traceback.format_exc()))\n\tmylogger.info(\"get %s records from open_play\" % count)\n\tdb_conn.commit()\n\ndef get_vivo_kc(page):\n\tcount = 0\n\t#url = \"http://gamecenter.vivo.com.cn/clientRequest/topicGame?id=214&page_index=1\"\n\turl = \"http://main.gamecenter.vivo.com.cn/clientRequest/startingGame?page_index=%s\" % page\n\ttry:\n\t\tr = requests.get(url)\n\t\tif r.status_code == 200:\n\t\t\td = r.json()\n\t\t\tfor ret in d['msg']:\n\t\t\t\ttitle = ret.get('name', u'')\n\t\t\t\tgame_type = ret.get('type', u'')\n\t\t\t\tpopular = ret.get('download', u'')\n\t\t\t\timg = ret.get('icon', u'')\n\t\t\t\tpkg_name = ret.get('pkgName', u'')\n\t\t\t\tcomment = ret.get('comment', u'')\n\t\t\t\tdt = ret.get('categoryType', u'')\n\t\t\t\tm = re.search(u'(\\d+)月(\\d+)日', dt)\n\t\t\t\t_date = u''\n\t\t\t\tgame_id = ret.get('id', u'')\n\t\t\t\ttry:\n\t\t\t\t\t_date = u\"%s-%s-%s\" % (datetime.date.today().year, m.group(1), m.group(2))\n\t\t\t\texcept Exception, e:\n\t\t\t\t\tmylogger.error(\"%s\" % (traceback.format_exc()))\n\t\t\t\tif _date and game_id:\n\t\t\t\t\tdetail_url = \"http://info.gamecenter.vivo.com.cn/clientRequest/gameDetail?id=%s&adrVerName=4.4.4&appVersion=37\" % game_id\n\t\t\t\t\tpublish_date = datetime.datetime.strptime(_date, '%Y-%m-%d')\n\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.game_id==game_id).filter(KC_LIST.publish_date==unicode(publish_date.date())).filter(KC_LIST.source==source_map.get('vivo')).first()\n\t\t\t\t\tif ins is None:\n\t\t\t\t\t\tcount+=1\n\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\"game_id\": game_id,\n\t\t\t\t\t\t\t\t\"game_type\": game_type,\n\t\t\t\t\t\t\t\t\"publish_date\": unicode(publish_date.date()),\n\t\t\t\t\t\t\t\t\"img\": img,\n\t\t\t\t\t\t\t\t\"url\": detail_url,\n\t\t\t\t\t\t\t\t\"popular\": popular,\n\t\t\t\t\t\t\t\t\"source\": source_map.get('vivo')\n\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\telse:\n\t\t\t\t\t\tins.url = detail_url\n\t\t\t\t\t\tins.game_id = game_id\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (url, traceback.format_exc()))\n\tmylogger.info(\"get %s records from vivo\" % count)\n\tdb_conn.commit()\n\t\t\t\n\ndef get_coolpad_kc():\n\tcount = 0\n\turl = \"http://gamecenter.coolyun.com/gameAPI/API/getResList?key=0\"\n\traw_data = \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<request username=\"\" cloudId=\"\" openId=\"\" sn=\"865931027730878\" platform=\"1\" platver=\"19\" density=\"480\" screensize=\"1080*1920\" language=\"zh\" mobiletype=\"MI4LTE\" version=\"4\" seq=\"0\" appversion=\"3120\" currentnet=\"WIFI\" channelid=\"coolpad\" networkoperator=\"46001\" simserianumber=\"89860115851040101064\">\n <rankorder>0</rankorder>\n <syncflag>0</syncflag>\n <start>1</start>\n <categoryid>1</categoryid>\n <iscoolpad>0</iscoolpad>\n <level>0</level>\n <querytype>3</querytype>\n <max>10</max>\n</request>\n\"\"\"\n\ttry:\n\t\tr = requests.post(url, data=raw_data, headers={'Content-Type': 'application/xml'}, timeout=10)\n\t\tif r.status_code == 200:\n\t\t\tt = re.sub(u'\\r|\\n', '', r.text)\n\t\t\tdoc = xmltodict.parse(t)\n\t\t\tfor k in doc['response']['reslist']['res']:\n\t\t\t\ttitle = k.get('@name', u'')\n\t\t\t\tgame_type = k.get('levelname', u'')\n\t\t\t\tpkg_name = k.get('package_name', u'')\n\t\t\t\tscore = k.get('score', u'')\n\t\t\t\timg = k.get('icon', u'')\n\t\t\t\tpopular = k.get('downloadtimes', u'')\n\t\t\t\tresid = k.get('@rid', u'')\n\t\t\t\tif resid:\n\t\t\t\t\tpublish_date = get_coolpad_pubtime_by_id(resid)\n\t\t\t\t\tif publish_date:\n\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.game_id==resid).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('coolpad')).first()\n\t\t\t\t\t\tif ins is None:\n\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\t\t\"game_id\": resid,\n\t\t\t\t\t\t\t\t\t\t\"title2\": resid,\n\t\t\t\t\t\t\t\t\t\t\"game_type\": game_type,\n\t\t\t\t\t\t\t\t\t\t\"publish_date\": publish_date,\n\t\t\t\t\t\t\t\t\t\t\"img\": img,\n\t\t\t\t\t\t\t\t\t\t\"popular\": popular,\n\t\t\t\t\t\t\t\t\t\t\"source\": source_map.get('coolpad')\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tins.game_id = resid\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (url, traceback.format_exc()))\n\tmylogger.info(\"get %s records from coolpad\" % count)\n\tdb_conn.commit()\n\n\ndef get_coolpad_pubtime_by_id(resid):\n\turl = \"http://gamecenter.coolyun.com/gameAPI/API/getDetailResInfo?key=0\"\n\traw_data = \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<request username=\"\" cloudId=\"\" openId=\"\" sn=\"865931027730878\" platform=\"1\" platver=\"19\" density=\"480\" screensize=\"1080*1920\" language=\"zh\" mobiletype=\"MI4LTE\" version=\"4\" seq=\"0\" appversion=\"3350\" currentnet=\"WIFI\" channelid=\"coolpad\" networkoperator=\"46001\" simserianumber=\"89860115851040101064\">\n <resid>%s</resid>\n</request>\"\"\" % resid\n\ttry:\n\t\tr = requests.post(url, data=raw_data, headers={'Content-Type': 'application/xml'})\n\t\tif r.status_code == 200:\n\t\t\tt = re.sub(u'\\r|\\n', '', r.text)\n\t\t\tdoc = xmltodict.parse(t)\n\t\t\td = doc['response']['reslist']['res']\n\t\t\tpubtime = d.get('pubtime', u'')\n\t\t\tif pubtime is not None:\n\t\t\t\tm = re.search(u'\\d+-\\d+-\\d+', pubtime)\n\t\t\t\tif m is not None:\n\t\t\t\t\tdt = datetime.datetime.strptime(m.group(), '%Y-%m-%d')\n\t\t\t\t\treturn unicode(dt.date())\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (url, traceback.format_exc()))\n\treturn u''\n\ndef get_gionee_kc(page):\n\tcount = 0\n\turl = \"http://game.gionee.com/Api/Local_Rank/clientIndex?&page=%s\" % page\n\ttry:\n\t\tr = requests.get(url, timeout=10)\n\t\tif r.status_code == 200:\n\t\t\td = r.json()\n\t\t\tfor ret in d['data']['list']:\n\t\t\t\ttitle = ret.get('name', u'')\n\t\t\t\timg = ret.get('img', u'')\n\t\t\t\tscore = ret.get('score', u'')\n\t\t\t\tgame_id = ret.get('gameid', u'')\n\t\t\t\tgame_type = ret.get('category', u'')\n\t\t\t\tdt = ret.get('date', u'')\n\t\t\t\tm = re.search(u'(\\d+)月(\\d+)日', dt)\n\t\t\t\tpublish_date = u''\n\t\t\t\ttry:\n\t\t\t\t\tpublish_date = u\"%s-%s-%s\" % (datetime.date.today().year, m.group(1), m.group(2))\n\t\t\t\texcept Exception, e:\n\t\t\t\t\tmylogger.error(\"### %s ###\\t%s\" % (dt.encode('utf-8'), traceback.format_exc()))\n\t\t\t\tif publish_date and game_id:\n\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.game_id==game_id).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('gionee')).first()\n\t\t\t\t\tif ins is None:\n\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\t\t\"title2\": game_id,\n\t\t\t\t\t\t\t\t\t\t\"game_id\": game_id,\n\t\t\t\t\t\t\t\t\t\t\"game_type\": game_type,\n\t\t\t\t\t\t\t\t\t\t\"publish_date\": publish_date,\n\t\t\t\t\t\t\t\t\t\t\"img\": img,\n\t\t\t\t\t\t\t\t\t\t\"source\": source_map.get('gionee')\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (url, traceback.format_exc()))\n\tmylogger.info(\"get %s records from gionee\" % count)\n\tdb_conn.commit()\n\ndef get_lenovo_kc():\n\tcount = 0\n\turl = \"http://yx.lenovomm.com/business/app!getNewest.action?width=1080&t=22&s=0&dpi=480&height=1920\"\n\ttry:\n\t\tr = requests.get(url, timeout=10)\n\t\tif r.status_code == 200:\n\t\t\td = r.json()\n\t\t\tfor ret in d['datalist']:\n\t\t\t\ttitle = ret.get('name', u'')\n\t\t\t\tgame_type = ret.get('categoryName', u'')\n\t\t\t\timg = ret.get('iconAddr', u'')\n\t\t\t\tpublishDate= ret.get('publishDate', u'')\n\t\t\t\tpopular = ret.get('downloadCount', u'')\n\t\t\t\tpkg_name = ret.get('packageName', u'')\n\t\t\t\tif publishDate and pkg_name:\n\t\t\t\t\tpublish_date = unicode(datetime.date.fromtimestamp(int(unicode(publishDate)[:-3])))\n\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.pkg_name==pkg_name).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('lenovo')).first()\n\t\t\t\t\t#ins = db_conn.query(KC_LIST).filter(KC_LIST.title==title).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('lenovo')).first()\n\t\t\t\t\tif ins is None:\n\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\t\t\"title2\": pkg_name,\n\t\t\t\t\t\t\t\t\t\t\"pkg_name\": pkg_name,\n\t\t\t\t\t\t\t\t\t\t\"game_type\": game_type,\n\t\t\t\t\t\t\t\t\t\t\"publish_date\": publish_date,\n\t\t\t\t\t\t\t\t\t\t\"popular\": popular,\n\t\t\t\t\t\t\t\t\t\t\"img\": img,\n\t\t\t\t\t\t\t\t\t\t\"source\": source_map.get('lenovo')\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\telse:\n\t\t\t\t\t\tins.title2 = ret.get('packageName', u'')\n\t\t\t\t\t\tins.pkg_name = ret.get('packageName', u'')\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (url, traceback.format_exc()))\n\tmylogger.info(\"get %s records from lenovo\" % count)\n\tdb_conn.commit()\n\t\t\t\t\n\ndef get_iqiyi_kc(page):\n\tcount = 0\n\turl = \"http://store.iqiyi.com/gc/list?callback=rs&id=228&no=%s\" % page\n\ttry:\n\t\tr = requests.get(url, timeout=10)\n\t\tif r.status_code == 200:\n\t\t\tm = re.search(u'rs\\\\(([\\s\\S]*)\\\\)\\\\;', r.text)\n\t\t\tif m is not None:\n\t\t\t\td = json.loads(m.group(1))\n\t\t\t\tfor ret in d['list']:\n\t\t\t\t\ttitle = ret.get('name', u'')\n\t\t\t\t\timg = ret.get('icon', u'')\n\t\t\t\t\tgame_type = ret.get('cate_name', u'')\n\t\t\t\t\tqipu_id = ret.get('qipu_id', u'')\n\t\t\t\t\tpopular = ret.get('cnt', u'')\n\t\t\t\t\tif qipu_id:\n\t\t\t\t\t\tpublish_date = get_iqiyi_pubtime_by_id(qipu_id)\n\t\t\t\t\t\tif publish_date:\n\t\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.game_id==qipu_id).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('iqiyi')).first()\n\t\t\t\t\t\t\t#ins = db_conn.query(KC_LIST).filter(KC_LIST.title==title).filter(KC_LIST.title2==qipu_id).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('iqiyi')).first()\n\t\t\t\t\t\t\tif ins is None:\n\t\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\t\t\t\t\"title2\": qipu_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\"game_id\": qipu_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\"game_type\": game_type,\n\t\t\t\t\t\t\t\t\t\t\t\t\"publish_date\": publish_date,\n\t\t\t\t\t\t\t\t\t\t\t\t\"popular\": popular,\n\t\t\t\t\t\t\t\t\t\t\t\t\"img\": img,\n\t\t\t\t\t\t\t\t\t\t\t\t\"source\": source_map.get('iqiyi')\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\tdb_conn.merge(item)\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (url, traceback.format_exc()))\n\tmylogger.info(\"get %s records from iqiyi\" % count)\n\tdb_conn.commit()\n\t\t\t\t\t\t\n\t\t\t\t\t\ndef get_iqiyi_pubtime_by_id(qipu_id):\n\turl = \"http://store.iqiyi.com/gc/game/detail?callback=rs&id=%s\" % qipu_id\n\ttry:\n\t\tr = requests.get(url)\n\t\tif r.status_code == 200:\n\t\t\tm = re.search(u'rs\\\\(([\\s\\S]*)\\\\)\\\\;', r.text)\n\t\t\tif m is not None:\n\t\t\t\td = json.loads(m.group(1))\n\t\t\t\tdt = d['app']['date']\n\t\t\t\tm = re.search(u'(\\d+)年(\\d+)月(\\d+)日', dt)\n\t\t\t\ttry:\n\t\t\t\t\tpublish_date = u\"%s-%s-%s\" % (m.group(1), m.group(2), m.group(3))\n\t\t\t\t\treturn publish_date\n\t\t\t\texcept Exception, e:\n\t\t\t\t\tmylogger.error(\"### %s ###\\t%s\" % (dt.encode('utf-8'), traceback.format_exc()))\n\texcept Exception, e:\n\t\tmylogger.error(\"### %s ###\\t%s\" % (qipu_id.encode('utf-8'), traceback.format_exc()))\n\treturn u''\t\n\t\ndef get_youku_kc():\n\tcount = 0\n\turl = \"http://api.gamex.mobile.youku.com/app/new_game_tab/get?pg=1&pz=40\"\n\ttry:\n\t\tr = requests.get(url, timeout=10)\n\t\tif r.status_code == 200:\n\t\t\td = r.json()\n\t\t\tfor ret in d['games']:\n\t\t\t\tpublish_date = ret.get('apk_update_time', u'')\n\t\t\t\tpopular = ret.get('total_downloads', u'')\n\t\t\t\ttitle = ret.get('appname', u'')\n\t\t\t\tgame_type = ret.get('type', u'')\n\t\t\t\timg = ret.get('logo', u'')\n\t\t\t\tgame_id = ret.get('id', u'')\n\t\t\t\tif publish_date and game_id:\n\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.game_id==game_id).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('youku')).first()\n\t\t\t\t\t#ins = db_conn.query(KC_LIST).filter(KC_LIST.title==title).filter(KC_LIST.title2==game_id).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('youku')).first()\n\t\t\t\t\tif ins is None:\n\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\t\t\"title2\": game_id,\n\t\t\t\t\t\t\t\t\t\t\"game_id\": game_id,\n\t\t\t\t\t\t\t\t\t\t\"game_type\": game_type,\n\t\t\t\t\t\t\t\t\t\t\"publish_date\": publish_date,\n\t\t\t\t\t\t\t\t\t\t\"popular\": popular,\n\t\t\t\t\t\t\t\t\t\t\"img\": img,\n\t\t\t\t\t\t\t\t\t\t\"source\": source_map.get('youku')\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (url, traceback.format_exc()))\n\tmylogger.info(\"get %s records from youku\" % count)\n\tdb_conn.commit()\n\ndef get_wandoujia_kc():\n\tcount = 0\n\turl = \"http://apis.wandoujia.com/apps/v1/topics/smart438/list?start=0&max=15\"\n\ttry:\n\t\tr = requests.get(url, timeout=10)\n\t\tif r.status_code == 200:\n\t\t\td = r.json()\n\t\t\tfor ret in d['entity']:\n\t\t\t\ttitle = ret.get('title', u'')\n\t\t\t\taction = ret.get('action', u'')\n\t\t\t\timg = ret.get('icon', u'')\n\t\t\t\tif action is not None:\n\t\t\t\t\tdetail_url = action.get('url', u'')\n\t\t\t\t\tif detail_url:\n\t\t\t\t\t\tdetail = get_wandoujia_detail(detail_url)\t\n\t\t\t\t\t\tif detail is not None:\n\t\t\t\t\t\t\tgame_type, popular, publish_date = detail\n\t\t\t\t\t\t\t#print title, game_type, publish_date\n\t\t\t\t\t\t\tif publish_date:\n\t\t\t\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.url==detail_url).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('wandoujia')).first()\n\t\t\t\t\t\t\t\t\tif ins is None:\n\t\t\t\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"url\": detail_url,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"game_type\": game_type,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"publish_date\": publish_date,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"popular\": popular,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"img\": img,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"source\": source_map.get('wandoujia')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\tdb_conn.merge(item)\n\texcept Exception,e:\n\t\tmylogger.error(\"### %s ### %s\" % (url, traceback.format_exc()))\n\tmylogger.info(\"get %s records from wandoujia\" % count)\n\tdb_conn.commit()\n\ndef get_wandoujia_detail(url):\n\ttry:\n\t\tr = requests.get(url, timeout=10)\n\t\tif r.status_code == 200:\n\t\t\td = r.json()\n\t\t\tentity = d['entity']\n\t\t\tif entity:\n\t\t\t\tdetail = entity[0]['detail']['appDetail']\n\t\t\t\tif detail is not None:\n\t\t\t\t\tcategories = detail.get('categories', [])\n\t\t\t\t\tgame_type = u\",\".join([c['name'] for c in categories if c['level']==1])\n\t\t\t\t\tpopular = detail.get('downloadCount', u'')\n\t\t\t\t\tpublishtime = detail.get('updatedDate', u'')\n\t\t\t\t\tpublish_date = unicode(datetime.date.fromtimestamp(int(unicode(publishtime)[:10]))) if publishtime else u\"\"\n\t\t\t\t\treturn game_type, popular, publish_date\n\texcept Exception,e:\n\t\tmylogger.error(\"### %s ### %s\" % (url.encode('utf-8'), traceback.format_exc()))\n\treturn None\n\t\t\n\ndef get_sogou_kc():\n\tcount = 0\n\turl = \"http://mobile.zhushou.sogou.com/android/rank/toplist.html?limit=25&start=25&group=2&id=13\"\n\ttry:\n\t\tr = requests.get(url, timeout=10)\n\t\tif r.status_code == 200:\n\t\t\td = r.json()\n\t\t\tfor ret in d['recommend_app']:\n\t\t\t\timg = ret.get('icon', u'')\n\t\t\t\ttitle = ret.get('name', u'')\n\t\t\t\tpopular = ret.get('downloadCount', u'')\n\t\t\t\tgame_type = ret.get('category_name', u'')\n\t\t\t\tdt = ret.get('date', u'')\n\t\t\t\tgame_id = ret.get('appid', u'')\n\t\t\t\tif dt and game_id:\n\t\t\t\t\tpublish_date = dt[:11]\n\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.game_id==game_id).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('sogou')).first()\n\t\t\t\t\tif ins is None:\n\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\t\t\"title2\": game_id,\n\t\t\t\t\t\t\t\t\t\t\"game_id\": game_id,\n\t\t\t\t\t\t\t\t\t\t\"game_type\": game_type,\n\t\t\t\t\t\t\t\t\t\t\"publish_date\": publish_date,\n\t\t\t\t\t\t\t\t\t\t\"popular\": popular,\n\t\t\t\t\t\t\t\t\t\t\"img\": img,\n\t\t\t\t\t\t\t\t\t\t\"source\": source_map.get('sogou')\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\telse:\n\t\t\t\t\t\tins.title2 = ret.get('appid', u'')\n\t\t\t\t\t\tins.game_id = ret.get('appid', u'')\n\texcept Exception,e:\n\t\tmylogger.error(\"### %s ### %s\" % (url, traceback.format_exc()))\n\tmylogger.info(\"get %s records from sogou\" % count)\n\tdb_conn.commit()\n\t\t\t\ndef get_dangle_kc():\n\tcount = 0\n\turl = \"http://api2014.digua.d.cn/newdiguaserver/netgame/memorabilia\"\n\t\n\theaders = {\"HEAD\": {\n #\"stamp\": 1446714106000,\n \"stamp\": 1446712885154,\n \"verifyCode\": \"78492ba9e8569f3b9d9173ac4e4b6cb9\",\n \"it\": 2,\n \"resolutionWidth\": 1080,\n \"imei\": \"865931027730878\",\n \"clientChannelId\": \"100327\",\n \"versionCode\": 750,\n \"mac\": \"34:80:b3:4d:69:87\",\n \"vender\": \"Qualcomm\",\n \"vp\": \"\",\n \"version\": \"7.5\",\n \"sign\": \"8bb4d72622576380\",\n \"dd\": 480,\n \"sswdp\": \"360\",\n \"hasRoot\": 0,\n \"glEsVersion\": 196608,\n \"device\": \"MI_4LTE\",\n \"ss\": 2,\n \"local\": \"zh_CN\",\n \"language\": \"2\",\n \"sdk\": 19,\n \"resolutionHeight\": 1920,\n \"osName\": \"4.4.4\",\n \"gpu\": \"Adreno (TM) 330\"\n\t}}\n\ttry:\n\t\tr = requests.post(url, headers=headers, timeout=15)\n\t\tif r.status_code == 200:\n\t\t\td = r.json()\n\t\t\tfor ret in d['list']:\n\t\t\t\tgame_type = ret.get('categoryName', u'')\n\t\t\t\tpublish_status = ret.get('operationStatus', u'')\n\t\t\t\ttitle = ret.get('name', u'')\n\t\t\t\tpublishtime = ret.get('activityDate', u'')\n\t\t\t\tpublish_date = unicode(datetime.date.fromtimestamp(int(unicode(publishtime)[:10]))) if publishtime else u\"\"\n\t\t\t\timg = ret.get('iconUrl', u'')\n\t\t\t\tgame_id = ret.get('id', u'')\n\t\t\t\tif publish_date and game_id:\n\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.game_id==game_id).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('dangle')).first()\n\t\t\t\t\tif ins is None:\n\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\t\t\"title2\": game_id,\n\t\t\t\t\t\t\t\t\t\t\"game_id\": game_id,\n\t\t\t\t\t\t\t\t\t\t\"game_type\": game_type,\n\t\t\t\t\t\t\t\t\t\t\"publish_status\": publish_status,\n\t\t\t\t\t\t\t\t\t\t\"publish_date\": publish_date,\n\t\t\t\t\t\t\t\t\t\t\"img\": img,\n\t\t\t\t\t\t\t\t\t\t\"source\": source_map.get('dangle')\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\telse:\n\t\t\t\t\t\tins.title2 = ret.get('id', u'')\n\t\t\t\t\t\tins.game_id = ret.get('id', u'')\n\texcept Exception,e:\n\t\tmylogger.error(\"### %s ### %s\" % (url, traceback.format_exc()))\n\tmylogger.info(\"get %s records from dangle\" % count)\n\tdb_conn.commit()\n\t\t\t\t\ndef get_i4_kc(page):\n\tcount = 0\n\turl = \"http://app3.i4.cn/controller/action/online.go?store=3&module=3&rows=20&sort=2&submodule=6&model=101&id=0&reqtype=3&page=%s\" % page\n\ttry:\n\t\tr = requests.get(url)\n\t\tif r.status_code == 200:\n\t\t\td = r.json()\n\t\t\tfor ret in d['result']['list']:\n\t\t\t\tgame_type = ret.get('typeName', u'')\n\t\t\t\ttitle = ret.get('appName', u'')\n\t\t\t\tgame_id = ret.get('id', u'')\n\t\t\t\tpopular = ret.get('downloadCount', u'')\n\t\t\t\tnewUpdateTime = ret.get('newUpdateTime', u'')\n\t\t\t\timg = u'http://d.image.i4.cn/image/%s' % ret.get('icon', u'')\n\t\t\t\tpublish_date = newUpdateTime[:10] if newUpdateTime else u''\n\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.game_id==game_id).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('i4')).first()\n\t\t\t\tif ins is None:\n\t\t\t\t\tcount += 1\n\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\t\"title2\": game_id,\n\t\t\t\t\t\t\t\t\t\"game_id\": game_id,\n\t\t\t\t\t\t\t\t\t\"game_type\": game_type,\n\t\t\t\t\t\t\t\t\t\"publish_date\": publish_date,\n\t\t\t\t\t\t\t\t\t\"img\": img,\n\t\t\t\t\t\t\t\t\t\"popular\": popular,\n\t\t\t\t\t\t\t\t\t\"source\": source_map.get('i4')\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\tdb_conn.merge(item)\n\texcept Exception,e:\n\t\tmylogger.error(\"### %s ### %s\" % (url, traceback.format_exc()))\n\tmylogger.info(\"get %s records from i4\" % count)\n\tdb_conn.commit()\n\ndef get_i4_detail_by_id():\n\turl = \"http://app3.i4.cn/controller/action/online.go?store=3&module=1&id=253283&reqtype=5\"\n\n\ndef get_muzhiwan_kc():\n\tcount = 0\n\tURL = \"http://www.muzhiwan.com/wangyou/kaice/\"\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\ttoday_kc_list = soup.find('ul', class_='td_del hot_list')\n\t\t\tif today_kc_list is not None:\n\t\t\t\tfor li in today_kc_list.find_all('li', class_='clearfix li_contents_list'):\n\t\t\t\t\ttitle = u''\n\t\t\t\t\tpkg_name = u''\n\t\t\t\t\tgame_type = u''\n\t\t\t\t\tpublish_status = u''\n\t\t\t\t\timg = u''\n\t\t\t\t\ttag_td = li.find('div', class_='tag tag_td')\n\t\t\t\t\tif tag_td is not None and tag_td.find('a') is not None:\n\t\t\t\t\t\ttitle = tag_td.find('a').text\n\t\t\t\t\t\tpkg_name = tag_td.find('a').get('href')\n\t\t\t\t\tfl = li.find('div', class_='fl')\n\t\t\t\t\tif fl is not None and fl.find('a') is not None:\n\t\t\t\t\t\tif fl.find('a').find('img') is not None:\n\t\t\t\t\t\t\timg = fl.find('a').find('img').get('src')\n\t\t\t\t\tpublish_status_div = soup.find('div', class_='fl pl10 ')\n\t\t\t\t\tif publish_status_div is not None:\n\t\t\t\t\t\tfor g in publish_status_div.find_all('p'):\n\t\t\t\t\t\t\tsegs = re.sub('\\s+', u'', g.text).split(':')\n\t\t\t\t\t\t\tif len(segs) == 2:\n\t\t\t\t\t\t\t\tif segs[0] == u'游戏状态':\n\t\t\t\t\t\t\t\t\tpublish_status = segs[1]\n\t\t\t\t\t\t\t\tif segs[0] == u'游戏类型':\n\t\t\t\t\t\t\t\t\tgame_type = segs[1]\n\t\t\t\t\tif pkg_name:\n\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\turl = u\"http://www.muzhiwan.com%s\" % pkg_name\n\t\t\t\t\t\tpublish_date = unicode(datetime.date.today())\n\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.url==url).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('muzhiwan')).first()\n\t\t\t\t\t\tif ins is None:\n\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\t\"url\": url,\n\t\t\t\t\t\t\t\t\t\"game_type\": game_type,\n\t\t\t\t\t\t\t\t\t\"publish_status\": publish_status,\n\t\t\t\t\t\t\t\t\t\"publish_date\": publish_date,\n\t\t\t\t\t\t\t\t\t\"img\": img,\n\t\t\t\t\t\t\t\t\t\"source\": source_map.get('muzhiwan')\n\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tins.img = img\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\tmylogger.info(\"get %s records from muzhiwan\" % count)\n\tdb_conn.commit()\n\n\ndef get_muzhiwan_kc_v1(page):\n\tcount = 0\n\t#URL = \"http://www.muzhiwan.com/category/12/\"\n\tURL = \"http://www.muzhiwan.com/category/12/new-0-0-%s.html\" % page\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\tul = soup.find('ul', class_=\"gamelist pt10 pb20 pl10\")\n\t\t\tif ul is not None:\n\t\t\t\tfor ret in ul.find_all('li'):\n\t\t\t\t\tdetail = ret.find('a')\n\t\t\t\t\tcomments_div = ret.find('div').find('span')\n\t\t\t\t\tpopular = u'0'\n\t\t\t\t\tif comments_div is not None and u'评论数' in comments_div.text:\n\t\t\t\t\t\tm = re.search(u'(\\d+)个', comments_div.text)\n\t\t\t\t\t\tpopular = m.group(1) if m is not None else u'0'\n\t\t\t\t\tif detail is not None:\n\t\t\t\t\t\t_img = detail.find('img')\n\t\t\t\t\t\tif _img is not None:\n\t\t\t\t\t\t\ttitle = _img.get('alt')\n\t\t\t\t\t\t\timg = _img.get('lazy-src')\n\t\t\t\t\t\t\tinfo = get_muzhiwan_detail(detail.get('href'))\n\t\t\t\t\t\t\turl = detail.get('href')\n\t\t\t\t\t\t\tif u'发布' in info:\n\t\t\t\t\t\t\t\tpublish_date = info.get(u'发布', u'')\n\t\t\t\t\t\t\t\tif publish_date and url is not None:\n\t\t\t\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.url==url).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('muzhiwan')).first()\n\t\t\t\t\t\t\t\t\tif ins is None:\n\t\t\t\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\t\t\t\t\"url\": url,\n\t\t\t\t\t\t\t\t\t\t\t\t\"title2\": info.get('title2', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\"game_type\": info.get(u'分类', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\"publish_date\": info.get(u'发布', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\"img\": img,\n\t\t\t\t\t\t\t\t\t\t\t\t\"popular\": popular,\n\t\t\t\t\t\t\t\t\t\t\t\t\"source\": source_map.get('muzhiwan')\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tins.url = detail.get('href')\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\tmylogger.info(\"get %s records from muzhiwan\" % count)\n\tdb_conn.commit()\n\ndef get_muzhiwan_detail(url):\n\tmydict = {}\n\ttry:\n\t\tresponse = s.get(url, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\tinfo = soup.find('div', class_='detail_info')\n\t\t\tif info is not None:\n\t\t\t\tgame_name = info.find('div', class_='game_name')\n\t\t\t\ttitle2 = game_name.find('h1').text if game_name is not None else u''\n\t\t\t\tmydict[u'title2'] = title2\n\t\t\t\tfor ret in info.find('div', class_='clearfix').find_all('li'):\n\t\t\t\t\tsegs = ret.text.split(u':')\n\t\t\t\t\tif len(segs) == 2:\n\t\t\t\t\t\tmydict[segs[0]] = segs[1]\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (url, traceback.format_exc()))\n\treturn mydict\n\ndef get_huawei_kc(page):\n\tcount = 0\n\tURL = \"http://appstore.huawei.com/game/list_2_1_%s\" % page\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\tunit_list = soup.find('div', class_='unit-main')\n\t\t\tif unit_list is not None:\n\t\t\t\tfor unit in unit_list.find_all('div', class_='list-game-app dotline-btn nofloat'):\n\t\t\t\t\ttitle = u\"\"\n\t\t\t\t\tpublish_date = u\"\"\n\t\t\t\t\timg = u\"\"\n\t\t\t\t\turl = u\"\"\n\t\t\t\t\tpopular = u\"\"\n\t\t\t\t\tinfo_ico_div = unit.find('div',class_='game-info-ico')\n\t\t\t\t\tif info_ico_div is not None:\n\t\t\t\t\t\tif info_ico_div.find('a') is not None:\n\t\t\t\t\t\t\turl = info_ico_div.find('a').get('href')\n\t\t\t\t\t\timg_div = info_ico_div.find('img')\n\t\t\t\t\t\tif img_div is not None:\n\t\t\t\t\t\t\ttitle = img_div.get('title')\n\t\t\t\t\t\t\timg = img_div.get('src')\n\t\t\t\t\tdate_p = unit.find('p', class_='date')\t\n\t\t\t\t\tif date_p is not None:\n\t\t\t\t\t\tdate_span = date_p.find('span')\n\t\t\t\t\t\tif date_span is not None:\n\t\t\t\t\t\t\tpublish_date = date_span.text.split(u':')[1].strip()\n\t\t\t\t\t\t\tif publish_date and title:\n\t\t\t\t\t\t\t\tdownload_div = unit.find('div', class_=\"app-btn\")\n\t\t\t\t\t\t\t\tif download_div is not None:\n\t\t\t\t\t\t\t\t\tif len(download_div.find_all('span'))==2:\n\t\t\t\t\t\t\t\t\t\tdownload_span = download_div.find_all('span')[1]\n\t\t\t\t\t\t\t\t\t\tm = re.search('\\d+', download_span.text)\n\t\t\t\t\t\t\t\t\t\tpopular = m.group() if m is not None else u''\n\t\t\t\t\t\t\t\t#print publish_date, title, popular, img\n\t\t\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.url==url).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('huawei')).first()\n\t\t\t\t\t\t\t\tif ins is None:\n\t\t\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\t\t\t\t\"publish_date\": publish_date,\n\t\t\t\t\t\t\t\t\t\t\t\t\"img\": img,\n\t\t\t\t\t\t\t\t\t\t\t\t\"url\": url,\n\t\t\t\t\t\t\t\t\t\t\t\t\"popular\": popular,\n\t\t\t\t\t\t\t\t\t\t\t\t\"source\": source_map.get('huawei')\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\tins.url = url\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\tmylogger.info(\"get %s records from huawei\" % count)\n\tdb_conn.commit()\n\t\t\t\t\n\ndef get_kuaiyong_kc(page):\n\tcount = 0\n\tURL = \"http://app.kuaiyong.com/list/index/appType/game/page/%s\" % page\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\tfor ret in soup.find_all('div', class_=\"app-item\"):\n\t\t\t\titem_icon = ret.find('a', class_=\"app-item-icon\")\n\t\t\t\tif item_icon is not None:\n\t\t\t\t\timg_div = item_icon.find('img')\n\t\t\t\t\timg = img_div.get('data-src') if img_div is not None else u''\n\t\t\t\t\tdetail_url = u\"http://app.kuaiyong.com%s\" % item_icon.get('href')\n\t\t\t\t\tif detail_url:\n\t\t\t\t\t\tinfo = get_kuaiyong_detail(detail_url)\n\t\t\t\t\t\tif u'时 间' in info:\n\t\t\t\t\t\t\ttitle = info.get('title', u'')\n\t\t\t\t\t\t\tpublish_date = info.get(u'时 间', u'')\n\t\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.url==detail_url).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('kuaiyong')).first()\n\t\t\t\t\t\t\tif ins is None:\n\t\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\t\t\t\t\"publish_date\": publish_date,\n\t\t\t\t\t\t\t\t\t\t\t\t\"img\": img,\n\t\t\t\t\t\t\t\t\t\t\t\t\"url\": detail_url,\n\t\t\t\t\t\t\t\t\t\t\t\t\"game_type\": info.get(u'类 别', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\"popular\": info.get(u'下载', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\"source\": source_map.get('kuaiyong')\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\tdb_conn.merge(item)\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\tmylogger.info(\"get %s records from kuaiyong\" % count)\n\tdb_conn.commit()\n\t\t\t\t\t\t\n\ndef get_kuaiyong_detail(URL):\n\tmydict = {}\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\tbase_right = soup.find('div', class_='base-right')\n\t\t\tmydict = {}\n\t\t\tif base_right is not None:\n\t\t\t\tif base_right.find('h1') is not None:\n\t\t\t\t\tmydict[u'title'] = base_right.find('h1').text\n\t\t\t\tbase_list = base_right.find('div', class_='base-list')\n\t\t\t\tif base_list is not None:\n\t\t\t\t\tfor ret in base_list.find_all('p'):\n\t\t\t\t\t\tif ret.text:\n\t\t\t\t\t\t\tsegs = ret.text.split(u':')\n\t\t\t\t\t\t\tif len(segs) == 2:\n\t\t\t\t\t\t\t\tmydict[segs[0]] = segs[1]\n\t\t\t\t\t\t\telif len(segs)==1 and u'次下载' in ret.text:\n\t\t\t\t\t\t\t\tmydict[u'下载'] = re.sub(u'次下载|\\n|\\r', u'', ret.text)\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\treturn mydict\n\ndef get_itools_kc():\n\tcount = 0\n\tURL = \"http://ios.itools.cn/game/iphone/gameall_3_1\"\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\tul = soup.find('ul', class_='ios_app_list')\n\t\t\tif ul is not None:\n\t\t\t\tfor app in ul.find_all('li'):\n\t\t\t\t\tapp_on = app.find('div', class_='ios_app_on')\n\t\t\t\t\tif app_on is not None:\n\t\t\t\t\t\tdetail_url = app_on.find('a').get('href') if app_on.find('a') is not None else u''\n\t\t\t\t\t\tif detail_url:\n\t\t\t\t\t\t\tdetail_url = u\"http://ios.itools.cn%s\" % detail_url\n\t\t\t\t\t\t\tinfo = get_itools_detail(detail_url)\n\t\t\t\t\t\t\tif 'title' in info and u'更新时间' in info:\n\t\t\t\t\t\t\t\ttitle = info.get('title', u'')\n\t\t\t\t\t\t\t\tdt = info.get(u'更新时间', u'')\n\t\t\t\t\t\t\t\tif title and dt:\n\t\t\t\t\t\t\t\t\tpublish_date = re.sub(u'年|月|日', u'-', dt)[:-1]\n\t\t\t\t\t\t\t\t\t#print title, publish_date\n\t\t\t\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.title==title).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('itools')).first()\n\t\t\t\t\t\t\t\t\tif ins is None:\n\t\t\t\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"publish_date\": publish_date,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"img\": info.get('img', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"url\": detail_url,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"game_type\": info.get(u'标 签', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"source\": source_map.get('itools')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\tdb_conn.merge(item)\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\tmylogger.info(\"get %s records from itools\" % count)\n\tdb_conn.commit()\n\ndef get_itools_detail(URL):\n\tmydict = {}\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\tdetails_app = soup.find('div', class_=\"details_app\")\n\t\t\tif details_app is not None:\n\t\t\t\timg_div = details_app.find('div', class_='fl w140')\n\t\t\t\tif img_div is not None:\n\t\t\t\t\timg = img_div.find('p').find('img').get('src') if img_div.find('p') is not None else u''\n\t\t\t\t\tmydict['img'] = img\n\t\t\t\tinfo_div = details_app.find('dl', class_='fl')\n\t\t\t\tif info_div is not None:\n\t\t\t\t\tmydict['title'] = info_div.find('dt').text\n\t\t\t\t\tfor info in info_div.find_all('span'):\n\t\t\t\t\t\tsegs = info.text.split(u':')\n\t\t\t\t\t\tif len(segs) == 2:\n\t\t\t\t\t\t\tmydict[segs[0]] = segs[1]\n\t\t\t\t\tfor info in info_div.find_all('dd'):\n\t\t\t\t\t\tsegs = info.text.split(u':')\n\t\t\t\t\t\tif len(segs) == 2:\n\t\t\t\t\t\t\tmydict[segs[0]] = segs[1]\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\treturn mydict\n\ndef get_anzhi_kc(page):\n\tcount = 0\n\tURL = \"http://www.anzhi.com/list_2_%s_new.html\" % page\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\tapp_list = soup.find('div', 'app_list border_three')\n\t\t\tif app_list is not None:\n\t\t\t\tfor app in app_list.find_all('div', class_='app_info'):\n\t\t\t\t\tapp_name = app.find('span', class_='app_name')\n\t\t\t\t\tif app_name is not None:\n\t\t\t\t\t\ttitle_a = app_name.find('a')\n\t\t\t\t\t\tif title_a is not None:\n\t\t\t\t\t\t\tdetail_url = u\"http://www.anzhi.com%s\" % title_a.get('href')\n\t\t\t\t\t\t\ttitle = title_a.text\n\t\t\t\t\t\t\tinfo = get_anzhi_detail(detail_url)\n\t\t\t\t\t\t\tif u'时间' in info:\n\t\t\t\t\t\t\t\tdt = info.get(u'时间', u'')\n\t\t\t\t\t\t\t\tif title and dt:\n\t\t\t\t\t\t\t\t\tpublish_date = re.sub(u'年|月|日', u'-', dt)[:-1]\n\t\t\t\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.title==title).filter(KC_LIST.publish_date==publish_date).filter(KC_LIST.source==source_map.get('anzhi')).first()\n\t\t\t\t\t\t\t\t\tif ins is None:\n\t\t\t\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"title\": title,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"publish_date\": publish_date,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"img\": info.get('img', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"url\": detail_url,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"popular\": info.get(u'下载', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"game_type\": info.get(u'分类', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\"source\": source_map.get('anzhi')\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\t\t\tins.popular = info.get(u'下载', '')\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\tmylogger.info(\"get %s records from anzhi\" % count)\n\tdb_conn.commit()\n\ndef get_anzhi_detail(URL):\n\tmydict = {}\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\tdetail_icon = soup.find('div', class_='detail_icon')\n\t\t\tif detail_icon is not None:\n\t\t\t\timg_div = detail_icon.find('img')\n\t\t\t\tif img_div is not None:\n\t\t\t\t\tmydict['img'] = u\"http://www.anzhi.com%s\" % img_div.get('src')\n\t\t\tdetail_line_ul = soup.find('ul', id='detail_line_ul')\n\t\t\tif detail_line_ul is not None:\n\t\t\t\tfor li in detail_line_ul.find_all('li'):\n\t\t\t\t\tsegs = li.text.split(u':')\n\t\t\t\t\tif len(segs) == 2:\n\t\t\t\t\t\tmydict[segs[0]] = segs[1]\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\treturn mydict\n\ndef get_360_web_kc(page):\n\tcount = 0\n\tURL = \"http://zhushou.360.cn/list/index/cid/2/order/newest/?page=%s\" % page\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\ticonList = soup.find('ul', 'iconList')\n\t\t\tif iconList is not None:\n\t\t\t\tfor li in iconList.find_all('li'):\n\t\t\t\t\ttitle = u''\n\t\t\t\t\tpublish_date = li.find('span').text if li.find('span') is not None else u''\n\t\t\t\t\timg = u''\n\t\t\t\t\tif li.find('h3') is not None:\n\t\t\t\t\t\tif li.find('h3').find('a') is not None:\n\t\t\t\t\t\t\ttitle = li.find('h3').find('a').text\n\t\t\t\t\tif title and publish_date:\n\t\t\t\t\t\tif li.find('a') is not None:\n\t\t\t\t\t\t\timg = li.find('a').find('img').get('src')\n\t\t\t\t\t\t\tif li.find('a').get('href') is not None:\n\t\t\t\t\t\t\t\t_url = u\"http://zhushou.360.cn%s\" % li.find('a').get('href')\n\t\t\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.url==_url).filter(KC_LIST.source==source_map.get('360zhushou_web')).filter(KC_LIST.publish_date==publish_date).first()\n\t\t\t\t\t\t\t\tif not ins:\n\t\t\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\t\t\t'publish_date':publish_date,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'title':title,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'img':img,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'url':_url,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'source':source_map.get('360zhushou_web'),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\tdb_conn.merge(item)\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\tmylogger.info(\"get %s records from 360 zhushou web page %s\" % (count, page))\n\tdb_conn.commit()\n\t\t\t\t\n\ndef get_pp_kc(page):\n\tcount = 0\n\theaders = {'tunnel-command':4261421088}\n\ttry:\n\t\tj = {\"dcType\":0, \"resType\":2, \"listType\":0, \"catId\":0, \"clFlag\":1, \"perCount\":32, \"page\": page}\n\t\tr = requests.post('http://jsondata.25pp.com/index.html', data=json.dumps(j), headers=headers)\n\t\tif r.status_code == 200:\n\t\t\tcontent = re.sub(u'\\ufeff', u'', r.text)\n\t\t\td = json.loads(content)\n\t\t\tfor g in d['content']:\n\t\t\t\tgame_id = g.get('id', u'')\n\t\t\t\tif game_id:\n\t\t\t\t\tdetail = get_pp_detail_by_id(game_id)\n\t\t\t\t\ttitle = g.get('title', u'')\n\t\t\t\t\tupdatetime = g.get('updatetime', u'')\n\t\t\t\t\tpublish_date = unicode(datetime.date.fromtimestamp(updatetime))\n\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.game_id==game_id).filter(KC_LIST.source==source_map.get('pp')).filter(KC_LIST.publish_date==publish_date).first()\n\t\t\t\t\tif not ins:\n\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t'publish_date':publish_date,\n\t\t\t\t\t\t\t\t\t\t'title':title,\n\t\t\t\t\t\t\t\t\t\t'game_type': detail.get('catName', u''),\n\t\t\t\t\t\t\t\t\t\t'game_id': game_id,\n\t\t\t\t\t\t\t\t\t\t'title2': game_id,\n\t\t\t\t\t\t\t\t\t\t'img': g.get('thumb', u''),\n\t\t\t\t\t\t\t\t\t\t'source':source_map.get('pp'),\n\t\t\t\t\t\t\t\t\t\t'popular' : g.get('downloads', u'')\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\texcept Exception,e:\n\t\tmylogger.error(\"get pp kc list\\t%s\" % (traceback.format_exc()))\n\tmylogger.info(\"get %s records from pp %s\" % (count, page))\n\tdb_conn.commit()\n\n\ndef get_pp_detail_by_id(game_id):\n\ttry:\n\t\td = {\"site\":1, \"id\": game_id}\n\t\tr = requests.post('http://pppc2.25pp.com/pp_api/ios_appdetail.php', data=d)\n\t\tif r.status_code == 200:\n\t\t\treturn r.json()\n\texcept Exception,e:\n\t\tmylogger.error(\"get %s detail \\t%s\" % (game_id.encode('utf-8'), traceback.format_exc()))\n\treturn {}\n\ndef get_meizu_kc():\n\tcount = 0\n\tURL = \"http://api-game.meizu.com/games/public/new/layout?start=0&max=50\"\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tj = response.json() \n\t\t\tif j.get('code', 9527) == 200:\n\t\t\t\tblocks = j['value']['blocks']\n\t\t\t\tif blocks:\n\t\t\t\t\tfor rt in blocks[0]['data']:\n\t\t\t\t\t\ttitle = rt.get('name', u'')\n\t\t\t\t\t\tgame_id = rt.get('id', 0)\n\t\t\t\t\t\tdetail = get_meizu_detail_by_id(game_id)\n\t\t\t\t\t\tif title and game_id and detail is not None:\n\t\t\t\t\t\t\tversion_time = detail.get('version_time', u'')\n\t\t\t\t\t\t\tif version_time and game_id:\n\t\t\t\t\t\t\t\tpublish_date = unicode(datetime.date.fromtimestamp(int(unicode(version_time)[:10])))\n\t\t\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.game_id==game_id).filter(KC_LIST.source==source_map.get('meizu')).filter(KC_LIST.publish_date==publish_date).first()\n\t\t\t\t\t\t\t\tif not ins:\n\t\t\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\t\t'publish_date': publish_date,\n\t\t\t\t\t\t\t\t\t\t\t\t'title': rt.get('name', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'game_type': rt.get('category_name', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'title2': game_id,\n\t\t\t\t\t\t\t\t\t\t\t\t'game_id': game_id,\n\t\t\t\t\t\t\t\t\t\t\t\t'img': rt.get('icon', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'source': source_map.get('meizu'),\n\t\t\t\t\t\t\t\t\t\t\t\t'popular' : rt.get('download_count', u'')\n\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\t\tdb_conn.merge(item)\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\tmylogger.info(\"get %s records from meizu \" % (count))\n\tdb_conn.commit()\n\t\t\n\ndef get_meizu_detail_by_id(game_id):\n\tURL = \"http://api-game.meizu.com/games/public/detail/%s\" % game_id\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tj = response.json()\n\t\t\tif 'value' in j:\n\t\t\t\treturn j['value']\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\" % (traceback.format_exc()))\n\treturn None\n\n\ndef get_xyzs_kc(page):\n\tcount = 0\n\tURL = \"http://interface.xyzs.com/v2/ios/c01/game/latest?p=%s&ps=20\" % page\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tj = response.json() \n\t\t\tif j.get('code') == 200:\n\t\t\t\tif 'data' in j:\n\t\t\t\t\tfor rt in j['data'].get('result', []):\n\t\t\t\t\t\ttitle = rt.get('title', u'')\n\t\t\t\t\t\taddtime = rt.get('addtime', u'')\n\t\t\t\t\t\tgame_id = rt.get('itunesid', 0)\n\t\t\t\t\t\t#detail = get_xyzs_detail_by_id(gid)\n\t\t\t\t\t\tif addtime and game_id:\n\t\t\t\t\t\t\t# addtime字段内容不一定正确,日期会异常\n\t\t\t\t\t\t\t#game_type = detail.get('apptypesno', u'') if detail is not None else u''\n\t\t\t\t\t\t\tpublish_date = unicode(datetime.date.fromtimestamp(int(addtime)))\n\t\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.game_id==game_id).filter(KC_LIST.source==source_map.get('xyzs')).filter(KC_LIST.publish_date==publish_date).first()\n\t\t\t\t\t\tif not ins:\n\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\t'publish_date': publish_date,\n\t\t\t\t\t\t\t\t\t\t\t'title': title,\n\t\t\t\t\t\t\t\t\t\t\t'title2': game_id,\n\t\t\t\t\t\t\t\t\t\t\t'game_id': game_id,\n\t\t\t\t\t\t\t\t\t\t\t'img': rt.get('icon', u''),\n\t\t\t\t\t\t\t\t\t\t\t'source': source_map.get('xyzs'),\n\t\t\t\t\t\t\t\t\t\t\t'popular' : rt.get('downloadnum', u'')\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tdb_conn.merge(item)\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\tmylogger.info(\"get %s records from xyzs \" % (count))\n\tdb_conn.commit()\n\ndef get_91play_detail_by_id(game_id):\n\tURL = \"http://play.91.com/api.php/Api/index\"\n\ttry:\n\t\traw_data = {\"id\": game_id,\"firmware\":\"19\",\"time\":1449458211590,\"device\":1,\"action\":30005,\"app_version\":302,\"action_version\":4,\"mac\":\"7b715ce093480b34d6987\",\"debug\":0}\n\t\tresponse = requests.post(URL, data=raw_data, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tj = response.json() \n\t\t\tif j['data'] is not None:\n\t\t\t\treturn json.loads(j['data'])\n\texcept Exception,e:\n\t\tmylogger.error(\"91play %s detail\\t%s\" % (game_id, traceback.format_exc()))\n\treturn None\n\t\t\n\ndef get_91play_kc():\n\tcount = 0\n\tURL = \"http://play.91.com/api.php/Api/index\"\n\ttry:\n\t\traw_data = {\"id\":2,\"firmware\":\"19\",\"time\":1449455693994,\"index\":0,\"device\":1,\"action\":30002,\"app_version\":302,\"action_version\":4,\"mac\":\"7b715ce093480b34d6987\",\"debug\":0,\"size\":20}\n\t\tresponse = requests.post(URL, data=raw_data, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tj = response.json() \n\t\t\tif j['data'] is not None:\n\t\t\t\tfor rt in json.loads(j['data']):\n\t\t\t\t\tgame_id = rt.get('id', 0)\n\t\t\t\t\tdetail = get_91play_detail_by_id(game_id)\n\t\t\t\t\t#for k, v in detail.iteritems():\n\t\t\t\t\t#\tprint k,v\n\t\t\t\t\tif detail is not None:\n\t\t\t\t\t\ttitle = detail.get('name', u'')\n\t\t\t\t\t\tupdate_time = detail.get('update_time', u'')\n\t\t\t\t\t\tif update_time and title:\n\t\t\t\t\t\t\tpublish_date = unicode(datetime.date.fromtimestamp(int(update_time)))\n\t\t\t\t\t\t\t#print title, publish_date\n\t\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.title==title).filter(KC_LIST.source==source_map.get('91play')).filter(KC_LIST.publish_date==publish_date).first()\n\t\t\t\t\t\t\tif not ins:\n\t\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t\t\t'publish_date': publish_date,\n\t\t\t\t\t\t\t\t\t\t\t\t'title': title,\n\t\t\t\t\t\t\t\t\t\t\t\t'title2': game_id,\n\t\t\t\t\t\t\t\t\t\t\t\t'game_id': game_id,\n\t\t\t\t\t\t\t\t\t\t\t\t'img': rt.get('icon_url', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'source': source_map.get('91play'),\n\t\t\t\t\t\t\t\t\t\t\t\t'popular' : rt.get('download_count', u'')\n\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\tdb_conn.merge(item)\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\tmylogger.info(\"get %s records from 91play \" % (count))\n\tdb_conn.commit()\n\n\ndef get_360_gamebox_kc(start):\n\tcount = 0\n\tURL = \"http://next.gamebox.360.cn/7/xgamebox/newzone?count=20&start=%s&type=ontest\" % start\n\ttry:\n\t\tresponse = requests.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tj = response.json() \n\t\t\tif j.get('errno') == 0 and j['data'] is not None:\n\t\t\t\tfor rt in j['data']:\n\t\t\t\t\t#for k, v in rt.iteritems():\n\t\t\t\t\t#\tprint k, v\n\t\t\t\t\tpublish_date = u''\n\t\t\t\t\ttitle = rt.get('name', u'')\n\t\t\t\t\tkc_state = rt.get('state')\n\t\t\t\t\tpkg_name = rt.get('apkid', u'')\n\t\t\t\t\tif kc_state is not None:\n\t\t\t\t\t\topen_time_human = kc_state.get('open_time_human', u'')\n\t\t\t\t\t\tif open_time_human:\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\tm = re.search(u'(\\d+)月(\\d+)日', open_time_human)\n\t\t\t\t\t\t\t\tstr_dt = u\"%s-%s-%s\" % (unicode(datetime.date.today().year), m.group(1), m.group(2))\n\t\t\t\t\t\t\t\tdt = datetime.datetime.strptime(str_dt, '%Y-%m-%d')\n\t\t\t\t\t\t\t\tpublish_date = unicode(dt.date())\n\t\t\t\t\t\t\texcept Exception, e:\n\t\t\t\t\t\t\t\tmylogger.error(\"### gamebox open time %s ###\\t%s\" % (title.encode('utf-8'), traceback.format_exc()))\n\t\t\t\t\tif pkg_name and publish_date:\n\t\t\t\t\t\tins = db_conn.query(KC_LIST).filter(KC_LIST.pkg_name==pkg_name).filter(KC_LIST.source==source_map.get('360_gamebox')).filter(KC_LIST.publish_date==publish_date).first()\n\t\t\t\t\t\tif not ins:\n\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\titem = KC_LIST(**{\n\t\t\t\t\t\t\t\t\t\t'publish_date': publish_date,\n\t\t\t\t\t\t\t\t\t\t'title': rt.get('name', u''),\n\t\t\t\t\t\t\t\t\t\t'game_type': rt.get('category_name', u''),\n\t\t\t\t\t\t\t\t\t\t'title2': pkg_name,\n\t\t\t\t\t\t\t\t\t\t'pkg_name': pkg_name,\n\t\t\t\t\t\t\t\t\t\t'game_id': rt.get('id', u''),\n\t\t\t\t\t\t\t\t\t\t'img': rt.get('logo_url', u''),\n\t\t\t\t\t\t\t\t\t\t'source': source_map.get('360_gamebox'),\n\t\t\t\t\t\t\t\t\t\t'popular' : rt.get('download_times', u'')\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\t\telse:\n\t\t\t\t\t\t\tins.game_id = rt.get('id', u'')\n\t\t\t\t\t\t\tins.pkg_name = rt.get('apkid', u'')\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\tmylogger.info(\"get %s records from 360_gamebox \" % (count))\n\tdb_conn.commit()\n\n\ndef main():\n\tmylogger.info(\"gogo\")\n\tget_18183_kc()\n\tget_360_kc()\n\tget_appicsh_kc()\n\tget_360zhushou_kc()\n\tget_xiaomi_new_kc(1)\n\tget_xiaomi_rpg_kc(1)\n\tget_open_play_kc()\n\tget_vivo_kc(1)\n\tget_coolpad_kc()\n\tget_gionee_kc(1)\n\tget_lenovo_kc()\n\tget_iqiyi_kc(1)\n\tget_youku_kc()\n\tget_sogou_kc()\n\tget_dangle_kc()\n\tget_huawei_kc(1)\n\tget_kuaiyong_kc(1)\n\tget_360_web_kc(1)\n\tget_wandoujia_kc()\n\tget_9game_today_kc()\n\tget_pp_kc(1)\n\tget_meizu_kc()\n\tget_i4_kc(1)\n\tget_xyzs_kc(1)\n\tget_91play_kc()\n\tget_360_gamebox_kc(0)\n\tget_muzhiwan_kc()\n\nif __name__ == '__main__':\n\tmain()\n\tget_anzhi_kc()\n"
},
{
"alpha_fraction": 0.6254538893699646,
"alphanum_fraction": 0.6459695100784302,
"avg_line_length": 33.86075973510742,
"blob_id": "cc9720ebcaf6b3b98609992bc08de735618ad009",
"content_id": "2582cba93a140ea4d147639a00c4e89330f52e56",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5518,
"license_type": "no_license",
"max_line_length": 165,
"num_lines": 158,
"path": "/spider/data_merge.py",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#encoding=utf-8\n\nimport sys\nimport requests\nimport json\nimport urllib\nimport traceback\nfrom config import *\nimport re\nfrom bs4 import BeautifulSoup\nimport time\nimport datetime\n\ndb_conn = new_session()\n\nmylogger = get_logger('merge_data')\n\ndef main():\n\tcount = 0\n\tdb_conn.close()\n\tmydict = {}\n\tfrom sqlalchemy import not_\n\tfor ret in new_session().query(KC_LIST).filter(KC_LIST.title!=u'').filter(not_(KC_LIST.source.in_((21, 22)))).filter(KC_LIST.publish_date>=u'2015-10-01'):\n\t\tsegs = re.split(u'-|\\(|\\)|(|)|:|:|[\\s]*-|-', ret.title)\n\t\tif len(segs)>=2:\n\t\t\tif ret.title.startswith('(') or ret.title.startswith(u'('): \n\t\t\t\tmydict[ret.id] = segs[2]\n\t\t\telse:\n\t\t\t\tmydict[ret.id] = segs[0]\n\t\telse:\n\t\t\tmydict[ret.id] = ret.title\n\tout = {}\n\ttitles = set(mydict.values())\n\tfor t in titles:\n\t\tout[t] = []\n\tfor k, v in mydict.iteritems():\t\n\t\tif v in out:\n\t\t\tout[v].append(str(k))\n\tfor title, ids in out.iteritems():\n\t\tpublish_status = get_publish_status(ids)\t\n\t\timgs, game_type, summary, download_num, comment_num, rating, pkg_size, author, version, topic_num_total = get_game_detail(ids)\n\t\t#print title, game_type, ids\n\t\tins = db_conn.query(PublishGame).filter(PublishGame.name==title).first()\n\t\tif ins is None:\n\t\t\tcount += 1\n\t\t\titem = PublishGame(**{\n\t\t\t\t\t\t\t\t'name': title,\n\t\t\t\t\t\t\t\t'imgs': imgs,\n\t\t\t\t\t\t\t\t'game_type': game_type,\n\t\t\t\t\t\t\t\t'summary': summary,\n\t\t\t\t\t\t\t\t'download_num': download_num,\n\t\t\t\t\t\t\t\t'comment_num': comment_num,\n\t\t\t\t\t\t\t\t'rating': rating,\n\t\t\t\t\t\t\t\t'pkg_size': pkg_size,\n\t\t\t\t\t\t\t\t'author': author,\n\t\t\t\t\t\t\t\t'version': version,\n\t\t\t\t\t\t\t\t'topic_num': topic_num_total,\n\t\t\t\t\t\t\t\t'kc_list_ids': publish_status.get('kc_list_ids', u''),\n\t\t\t\t\t\t\t\t'channels': publish_status.get('channel_list', u''),\n\t\t\t\t\t\t\t\t'publish_dates': publish_status.get('publish_date_list', u''),\n\t\t\t\t\t\t\t\t})\n\t\t\tdb_conn.merge(item)\n\t\t\tif count % 500 == 0:\n\t\t\t\tdb_conn.commit()\n\t\t\t\tmylogger.info(\"merge data %s commit ...\" % count)\t\t\n\t\telse:\n\t\t\tins.imgs = imgs\n\t\t\tins.game_type = game_type\n\t\t\tins.summary = summary\n\t\t\tins.download_num = download_num\n\t\t\tins.comment_num = comment_num\n\t\t\tins.rating = rating\n\t\t\tins.pkg_size = pkg_size\n\t\t\tins.author = author\n\t\t\tins.version = version\n\t\t\tins.topic_num = topic_num_total\n\t\t\tins.channels = publish_status.get('channel_list', u'')\n\t\t\tins.publish_dates = publish_status.get('publish_date_list', u'')\n\t\t\tins.kc_list_ids = publish_status.get('kc_list_ids', u'')\n\t\t\tins.last_update = datetime.datetime.now()\n\tdb_conn.commit()\n\ndef get_publish_status(ids):\n\tout = {}\n\tl1 = []\n\tl2 = []\n\t_sql = \"select b.name,publish_date from (select * from kc_list where id in (%s)) a join channel b on a.source=b.id order by publish_date\" % \",\".join(ids)\n\tfor ret in db_conn.execute(_sql):\n\t\tchannel,publish_date = ret\n\t\tl1.append(publish_date)\n\t\tl2.append(channel)\n\tout['publish_date_list'] = \",\".join(l1)\n\tout['channel_list'] = \",\".join(l2)\n\tout['kc_list_ids'] = \",\".join(ids)\n\treturn out\n\ndef get_game_detail(ids):\n\timgs, game_type, summary, download_num, comment_num, rating, pkg_size, author, version, topic_num_total = [u''] * 10\n\t_sql = \"select max(dt) as dt, kc_id from game_detail_by_day where kc_id in (%s) group by kc_id\" % (\",\".join(ids))\n\tfor re in db_conn.execute(_sql):\n\t\tdt, kc_id = re\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.dt==dt).filter(GameDetailByDay.kc_id==kc_id).first()\n\t\tif ins is not None:\n\t\t\tif not imgs:\n\t\t\t\timgs = ins.imgs\n\t\t\tif not game_type:\n\t\t\t\tgame_type = ins.game_type\n\t\t\tif not summary:\n\t\t\t\tsummary = ins.summary\n\t\t\tif not download_num or download_num == u'0':\n\t\t\t\tdownload_num = ins.download_num\n\t\t\tif not comment_num or comment_num == u'0':\n\t\t\t\tcomment_num = ins.comment_num\n\t\t\tif not rating or rating == u'0':\n\t\t\t\trating = ins.rating\n\t\t\tif not pkg_size:\n\t\t\t\tsize = ins.pkg_size\n\t\t\t\tif ins.pkg_size and u'M' not in ins.pkg_size.upper() and u'G' not in ins.pkg_size.upper():\n\t\t\t\t\tsize = \"%sM\" % round(int(ins.pkg_size)/1024.0/1024.0, 2)\n\t\t\t\tpkg_size = size\n\t\t\tif not author:\n\t\t\t\tauthor = ins.author\n\t\t\tif not version:\n\t\t\t\tversion = ins.version\n\t\t\tif not topic_num_total or rating == u'0':\n\t\t\t\ttopic_num_total = ins.topic_num_total\n\treturn (imgs, game_type, summary, download_num, comment_num, rating, pkg_size, author, version, topic_num_total)\n\n\n\t#ids = (int(id) for id in ids)\n\t#for ret in db_conn.query(GameDetailByDay).filter(GameDetailByDay.dt==unicode(datetime.date.today()+datetime.timedelta(-1))).filter(GameDetailByDay.kc_id.in_(ids)):\n\t#\tprint ret.kc_id, ret.dt\n\t\t\ndef remove_duplicate_record():\n\tfor rt in db_conn.execute(\"select source,title, publish_date, count(1) from kc_list where source=0 group by source, title, publish_date having count(1)>1;\"):\n\t\tsource, title, publish_date, count = rt\n\t\tprint title, publish_date\n\t\tins = db_conn.execute(\"select min(id) from kc_list where source=%s and publish_date=\\'%s\\' and title=\\'%s\\'\" % (source, publish_date, title)).first()\n\t\tprint 'delete %s' % ins[0]\n\t\tdelete_record = db_conn.query(KC_LIST).filter(KC_LIST.id==ins[0]).one()\n\t\tdb_conn.delete(delete_record)\n\tdb_conn.commit()\n\n\ndef func():\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.title2!=u'').filter(KC_LIST.source.in_((7, 9, 10, 12, 14, 15, 25, 13, 16, 26, 27, 24))):\n\t\tret.game_id = ret.title2\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.title2!=u'').filter(KC_LIST.source.in_((4, 11, 28))):\n\t\tret.pkg_name = ret.title2\n\tdb_conn.commit()\n\nif __name__ == '__main__':\n\t#main()\n\t#print get_publish_status(['9247,13786,17106'])\n\t#get_game_detail(['12746','12747','12748'])\n\t#remove_duplicate_record()\n\tfunc()\n"
},
{
"alpha_fraction": 0.6311154365539551,
"alphanum_fraction": 0.6785714030265808,
"avg_line_length": 37.566036224365234,
"blob_id": "db2841aacbe225f0c49dc40bd5a609227ec33ee8",
"content_id": "78da1824c4926331e269e9ca974354647b8063ef",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 2138,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 53,
"path": "/r_project/rfm.R",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#! /usr/bin/env Rscript\n\nclusters <- 8\n#tt <- read.delim(\"/home/cyp/data_eye/r_project/test_set\", header=TRUE)\ntt <- read.delim(\"/home/cyp/data_eye/r_project/uid_payment_d30\", header=TRUE)\n#is_new <- tt$duration_d30==tt$duation\n#first_pay <- tt$payamount_d30==tt$payamount\nd <- data.frame(tt[, c(4,5,6)], row.names=tt$uid)\n#标准化处理\n\nkc <- kmeans(scale(d), clusters, iter.max = 20)\nrs <- data.frame(kc$cluster)\nmytable <- with(rs, table(rs$kc.cluster))\nmytable\nd <- cbind(d, tt[,2:3])\nd$duration_d30 <- round(d$duration_d30/60, digits = 2)\nd <- cbind(d, rs)\n#聚类结果可视化 \n#plot(scale(d)[,2:3], col = kc$cluster, pch = as.integer(d$kc.cluster))\n#不同的颜色代表不同的聚类结果,不同的形状代表训练数据集的原始分类情况。\n#points(kc$centers[,2:3], col = 1:10, pch = 8, cex=2)\npaytimes_d30 <- c()\npayamount_d30 <- c()\ndate_diff <- c()\nlogintimes_d30 <- c()\nduration_d30 <- c()\nR <- c()\nF <- c()\nM <- c()\ntotal <- c()\nfor (i in 1:clusters) {\n\tcls <- d[which(d$kc.cluster==i),]\n\tpaytimes_d30 <- append(paytimes_d30, round(median(cls$paytimes_d30), digits=0))\n\tpayamount_d30 <- append(payamount_d30, round(median(cls$payamount_d30), digits=2))\n\tdate_diff <- append(date_diff, round(median(cls$date_diff), digits=2))\n\tlogintimes_d30 <- append(logintimes_d30, round(median(cls$logintimes_d30), digits=0))\n\tduration_d30 <- append(duration_d30, round(median(cls$duration_d30), digits=2))\n\tR <- append(R, round(median(cls$date_diff) - median(d$date_diff), digits=0))\n\tF <- append(F, round(median(cls$paytimes_d30) - median(d$paytimes_d30), digits=0))\n\tM <- append(M, round(median(cls$payamount_d30) - median(d$payamount_d30), digits=2))\n\ttotal <- append(total, mytable[i])\n\tprint(paste(\"kcuster \", i, \" size \", nrow(cls), \"payment_sum\", sum(cls$payamount_d30)))\n\tprint(summary(cls))\n\t}\nprint(median(d$date_diff))\nprint(median(d$paytimes_d30))\nprint(median(d$payamount_d30))\nprint(median(d$logintimes_d30))\nprint(median(d$duration_d30))\nout <- data.frame(date_diff, paytimes_d30, payamount_d30, R, F, M, logintimes_d30, duration_d30, total)\nprint(out)\nwrite.table(out, \"rfm.txt\", sep=\"\\t\")\n##dev.off()\n"
},
{
"alpha_fraction": 0.56443852186203,
"alphanum_fraction": 0.5890478491783142,
"avg_line_length": 35.7842903137207,
"blob_id": "aecf7123700569a9e0d2df2576ac720dd9c52fb2",
"content_id": "47cc026233cb339e625756e9dd24457dce0bc726",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 59240,
"license_type": "no_license",
"max_line_length": 538,
"num_lines": 1604,
"path": "/spider/get_hot_game_detail_by_day.py",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#encoding=utf-8\n\nimport requests\nimport json\nimport re\nfrom bs4 import BeautifulSoup\nfrom time import sleep\nimport traceback\nfrom config import *\nimport random\nimport xmltodict\nimport datetime\n\ndb_conn = new_session()\nmylogger = get_logger('get_hot_game_detail')\n\nheaders = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36'}\n\nimport random\n\nclass T:\n\t\n\tdef __init__(self, status_code):\n\t\tself.status_code = status_code\n\nclass EX:\n\t\n\tmsg = \"\"\n\n\ndef get_9game_detail(channel_id):\n\tmylogger.info(\"get 9game detail start ...\")\n\tcount = 0\n\terror_times = 0\n\tsess = requests.session()\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where url!='' and dt!='' and source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(_sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, url = ret\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"9game reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\tp = proxies[random.randrange(len(proxies))]\n\t\t\t\tresponse = sess.get(url, timeout=15, proxies=p)\n\t\t\t\tif response.status_code == 200:\n\t\t\t\t\tcount += 1\n\t\t\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\t\t\tspec_pic = soup.find('div', class_='spec-pic')\n\t\t\t\t\timgs \t= u''\n\t\t\t\t\trating \t= u''\n\t\t\t\t\tgame_type = u''\n\t\t\t\t\tcomments_num = u''\n\t\t\t\t\ttopic_num_day = u''\n\t\t\t\t\ttopic_num_total = u''\n\t\t\t\t\tif spec_pic is not None:\n\t\t\t\t\t\timgs = u','.join([pic.find('img').get('src') for pic in spec_pic.find_all('span', class_='img')])\n\t\t\t\t\ttips = soup.find('div', class_='tips')\n\t\t\t\t\tsummary = tips.text.strip() if tips is not None else u''\n\t\t\t\t\tbbs = soup.find('li', class_='bbs')\n\t\t\t\t\tif bbs is not None:\n\t\t\t\t\t\tif bbs.find('a') is not None:\n\t\t\t\t\t\t\tinfo = get_9game_info_from_bbs(bbs.find('a').get('href'))\n\t\t\t\t\t\t\tif info is not None:\n\t\t\t\t\t\t\t\ttopic_num_day, topic_num_total = info\n\t\t\t\t\tscores = soup.find('div', class_='view-scroe1')\n\t\t\t\t\tif scores is not None:\n\t\t\t\t\t\trating = scores.find('div', class_='big-s').text\n\t\t\t\t\tp_des = soup.find('div', class_='p-des')\n\t\t\t\t\tif p_des is not None:\n\t\t\t\t\t\tif p_des.find('p') is not None:\n\t\t\t\t\t\t\tcontent = re.sub(u'\\r| |\\xa0', u'', p_des.find('p').text)\n\t\t\t\t\t\t\tfor seg in content.split('\\n'):\n\t\t\t\t\t\t\t\tif u'类型' in seg:\n\t\t\t\t\t\t\t\t\tif len(seg.split(u':')) == 2:\n\t\t\t\t\t\t\t\t\t\tgame_type = seg.split(u':')[1].strip()\n\t\t\t\t\t\t\t\telif u'评论' in seg:\n\t\t\t\t\t\t\t\t\tm = re.search('\\d+', seg)\n\t\t\t\t\t\t\t\t\tcomments_num = m.group() if m is not None else u''\n\n\t\t\t\t\titem = HotGameDetailByDay(**{'channel': channel_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'name' : name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : imgs,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'summary' : summary,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'game_type' : game_type,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'topic_num_total' : topic_num_total,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'rating' : rating ,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'comment_num' : comments_num,\n\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\tif count % 50 == 0:\n\t\t\t\t\t\tsleep(3)\n\t\t\t\t\t\tmylogger.info(\"9game detail commit %s\" % count)\n\t\t\t\t\t\tdb_conn.commit()\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"%s\\t%s\" % (url.encode('utf-8'), traceback.format_exc()))\n\n\tmylogger.info(\"get 9game detail %s\" % count)\n\tdb_conn.commit()\n\ndef get_9game_info_from_bbs(url):\n\ttry:\n\t\tp = proxies[random.randrange(len(proxies))]\n\t\tresponse = requests.get(url, timeout=10, proxies=p)\n\t\tif response.status_code == 200:\n\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\ttopics = soup.find('span', 'xs1 xw0 i')\t\n\t\t\tif topics is not None:\n\t\t\t\tnums = topics.find_all('strong')\n\t\t\t\tif len(nums) == 2:\n\t\t\t\t\ttoday_nums, total_nums = [i.text for i in nums]\n\t\t\t\t\treturn today_nums, total_nums\n\texcept Exception,e:\n\t\tmylogger.error(\"%s 9game bbs \\t%s\" % (url.encode('utf-8'), traceback.format_exc()))\n\treturn None\n\n\ndef get_18183_detail(channel_id):\n\tmylogger.info(\"get 18183 detail start ...\")\n\tcount = 0 \n\terror_times = 0\n\tsess = requests.session()\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(_sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, url = ret\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"18183 reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\tresponse = sess.get(url, timeout=10, proxies=p)\n\t\t\t\tcount += 1\n\t\t\t\ttopic_num_total = u''\n\t\t\t\tgame_type = u''\n\t\t\t\tpkg_size = u''\n\t\t\t\tsummary = u''\n\t\t\t\timgs = u''\n\t\t\t\tr = response.text.encode('ISO-8859-1').decode('utf-8')\n\t\t\t\tsoup = BeautifulSoup(r)\n\t\t\t\tfor li1 in soup.find_all('li', class_='li1'):\n\t\t\t\t\tcodes = li1.find_all('code')\n\t\t\t\t\tspans = li1.find_all('span')\n\t\t\t\t\tfor i in xrange(len(codes)):\n\t\t\t\t\t\tif codes[i].text == u'类型:':\n\t\t\t\t\t\t\tgame_type = spans[i].text.strip()\n\t\t\t\t\t\tif codes[i].text == u'关注:':\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\trs = requests.get(spans[i].find('script').get('src'))\n\t\t\t\t\t\t\t\tif rs.status_code == 200:\n\t\t\t\t\t\t\t\t\tm = re.search('\\d+', rs.text)\n\t\t\t\t\t\t\t\t\tif m is not None:\n\t\t\t\t\t\t\t\t\t\ttopic_num_total = m.group()\n\t\t\t\t\t\t\texcept Exception,e:\n\t\t\t\t\t\t\t\tmylogger.error(\"18183 topic page error and sleep 3s %s\" % (traceback.format_exc()))\n\t\t\t\t\t\t\t\tsleep(3)\n\t\t\t\tdwnli = soup.find('li', class_='dwnli')\n\t\t\t\tif dwnli is not None:\n\t\t\t\t\tif dwnli.find('p') is not None:\n\t\t\t\t\t\tif dwnli.find('p') is not None:\n\t\t\t\t\t\t\tpkg_size = dwnli.find('p').text.split(u':')[1]\n\t\t\t\tjianjie_txt = soup.find('div', class_='jianjie_txt')\n\t\t\t\tif jianjie_txt is not None:\n\t\t\t\t\tsummary = jianjie_txt.text.strip()\n\t\t\t\ttabcen_ul = soup.find('ul', class_='tabcen_ul')\n\t\t\t\tif tabcen_ul is not None:\n\t\t\t\t\ticons = []\n\t\t\t\t\tfor ss_body in tabcen_ul.find_all('li', class_='ss_body'):\n\t\t\t\t\t\tif ss_body.find('img') is not None:\n\t\t\t\t\t\t\ticons.append(ss_body.find('img').get('src'))\n\t\t\t\t\tif icons:\n\t\t\t\t\t\timgs = u\",\".join(icons)\n\t\t\t\titem = HotGameDetailByDay(**{'channel': channel_id,\n\t\t\t\t\t\t\t\t\t\t\t\t'name' : name,\n\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : imgs,\n\t\t\t\t\t\t\t\t\t\t\t\t'summary' : summary,\n\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : pkg_size,\n\t\t\t\t\t\t\t\t\t\t\t\t'game_type' : game_type,\n\t\t\t\t\t\t\t\t\t\t\t\t'topic_num_total' : topic_num_total,\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\t\t\t\tif count % 100 == 0:\n\t\t\t\t\tsleep(3)\n\t\t\t\t\tmylogger.info(\"18183 detail commit %s\" % count)\n\t\t\t\t\tdb_conn.commit()\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"%s\\t%s\" % (url.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get 18183 detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_appicsh_detail(channel_id):\n\tmylogger.info(\"get appicsh detail start ...\")\n\tcount = 0\n\terror_times = 0\n\tsess = requests.session()\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(_sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, pkg = ret\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"appicsh reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\turl = \"http://m5.qq.com/app/getappdetail.htm?pkgName=%s&sceneId=0\" % pkg.split('\\t')[0]\n\t\t\t\tr = sess.get(url, timeout=10)\n\t\t\t\tif r.status_code == 200:\n\t\t\t\t\td = r.json()\n\t\t\t\t\tif d['obj'] is not None and d['obj']['appInfo'] is not None:\n\t\t\t\t\t\tappinfo = d['obj']['appInfo']\n\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\tpublishtime = appinfo.get('apkPublishTime', u\"\")\n\t\t\t\t\t\tupdate_time = unicode(datetime.date.fromtimestamp(publishtime)) if publishtime else u\"\"\n\n\t\t\t\t\t\titem = HotGameDetailByDay(**{'name': name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'channel' : channel_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join([i for i in appinfo['screenshots']]),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'summary' : appinfo.get('description', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : appinfo.get('fileSize', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'version' : appinfo.get('versionName', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'rating' : appinfo.get('averageRating', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'download_num' : appinfo.get('appDownCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'author' : appinfo.get('authorName', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'update_time' : update_time\n\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\t\tif count % 100 == 0:\n\t\t\t\t\t\t\tdb_conn.commit()\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"%s\\t%s\" % (pkg.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get appicsh detail %s\" % count)\n\tdb_conn.commit()\n\t\t\t\n\ndef get_xiaomi_game_detail(channel_id):\n\tcount = 0\n\txiaomi_app_map = get_xiaomi_app_list()\n\tmylogger.info(\"get xiaomi_game rank detail start ...\")\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(\"### %s ###\" % _sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, pkg_name = ret\n\t\tif pkg_name in xiaomi_app_map:\n\t\t\tdt = unicode(datetime.date.today())\n\t\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\t\tif not ins:\n\t\t\t\tg = xiaomi_app_map.get(pkg_name)\n\t\t\t\tif g is not None:\n\t\t\t\t\tcount += 1\n\t\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t\t'channel': channel_id,\n\t\t\t\t\t\t\t\t\t\t\t\t'name': name,\n\t\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('introduction', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'author' : g.get('publisherName', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get('className', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'version' : g.get('versionName', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'rating' : g.get('ratingScore', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('downloadCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('apkSize' u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join([i.get('url') for i in g['screenShot']]),\n\t\t\t\t\t\t\t\t\t\t\t\t'topic_num_total' : g.get('ratingCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\tdb_conn.merge(item)\n\tmylogger.info(\"get xiaomi game detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_xiaomi_app_list():\n\tmydict = {}\n\txiaomi_app_download = \"http://app.migc.xiaomi.com/cms/interface/v5/rankgamelist1.php?uid=20150905_132380697&platform=android&os=V6.7.1.0.KXDCNCH&stampTime=1449557687000&density=480&imei=865931027730878&pageSize=50&versionCode=1822&cid=gamecenter_100_1_android%7C865931027730878&clientId=40b53f3e316bda9f83c2e0c094d5b7f6&vn=MIGAMEAPPSTAND_1.8.22&co=CN&page=1&macWifi=3480B34D6987&la=zh&ua=Xiaomi%257CMI%2B4LTE%257C4.4.4%257CKTU84P%257C19%257Ccancro&carrier=unicom&rankId=17&mnc=46001&fuid=&mid=&imsi=460015776509846&sdk=19&mac3g=&bid=701\"\n\txiaomi_app_hot = \"http://app.migc.xiaomi.com/cms/interface/v5/rankgamelist1.php?uid=20150905_132380697&platform=android&os=V6.7.1.0.KXDCNCH&stampTime=1449557980000&density=480&imei=865931027730878&pageSize=50&versionCode=1822&cid=gamecenter_100_1_android%7C865931027730878&clientId=40b53f3e316bda9f83c2e0c094d5b7f6&vn=MIGAMEAPPSTAND_1.8.22&co=CN&page=1&macWifi=3480B34D6987&la=zh&ua=Xiaomi%257CMI%2B4LTE%257C4.4.4%257CKTU84P%257C19%257Ccancro&carrier=unicom&rankId=18&mnc=46001&fuid=&mid=&imsi=460015776509846&sdk=19&mac3g=&bid=701\"\n\ttry:\n\t\tfor url in [xiaomi_app_download, xiaomi_app_hot]:\n\t\t\tr = requests.get(url)\n\t\t\tif r.status_code == 200:\n\t\t\t\tj = r.json()\n\t\t\t\tfor game in j['gameList']:\n\t\t\t\t\tpackageName = game.get('packageName', u'')\n\t\t\t\t\tif packageName:\n\t\t\t\t\t\tmydict[packageName] = game\n\texcept Exception,e:\n\t\tmylogger.error(\"get xiaomi app list\\t%s\" % (traceback.format_exc()))\n\treturn mydict\n\n\t\t\t\t\t\t\t\n\ndef get_open_play_detail(channel_id):\n\tcount = 0\n\terror_times = 0\n\tsess = requests.session()\n\tmylogger.info(\"get open play detail start ...\")\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(\"### %s ###\" % _sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, url = ret\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"open play detail reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\tresponse = sess.get(url, timeout=10)\n\t\t\t\tif response.status_code == 200:\n\t\t\t\t\td = response.json()\n\t\t\t\t\tif d.get('text', u'') == u'success':\n\t\t\t\t\t\tcount += 1 \n\t\t\t\t\t\tg = d['ext']['game_detail']\n\t\t\t\t\t\ttopic_num_total = u''\n\t\t\t\t\t\tref_vote_info = d['ext']['ref_vote_info']\n\t\t\t\t\t\tif ref_vote_info['vote_state'] == 1:\n\t\t\t\t\t\t\ttopic_num_total = ref_vote_info['vote_up_count'] + ref_vote_info['vote_dn_count']\n\t\t\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t\t\t'channel': channel_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'name': name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('game_introduction', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'author' : g.get('cp_name', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get('game_class', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'version' : g.get('version', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('game_download_count', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('game_size' u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g['game_view_images']),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'topic_num_total' : topic_num_total,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\t\tif count % 100 == 0:\n\t\t\t\t\t\t\tsleep(3)\n\t\t\t\t\t\t\tmylogger.info(\"open play detail commit %s\" % count)\n\t\t\t\t\t\t\tdb_conn.commit()\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"%s\\t%s\" % (url.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get open play detail %s\" % count)\n\tdb_conn.commit()\n\ndef get_vivo_detail(channel_id):\n\tcount = 0\n\terror_times = 0\n\tsess = requests.session()\n\tmylogger.info(\"get vivo detail start ...\")\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where url!='' and dt!='' and source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(_sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, pkg = ret\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"vivo reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\tdetail_url = \"http://info.gamecenter.vivo.com.cn/clientRequest/gameDetail?id=%s&adrVerName=4.4.4&appVersion=37\" % pkg.split('\\t')[1]\n\t\t\t\tr = sess.get(detail_url, timeout=10)\n\t\t\t\tif r.status_code == 200:\n\t\t\t\t\td = r.json()\n\t\t\t\t\tif d is not None and 'result' in d and d['result']:\n\t\t\t\t\t\tg = d.get('game')\n\t\t\t\t\t\tif g is not None:\n\t\t\t\t\t\t\tcount += 1 \n\t\t\t\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t\t\t'channel': channel_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'name': name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('desc', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'rating' : g.get('comment', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'author' : g.get('gameDeveloper', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get('type', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'version' : g.get('versonName', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('download', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'comment_num' : g.get('commentNum', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('size' u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'update_time' : g.get('date', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g['screenshot'].split(u'###')),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"%s\\t%s\" % (pkg.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get vivo play detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_coolpad_detail(channel_id):\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get coolpad detail start ...\")\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(\"### %s ###\" % _sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, pkg = ret\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"coolpad reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\tg = get_coolpad_detail_by_id(pkg.split('\\t')[1])\n\t\t\tif isinstance(g, EX):\n\t\t\t\terror_times += 1\n\t\t\telif g is not None:\n\t\t\t\tcount += 1 \n\t\t\t\timgs = u''\n\t\t\t\tif g['pics'] is not None and g['pics']['picurl'] is not None:\n\t\t\t\t\timgs = u','.join([i for i in g['pics']['picurl'] if i is not None])\n\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t'name': name,\n\t\t\t\t\t\t\t\t\t\t\t'channel': channel_id,\n\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('summary', u''),\n\t\t\t\t\t\t\t\t\t\t\t'rating' : g.get('score', u''),\n\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get('levelname', u''),\n\t\t\t\t\t\t\t\t\t\t\t'version' : g.get('version', u''),\n\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('downloadtimes', u''),\n\t\t\t\t\t\t\t\t\t\t\t'comment_num' : g.get('commcount', u''),\n\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('size' u''),\n\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t'imgs' : imgs,\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\tmylogger.info(\"get coolpad detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_coolpad_detail_by_id(resid):\n\turl = \"http://gamecenter.coolyun.com/gameAPI/API/getDetailResInfo?key=0\"\n\traw_data = \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<request username=\"\" cloudId=\"\" openId=\"\" sn=\"865931027730878\" platform=\"1\" platver=\"19\" density=\"480\" screensize=\"1080*1920\" language=\"zh\" mobiletype=\"MI4LTE\" version=\"4\" seq=\"0\" appversion=\"3350\" currentnet=\"WIFI\" channelid=\"coolpad\" networkoperator=\"46001\" simserianumber=\"89860115851040101064\">\n <resid>%s</resid>\n</request>\"\"\" % resid\n\ttry:\n\t\tr = requests.post(url, data=raw_data, headers={'Content-Type': 'application/xml'})\n\t\tif r.status_code == 200:\n\t\t\tt = re.sub(u'\\r|\\n', '', r.text)\n\t\t\tdoc = xmltodict.parse(t)\n\t\t\td = doc['response']['reslist']['res']\n\t\t\tif d['@rid'] != u'':\n\t\t\t\treturn d\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (resid.encode('utf-8'), traceback.format_exc()))\n\t\treturn EX()\n\treturn None\n\ndef get_gionee_detail(channel_id):\n\tcount = 0\n\terror_times = 0\n\tsess = requests.session()\n\tmylogger.info(\"get gionee detail start ...\")\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(\"### %s ###\" % _sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, pkg = ret\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"gionee reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\t_url = u\"http://game.gionee.com/Api/Local_Gameinfo/getDetails?gameId=%s\" % pkg.split('\\t')[1]\n\t\t\t\tr = sess.get(_url, timeout=10)\n\t\t\t\tif r.status_code == 200:\n\t\t\t\t\td = r.json()\n\t\t\t\t\tif d['success']:\n\t\t\t\t\t\tg = d['data']\n\t\t\t\t\t\tcount += 1 \n\t\t\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t\t\t'name': name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'channel': channel_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'rating' : g.get('score', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('downloadCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'author' : g.get('publisher', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get('category', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'version' : g.get('versionName', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('fileSize' u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g['bannerList']['fullPicture']),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"%s\\t%s\" % (pkg.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get gionee play detail %s\" % count)\n\tdb_conn.commit()\n\n\n\ndef get_leveno_detail():\n\tcount = 0\n\terror_times = 0\n\tsess = requests.session()\n\tmylogger.info(\"get lenovo detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.title2!=u'').filter(KC_LIST.source==11):\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"leveno reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.kc_id==ret.id).filter(HotGameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\t_url = u\"http://yx.lenovomm.com/business/app!getAppDetail5.action?dpi=480&height=1920&dev=ph&width=1080&cpu=armeabi-v7a&pn=%s&uid=72DB07100FC223A2EDE82F4A44AE96B4&os=4.4.4&perf=hp&model=MI 4LTE&type=0&density=xx&mac=7A031DAB40535B3F5E204582EB961FC5\" % ret.title2\n\t\t\ttry:\n\t\t\t\tp = proxies[random.randrange(len(proxies))]\n\t\t\t\tr = sess.get(_url, timeout=10, proxies=p)\n\t\t\t\tif r.status_code == 200:\n\t\t\t\t\td = r.json()\n\t\t\t\t\tif 'app' in d:\n\t\t\t\t\t\tg = d['app']\n\t\t\t\t\t\tcount += 1 \n\t\t\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'rating' : g.get('averageStar', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get('categoryName', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'version' : g.get('version', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('size' u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('downloadCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('description', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : g['snapList'],\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\texcept Exception,e:\n\t\t\t\tsleep(1.23)\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"%s\\t%s\" % (_url.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get lenovo detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_iqiyi_detail(channel_id):\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get iqiyi detail start ...\")\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(\"### %s ###\" % _sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, qipu_id = ret\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"iqiyi reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\td = get_iqiyi_detail_by_id(qipu_id)\n\t\t\tif isinstance(d, EX):\n\t\t\t\terror_times += 1\n\t\t\telif d is not None:\n\t\t\t\tg = d['app']\n\t\t\t\tcount += 1 \n\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t'channel': channel_id,\n\t\t\t\t\t\t\t\t\t\t\t'name': name,\n\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('desc', u''),\n\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get('cate_name', u''),\n\t\t\t\t\t\t\t\t\t\t\t'version' : g.get('version', u''),\n\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('cnt', u''),\n\t\t\t\t\t\t\t\t\t\t\t'author' : g.get('author', u''),\n\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('l_size' u''),\n\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t'imgs' : u\",\".join([i.get('full_img', u'') for i in d['medias']]),\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\tmylogger.info(\"get iqiyi detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_iqiyi_detail_by_id(qipu_id):\n\turl = \"http://store.iqiyi.com/gc/game/detail?callback=rs&id=%s\" % qipu_id\n\ttry:\n\t\tr = requests.get(url)\n\t\tif r.status_code == 200:\n\t\t\tm = re.search(u'rs\\\\(([\\s\\S]*)\\\\)\\\\;', r.text)\n\t\t\tif m is not None:\n\t\t\t\treturn json.loads(m.group(1))\n\texcept Exception, e:\n\t\tmylogger.error(\"### %s ###\\t%s\" % (qipu_id.encode('utf-8'), traceback.format_exc()))\n\t\treturn EX()\n\treturn None\n\ndef get_sogou_detail(channel_id):\n\tcount = 0\n\terror_times = 0\n\tsess = requests.session()\n\tmylogger.info(\"get sogou detail start ...\")\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(\"### %s ###\" % _sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, pkg = ret\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"sogou reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\t_url = u\"http://mobile.zhushou.sogou.com/m/appDetail.html?id=%s\" % pkg.split('\\t')[1]\n\t\t\t\tr = sess.get(_url, timeout=10)\n\t\t\t\tif r.status_code == 200:\n\t\t\t\t\td = r.json()\n\t\t\t\t\tg = d['ainfo']\n\t\t\t\t\tcount += 1 \n\t\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t\t'name': name,\n\t\t\t\t\t\t\t\t\t\t\t\t'channel': channel_id,\n\t\t\t\t\t\t\t\t\t\t\t\t'rating' : g.get('score', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('desc', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'version' : g.get('vn', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'game_type' : d['tgroup'].get('name', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('dc', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'author' : g.get('author', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('size' u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : u\",\".join([i.get('url', u'') for i in d['images']]),\n\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\tdb_conn.merge(item)\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"%s\\t%s\" % (pkg.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get sogou detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_dangle_detail(channel_id):\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get dangle detail start ...\")\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(\"### %s ###\" % _sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, url = ret\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"dangle reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\tresourceType, gid = url.split('\\t')\n\t\t\tg = get_dangle_detail_by_id(resourceType, gid)\n\t\t\tif isinstance(g, EX):\n\t\t\t\terror_times += 1\n\t\t\telif g is not None:\n\t\t\t\tcount += 1 \n\t\t\t\tpackageTOs = {}\n\t\t\t\tif 'packageTOs' in g:\n\t\t\t\t\tpackageTOs = g['packageTOs'][0] if g['packageTOs'] else {}\n\t\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t\t'channel': channel_id,\n\t\t\t\t\t\t\t\t\t\t\t\t'name': name,\n\t\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('description', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get('categoryName', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'version' : packageTOs.get('versionName', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'rating' : g.get('score', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'comment_num' : g.get('commentCnt', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'topic_num_total' : g.get('grade', {}).get('personCnt', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('appInstalledCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'author' : g.get('author', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : packageTOs.get('fileSize', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g['snapshotUrls']),\n\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\tdb_conn.merge(item)\n\tmylogger.info(\"get dangle detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_dangle_detail_by_id(resourceType, gid):\n\tpayload = {'id': gid, 'resourceType': resourceType}\n\turl = \"http://api2014.digua.d.cn/newdiguaserver/res/detail\"\n\t#url = \"http://api2014.digua.d.cn/newdiguaserver/res/detail?id=%s&resourceType=5\"% gid\n\theaders = {\"HEAD\": {\n \"stamp\":1447747218496,\n \"verifyCode\":\"78492ba9e8569f3b9d9173ac4e4b6cb9\",\n \"it\":2,\n \"resolutionWidth\":1080,\n \"imei\":\"865931027730878\",\n \"clientChannelId\":\"100327\",\n \"versionCode\":750,\n \"mac\":\"34:80:b3:4d:69:87\",\n \"vender\":\"Qualcomm\",\n \"vp\":\"\",\n \"version\":\"7.5\",\n \"sign\":\"cfd1b8d1b60f85c4\",\n \"dd\":480,\n \"sswdp\":\"360\",\n \"hasRoot\":0,\n \"glEsVersion\":196608,\n \"device\":\"MI_4LTE\",\n \"ss\":2,\n \"local\":\"zh_CN\",\n \"language\":\"2\",\n \"sdk\":19,\n \"resolutionHeight\":1920,\n \"osName\":\"4.4.4\",\n \"gpu\":\"Adreno (TM) 330\"\n\t}}\n\ttry:\n\t\tr = requests.post(url, data=payload, headers=headers, timeout=20)\n\t\tif r.status_code == 200:\n\t\t\td = r.json()\n\t\t\treturn d\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (url, traceback.format_exc()))\n\t\treturn EX()\n\treturn None\n\ndef get_muzhiwan_detail():\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get muzhiwan detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.url!=u'').filter(KC_LIST.source==17):\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"muzhiwan reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.kc_id==ret.id).filter(HotGameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\tg = get_muzhiwan_detail_by_id(ret.url)\n\t\t\tif g:\n\t\t\t\t#m = re.search(u'(\\d+)个', g.get(u'评论数', u''))\n\t\t\t\t#comment_num = m.group(1) if m is not None else u''\n\t\t\t\tcount += 1 \n\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('description', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'version' : g.get(u'版本', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get(u'分类', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'comment_num' : g.get('comments', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get(u'大小' u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g.get('imgs', [])),\n\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\t\t\t\tif count % 100 == 0:\n\t\t\t\t\tsleep(1.23)\n\t\t\t\t\tmylogger.info(\"muzhiwan detail %s commit ... \" % count)\n\t\t\tif 'ex_msg' in g:\n\t\t\t\terror_times += 1\n\tmylogger.info(\"get muzhiwan detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_muzhiwan_comment_by_gid(gid):\n\ttry:\n\t\turl = u'http://www.muzhiwan.com/index.php?action=game&opt=readHit&gid=%s' % gid\n\t\tr = requests.get(url)\n\t\tif r.status_code == 200:\n\t\t\treturn r.text\n\texcept Exception,e:\n\t\tmylogger.error(\"get muzhiwan comments %s\\t%s\" % (url, traceback.format_exc()))\n\treturn None\n\ndef get_muzhiwan_detail_by_id(url):\n\tmydict = {}\n\ttry:\n\t\tresponse = requests.get(url, timeout=10)\n\t\tsoup = BeautifulSoup(response.text)\n\t\tinfo = soup.find('div', class_='detail_info')\n\t\tgid = soup.find('input', id='gid')\n\t\tif gid is not None:\n\t\t\tcomments = get_muzhiwan_comment_by_gid(gid.get('value'))\n\t\t\tif comments is not None:\n\t\t\t\tmydict['comments'] = comments\n\t\tif info is not None:\n\t\t\tfor ret in info.find('div', class_='clearfix').find_all('li'):\n\t\t\t\tsegs = ret.text.split(u':')\n\t\t\t\tif len(segs) == 2:\n\t\t\t\t\tmydict[segs[0]] = segs[1]\n\t\timgs = soup.find('div', class_=\"img_screen\")\t\n\t\tif imgs is not None:\n\t\t\tmydict['imgs'] = [i.find('img').get('src') for i in imgs.find_all('li')]\n\t\tsummary = soup.find('p', itemprop=\"description\")\n\t\tif summary is not None:\n\t\t\tmydict['description'] = summary.text\n\texcept Exception,e:\n\t\tmydict = {'ex_msg': u'Exception'}\n\t\tmylogger.error(\"%s\\t%s\" % (url, traceback.format_exc()))\n\treturn mydict\n\n\ndef get_huawei_detail():\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get huawei detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.url!=u'').filter(KC_LIST.source==18):\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"huawei reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.kc_id==ret.id).filter(HotGameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\tg = get_huawei_detail_by_id(ret.url)\n\t\t\tif 'ex_msg' in g:\n\t\t\t\terror_times += 1\n\t\t\tif g:\n\t\t\t\tcount += 1 \n\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('description', u''),\n\t\t\t\t\t\t\t\t\t\t\t'version' : g.get(u'版本', u''),\n\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get(u'分类', u''),\n\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('download_num', u''),\n\t\t\t\t\t\t\t\t\t\t\t'comment_num' : g.get('comment_num', u''),\n\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get(u'大小', u''),\n\t\t\t\t\t\t\t\t\t\t\t'author' : g.get('author', u''),\n\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g.get('imgs', [])),\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\t\t\t\tif count % 100 == 0:\n\t\t\t\t\tmylogger.info(\"huawei detail commit %s\" % count)\n\t\t\t\t\tdb_conn.commit()\n\tmylogger.info(\"get huawei detail %s\" % count)\n\tdb_conn.commit()\n\ndef get_huawei_detail_by_id(url):\n\tmydict = {}\n\ttry:\n\t\tp = proxies[random.randrange(len(proxies))]\n\t\tresponse = requests.get(url, timeout=20, proxies=p)\n\t\tsoup = BeautifulSoup(response.text)\n\t\tfor d in soup.find_all('li', class_='ul-li-detail'):\n\t\t\tif u'开发者:' in d.text:\n\t\t\t\tmydict['author'] = d.find('span').get('title')\n\t\t\telse:\n\t\t\t\tsegs = d.text.split(u':')\n\t\t\t\tif len(segs) == 2:\n\t\t\t\t\tmydict[segs[0]] = segs[1]\n\t\tinfo = soup.find('ul', class_='app-info-ul nofloat')\n\t\tif info is not None:\n\t\t\tlis = info.find_all('li')\n\t\t\tif len(lis) >= 2:\n\t\t\t\tdownload_li = lis[1]\n\t\t\t\tdownload_span = download_li.find('span', class_='grey sub')\n\t\t\t\tif download_span is not None:\n\t\t\t\t\tm = re.search('\\d+', download_span.text)\n\t\t\t\t\tif m is not None:\n\t\t\t\t\t\tmydict['download_num'] = m.group()\n\t\timgs = soup.find('ul', class_=\"imgul\")\t\n\t\tif imgs is not None:\n\t\t\tmydict['imgs'] = [i.find('img').get('src') for i in imgs.find_all('li')]\n\t\tsummary = soup.find('div', id=\"app_strdesc\")\n\t\tif summary is not None:\n\t\t\tmydict['description'] = summary.text\n\t\tcomment_list = soup.find('div', id='comment_list')\n\t\tif comment_list is not None:\n\t\t\tcomment = comment_list.find('span', class_='title')\n\t\t\tif comment is not None:\n\t\t\t\tm = re.search('\\d+', comment.text)\n\t\t\t\tif m is not None:\n\t\t\t\t\tmydict['comment_num'] = m.group()\n\texcept Exception,e:\n\t\tmydict = {'ex_msg': u'Exception'}\n\t\tmylogger.error(\"%s\\t%s\" % (url, traceback.format_exc()))\n\t\tsleep(5)\n\treturn mydict\n\ndef get_kuaiyong_detail(channel_id):\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get kuaiyong detail start ...\")\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(\"### %s ###\" % _sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, url = ret\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"kuaiyong reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\tg = get_kuaiyong_detail_by_id(url)\n\t\t\tif isinstance(g, EX):\n\t\t\t\terror_times += 1\n\t\t\telif g:\n\t\t\t\tcount += 1 \n\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t'channel': channel_id,\n\t\t\t\t\t\t\t\t\t\t\t'name': name,\n\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('description', u''),\n\t\t\t\t\t\t\t\t\t\t\t'version' : g.get(u'版 本', u''),\n\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get(u'类 别', u''),\n\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get(u'大 小', u''),\n\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get(u'下载', u''),\n\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t'rating' : g.get('rating', u''),\n\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g.get('imgs', [])),\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\t\t\t\tif count % 100 == 0:\n\t\t\t\t\tmylogger.info(\"kuaiyong detail commit %s\" % count)\n\t\t\t\t\tdb_conn.commit()\n\tmylogger.info(\"get kuaiyong detail %s\" % count)\n\tdb_conn.commit()\n\ndef get_kuaiyong_detail_by_id(URL):\n\tmydict = {}\n\ttry:\n\t\tresponse = requests.get(URL, timeout=10)\n\t\tsoup = BeautifulSoup(response.text)\n\t\tbase_right = soup.find('div', class_='base-right')\n\t\tmydict = {}\n\t\tif base_right is not None:\n\t\t\tif base_right.find('h1') is not None:\n\t\t\t\tmydict[u'title'] = base_right.find('h1').text\n\t\t\tbase_list = base_right.find('div', class_='base-list')\n\t\t\tif base_list is not None:\n\t\t\t\tfor ret in base_list.find_all('p'):\n\t\t\t\t\tif ret.text:\n\t\t\t\t\t\tsegs = ret.text.split(u':')\n\t\t\t\t\t\tif len(segs) == 2:\n\t\t\t\t\t\t\tmydict[segs[0]] = segs[1]\n\t\t\t\t\t\telif len(segs)==1 and u'次下载' in ret.text:\n\t\t\t\t\t\t\tmydict[u'下载'] = re.sub(u'次下载|\\n|\\r', u'', ret.text)\n\t\t\t\tapp_star = base_list.find('p', class_='app-star') \n\t\t\t\tif app_star is not None:\n\t\t\t\t\tmydict['rating'] = len(app_star.find_all('span', class_='highlight'))\n\t\tdetail = soup.find('div', class_='detail')\n\t\tif detail is not None:\n\t\t\tpreview_contents = detail.find('div', class_='preview-content')\n\t\t\tif preview_contents is not None:\n\t\t\t\tmydict['imgs'] = [p.get('src') for p in preview_contents.find_all('img')]\n\t\tdetail_content = soup.find('div', class_='detail-content-inner')\n\t\tif detail_content is not None:\n\t\t\tmydict['description'] = detail_content.text\n\texcept Exception,e:\n\t\tsleep(1.21)\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\t\treturn EX()\n\treturn mydict\n\n\ndef get_anzhi_detail():\n\tcount = 0\n\tmylogger.info(\"get kuaiyong detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.url!=u'').filter(KC_LIST.source==19):\n\t\tcount += 1 \n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.kc_id==ret.id).filter(HotGameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\tg = get_anzhi_detail_by_id(ret.url)\n\t\t\tif g:\n\t\t\t\tdt = unicode(datetime.date.today())\n\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t'summary' : g.get('description', u''),\n\t\t\t\t\t\t\t\t\t'version' : g.get(u'版 本', u''),\n\t\t\t\t\t\t\t\t\t'game_type' : g.get(u'类 别', u''),\n\t\t\t\t\t\t\t\t\t'pkg_size' : g.get(u'大 小', u''),\n\t\t\t\t\t\t\t\t\t'download_num' : g.get(u'下载', u''),\n\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t'rating' : g.get('rating', u''),\n\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g.get('imgs', [])),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\tdb_conn.merge(item)\n\t\t\tif count % 100 == 0:\n\t\t\t\tmylogger.info(\"kuaiyong detail commit %s\" % count)\n\t\t\t\tdb_conn.commit()\n\tmylogger.info(\"get kuaiyong detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_anzhi_detail_by_id(URL):\n\tmydict = {}\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\t\tresponse = T(404)\n\tif response.status_code == 200:\n\t\tsoup = BeautifulSoup(response.text)\n\t\tdetail_icon = soup.find('div', class_='detail_icon')\n\t\tif detail_icon is not None:\n\t\t\timg_div = detail_icon.find('img')\n\t\t\tif img_div is not None:\n\t\t\t\tmydict['img'] = u\"http://www.anzhi.com%s\" % img_div.get('src')\n\t\tdetail_line_ul = soup.find('ul', id='detail_line_ul')\n\t\tif detail_line_ul is not None:\n\t\t\tfor li in detail_line_ul.find_all('li'):\n\t\t\t\tsegs = li.text.split(u':')\n\t\t\t\tif len(segs) == 2:\n\t\t\t\t\tmydict[segs[0]] = segs[1]\n\t\tstars_detail = soup.find('div', id='stars_detail')\n\t\tif stars_detail is not None:\n\t\t\tm = re.search('(\\d+)px', stars_detail.get('style'))\n\t\t\tif m is not None:\n\t\t\t\tmydict['rating'] = round(m.group(1)/30.0, 1)\n\t\tapp_detail_infor = soup.find('div', class_='app_detail_infor')\n\t\tif app_detail_infor is not None:\n\t\t\tmydict['description'] = app_detail_infor.text.strip()\n\t\tsection_body = soup.find('div', class_='section-body')\n\t\tif section_body is not None:\n\t\t\tmydict['imgs'] = [u\"http://www.anzhi.com%s\" % i.get('src') for i in section_body.find_all('img')]\n\treturn mydict\n\ndef get_wandoujia_detail(channel_id):\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get wandoujia detail start ...\")\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(\"### %s ###\" % _sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, url = ret\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"wandoujia reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\tr = requests.get(url, timeout=10)\n\t\t\t\tif r.status_code == 200:\n\t\t\t\t\td = r.json()\n\t\t\t\t\tif d['entity'] is not None and len(d['entity'])>=1:\n\t\t\t\t\t\tg = d['entity'][0]['detail']['appDetail']\n\t\t\t\t\t\tcount += 1 \n\t\t\t\t\t\tcategories = g.get('categories', [])\n\t\t\t\t\t\tgame_type = u\",\".join([c['name'] for c in categories if c['level']==2])\n\t\t\t\t\t\tapk = {}\n\t\t\t\t\t\tapk_list = g.get('apk', [])\n\t\t\t\t\t\tif len(apk_list) >= 1:\n\t\t\t\t\t\t\tapk = apk_list[0]\n\t\t\t\t\t\tdeveloper = g.get('developer', {})\n\t\t\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t\t\t'name': name,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'channel': channel_id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('description', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'version' : apk.get('versionName', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'game_type' : game_type,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : apk.get('size', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'comment_num' : g.get('commentsCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('downloadCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'author' : developer.get('name', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g.get('screenshots',{}).get('normal', [])),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\t\tif count % 100 == 0:\n\t\t\t\t\t\t\tmylogger.info(\"wandoujia detail commit %s\" % count)\n\t\t\t\t\t\t\tdb_conn.commit()\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"### %s ### %s\" % (url.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get wandoujia detail %s\" % count)\n\tdb_conn.commit()\n\n\n\ndef get_meizu_detail_by_id(gid):\n\tURL = \"http://api-game.meizu.com/games/public/detail/%s\" % gid\n\ttry:\n\t\tresponse = requests.get(URL, timeout=10)\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\t\tresponse = T(404)\n\tif response.status_code == 200:\n\t\tj = response.json()\n\t\tif 'value' in j:\n\t\t\treturn j['value']\n\treturn None\n\n\ndef get_meizu_detail():\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get meizu detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.title2!=u'').filter(KC_LIST.source==25):\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"meizu reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.kc_id==ret.id).filter(HotGameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\tg = get_meizu_detail_by_id(ret.title2)\n\t\t\tif g is not None:\t\n\t\t\t\tcount += 1 \n\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t'summary' : g.get('description', u''),\n\t\t\t\t\t\t\t\t\t'version' : g.get('version_name', u''),\n\t\t\t\t\t\t\t\t\t'game_type' : g.get('category_name', u''),\n\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('size', u''),\n\t\t\t\t\t\t\t\t\t'comment_num' : g.get('evaluate_count', u''),\n\t\t\t\t\t\t\t\t\t'download_num' : g.get('download_count', u''),\n\t\t\t\t\t\t\t\t\t'author' : g.get('publisher', u''),\n\t\t\t\t\t\t\t\t\t'rating' : g.get('avg_score', u''),\n\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t'imgs' : u','.join([i.get('image') for i in g.get('images', [])]),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\t\t\telse:\n\t\t\t\terror_times += 1\n\tmylogger.info(\"get meizu detail %s\" % count)\n\tdb_conn.commit()\n\ndef get_proxies():\n\treturn [{rc.type: u\"%s:%s\" % (rc.ip, rc.port)} for rc in db_conn.query(ProxyList)]\n\ndef check_proxy(proxy):\n\tstart = time.time()\n\ttry:\n\t\tr = requests.get(\"http://www.sogou.com/\", headers=headers)\n\t\t#r = requests.get(\"http://www.douban.com/\", headers=headers, proxies = proxy)\n\t\tif r.status_code == 200:\n\t\t\tend = time.time()\n\t\t\tprint proxy, end - start\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\" % (traceback.format_exc()))\n\t\t\n\ndef get_youku_detail_by_id(app_id):\n\tURL = \"http://api.gamex.mobile.youku.com/v2/app/detail?product_id=1&app_id=%s\" % app_id\n\ttry:\n\t\tresponse = requests.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tj = response.json()\n\t\t\treturn j['app']\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL, traceback.format_exc()))\n\t\treturn EX()\n\treturn None\n\ndef get_youku_detail(channel_id):\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get youku detail start ...\")\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where url!='' and dt!='' and source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(_sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, pkg_id = ret\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"youku reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\tg = get_youku_detail_by_id(pkg_id)\n\t\t\tif isinstance(g, EX):\n\t\t\t\terror_times += 1\n\t\t\telif g is not None:\t\n\t\t\t\tcount += 1 \n\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t'channel': channel_id,\n\t\t\t\t\t\t\t\t\t'name': name,\n\t\t\t\t\t\t\t\t\t'summary' : g.get('desc', u''),\n\t\t\t\t\t\t\t\t\t'version' : g.get('version', u''),\n\t\t\t\t\t\t\t\t\t'game_type' : g.get('type', u''),\n\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('size', u''),\n\t\t\t\t\t\t\t\t\t'rating' : g.get('score', u''),\n\t\t\t\t\t\t\t\t\t'download_num' : g.get('total_downloads', u''),\n\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g.get('screenshot', [])),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\tmylogger.info(\"get youku detail %s\" % count)\n\tdb_conn.commit()\n\ndef get_360_app_detail(channel_id):\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get 360 app hot game detail start ...\")\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(_sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, pkg = ret\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"360 reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\turl = \"http://125.88.193.234/mintf/getAppInfoByIds?pname=%s\" % pkg.split('\\t')[0]\n\t\t\t\tr = requests.get(url, timeout=10)\n\t\t\t\tif r.status_code == 200:\n\t\t\t\t\tj = r.json()\n\t\t\t\t\tif j['data'] is not None and len(j['data'])>=1:\n\t\t\t\t\t\tg = j['data'][0]\n\t\t\t\t\t\tcount += 1 \n\t\t\t\t\t\tcomments_url = \"http://comment.mobilem.360.cn/comment/getCommentTags?objid=%s\" % pkg.split('\\t')[1]\n\t\t\t\t\t\tcomments_num = u''\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tget_comments_r = requests.get(comments_url)\n\t\t\t\t\t\t\tif get_comments_r.status_code == 200:\n\t\t\t\t\t\t\t\tcomments_j = get_comments_r.json()\n\t\t\t\t\t\t\t\tfor tag in comments_j['data']['tag']:\n\t\t\t\t\t\t\t\t\tif tag.get('title', u'') == u'全部':\n\t\t\t\t\t\t\t\t\t\tcomments_num = tag.get('num', u'')\n\t\t\t\t\t\texcept Exception,e :\n\t\t\t\t\t\t\tmylogger.error(\"360 app comments #### %s #### \\t%s\" % (comments_url, traceback.format_exc()))\n\t\t\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t'name': name,\n\t\t\t\t\t\t\t\t\t'summary' : g.get('brief', u''),\n\t\t\t\t\t\t\t\t\t'version' : g.get('version_name', u''),\n\t\t\t\t\t\t\t\t\t'game_type' : g.get('category_name', u''),\n\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('size', u''),\n\t\t\t\t\t\t\t\t\t'rating' : g.get('rating', u''),\n\t\t\t\t\t\t\t\t\t'author' : g.get('corp', u''),\n\t\t\t\t\t\t\t\t\t'comment_num' : comments_num,\n\t\t\t\t\t\t\t\t\t'download_num' : g.get('download_times', u''),\n\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t'channel' : channel_id,\n\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g.get('trumb', u'').split(u'|')),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\t\tif count % 50 == 0:\n\t\t\t\t\t\t\tdb_conn.commit()\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"360 app #### %s #### \\t%s\" % (pkg.encode('utf-8'), traceback.format_exc()))\n\t\t\t\t\n\tmylogger.info(\"get 360 app detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_i4_app_detail(channel_id):\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get i4 app detail start ...\")\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(\"### %s ###\" % _sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, pkg = ret\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"i4 reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\turl = \"http://app3.i4.cn/controller/action/online.go?store=3&module=1&id=%s&reqtype=5\" % pkg.split('\\t')[1]\n\t\t\ttry:\n\t\t\t\tr = requests.get(url, timeout=10)\n\t\t\t\tif r.status_code == 200:\n\t\t\t\t\tj = r.json()\n\t\t\t\t\tif j['result']['list'] is not None and len(j['result']['list']) >= 1:\n\t\t\t\t\t\tg = j['result']['list'][0]\n\t\t\t\t\t\tcount += 1 \n\t\t\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t'channel': channel_id,\n\t\t\t\t\t\t\t\t\t'name': name,\n\t\t\t\t\t\t\t\t\t'summary' : g.get('shortNote', u''),\n\t\t\t\t\t\t\t\t\t'version' : g.get('shortVersion', u''),\n\t\t\t\t\t\t\t\t\t'game_type' : g.get('typeName', u''),\n\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('sizeByte', u''),\n\t\t\t\t\t\t\t\t\t'author' : g.get('company', u''),\n\t\t\t\t\t\t\t\t\t'download_num' : g.get('downloadCount', u''),\n\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t'imgs' : u','.join([u\"http://d.image.i4.cn/image/%s\" % img.get('url') for img in json.loads(g.get('image', []))]),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"i4 app #### %s #### \\t%s\" % (pkg.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get i4 app detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_xyzs_app_detail(channel_id):\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get xyzs app detail start ...\")\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where url!='' and dt!='' and source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(_sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, pkg = ret\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"xyzs reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\turl = \"http://interface.xyzs.com/v2/ios/c01/app\"\n\t\t\t\td = {'itunesid': int(pkg.split('\\t')[1])}\n\t\t\t\tr = requests.get(url, params=d, timeout=10)\n\t\t\t\tif r.status_code == 200:\n\t\t\t\t\tj = r.json()\n\t\t\t\t\tif j['code'] == 200:\n\t\t\t\t\t\tg = j['data']['app']\n\t\t\t\t\t\tcount += 1 \n\t\t\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t'name': name,\n\t\t\t\t\t\t\t\t\t'channel': channel_id,\n\t\t\t\t\t\t\t\t\t'summary' : g.get('content', u''),\n\t\t\t\t\t\t\t\t\t'version' : g.get('version', u''),\n\t\t\t\t\t\t\t\t\t'game_type' : g.get('apptypesno', u''),\n\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('size', u''),\n\t\t\t\t\t\t\t\t\t'download_num' : g.get('downloadnum', u''),\n\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g.get('iphoneimg', [])),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"xyzs app #### %s #### \\t%s\" % (pkg.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get xyzs app detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_91play_detail(channel_id):\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get 91play app detail start ...\")\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(\"### %s ###\" % _sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, pkg = ret\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"91play reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\turl = \"http://play.91.com/api.php/Api/index\"\n\t\t\t\traw_data = {\"id\": int(pkg.split('\\t')[1]),\"firmware\":\"19\",\"time\":1449458211590,\"device\":1,\"action\":30005,\"app_version\":302,\"action_version\":4,\"mac\":\"7b715ce093480b34d6987\",\"debug\":0}\n\t\t\t\tresponse = requests.post(url, data=raw_data, timeout=10)\n\t\t\t\tif response.status_code == 200:\n\t\t\t\t\tj = response.json() \n\t\t\t\t\tif j['code']==0 and j['data'] is not None and json.loads(j['data']) !=u'没有更多数据了':\n\t\t\t\t\t\tg = json.loads(j['data'])\n\t\t\t\t\t\t#break\n\t\t\t\t\t\tcount += 1 \n\t\t\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t'name': name,\n\t\t\t\t\t\t\t\t\t'channel': channel_id,\n\t\t\t\t\t\t\t\t\t'summary' : g.get('content', u''),\n\t\t\t\t\t\t\t\t\t'rating' : g.get('score', u''),\n\t\t\t\t\t\t\t\t\t'version' : g.get('version', u''),\n\t\t\t\t\t\t\t\t\t'game_type' : g.get('type_name', u''),\n\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('app_size', u''),\n\t\t\t\t\t\t\t\t\t'author' : g.get('developer', u''),\n\t\t\t\t\t\t\t\t\t'download_num' : g.get('download_count', u''),\n\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t'imgs' : g.get('img_urls', u'')\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"91play app detail #### %s #### \\t%s\" % (pkg.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get 91play app detail %s\" % count)\n\tdb_conn.commit()\n\ndef get_360_gamebox_detail(channel_id):\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get 360_gamebox app detail start ...\")\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(_sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, pkg = ret\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"360 gamebox reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\turl = \"http://next.gamebox.360.cn/7/xgamebox/getappintro?pname=%s\" % pkg.split('\\t')[0]\n\t\t\t\tresponse = requests.get(url, timeout=10)\n\t\t\t\tif response.status_code == 200:\n\t\t\t\t\tj = response.json() \n\t\t\t\t\tif j['data'] is not None and j['data']['info'] is not None and j['data']['info']:\n\t\t\t\t\t\tg = j['data']['info']\n\t\t\t\t\t\tcount += 1 \n\t\t\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t'channel': channel_id,\n\t\t\t\t\t\t\t\t\t'name': name,\n\t\t\t\t\t\t\t\t\t'summary' : g.get('brief', u''),\n\t\t\t\t\t\t\t\t\t'rating' : g.get('rating', u''),\n\t\t\t\t\t\t\t\t\t'version' : g.get('version_name', u''),\n\t\t\t\t\t\t\t\t\t'game_type' : g.get('category_name', u''),\n\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('size', u''),\n\t\t\t\t\t\t\t\t\t'author' : g.get('corp', u''),\n\t\t\t\t\t\t\t\t\t'download_num' : g.get('download_times', u''),\n\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t'imgs' : u\",\".join(g.get('trumb', u'').split(u'|'))\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"360_gamebox app detail #### %s #### \\t%s\" % (pkg.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get 360_gamebox app detail %s\" % count)\n\tdb_conn.commit()\n\ndef get_m_baidu_detail(channel_id):\n\tcount = 0\n\terror_times = 0\n\tsess = requests.session()\n\tmylogger.info(\"get baidu zhushou app detail start ...\")\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(\"### %s ###\" % _sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, pkg = ret\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"baidu zhoushou app detail reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\tpkg_name, pkg_id = pkg.split('\\t')\n\t\t\t\turl = u\"http://m.baidu.com/appsrv?native_api=1&psize=3&pkname=%s&action=detail&docid=%s\" % (pkg_name, pkg_id)\n\t\t\t\tr = sess.get(url, timeout=10)\n\t\t\t\tif r.status_code == 200:\n\t\t\t\t\td = r.json()\n\t\t\t\t\tif d['error_no'] == 0:\n\t\t\t\t\t\tif d['result'] is not None and d['result']['data'] is not None:\n\t\t\t\t\t\t\tg = d['result']['data']\n\t\t\t\t\t\t\tcount +=1\n\t\t\t\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t'channel': channel_id,\n\t\t\t\t\t\t\t\t\t\t'name': name,\n\t\t\t\t\t\t\t\t\t\t'summary' : g.get('brief', u''),\n\t\t\t\t\t\t\t\t\t\t'rating' : g.get('display_score', u''),\n\t\t\t\t\t\t\t\t\t\t'version' : g.get('versionname', u''),\n\t\t\t\t\t\t\t\t\t\t'game_type' : g.get('catename', u''),\n\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('packagesize', u''),\n\t\t\t\t\t\t\t\t\t\t'author' : g.get('sourcename', u''),\n\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('all_download_pid', u''),\n\t\t\t\t\t\t\t\t\t\t'download_num_day' : g.get('today_download_pid', u''),\n\t\t\t\t\t\t\t\t\t\t'comment_num' : g.get('display_count', u''),\n\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t'imgs' : u\",\".join(g.get('screenshots', []))\n\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\t\t\tif count % 50:\n\t\t\t\t\t\t\t\tdb_conn.commit()\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"%s\\t%s\" % (url.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get baidu zhushou app detail %s\" % count)\n\tdb_conn.commit()\n\ndef get_pp_detail_by_id(gid):\n\ttry:\n\t\td = {\"site\":1, \"id\": gid}\n\t\tp = proxies[random.randrange(len(proxies))]\n\t\tr = requests.post('http://pppc2.25pp.com/pp_api/ios_appdetail.php', data=d, proxies=p)\n\t\treturn r.json()\n\texcept Exception,e:\n\t\tmylogger.error(\"get %s detail \\t%s\" % (gid.encode('utf-8'), traceback.format_exc()))\n\t\treturn EX()\n\treturn None\n\ndef get_pp_comments_by_id(gid):\n\ttry:\n\t\td = {\"s\":1, \"a\":101, \"i\": gid, \"p\":1, \"l\":1}\n\t\tp = proxies[random.randrange(len(proxies))]\n\t\tr = requests.post('http://pppc2.25pp.com/pp_api/comment.php', data=d, proxies=p)\n\t\tif r.status_code == 200:\n\t\t\treturn r.json()\n\texcept Exception,e:\n\t\tmylogger.error(\"get %s comments \\t%s\" % (gid.encode('utf-8'), traceback.format_exc()))\n\treturn {}\n\ndef get_pp_detail(channel_id):\n\tcount = 0\n\terror_times = 0\n\tsess = requests.session()\n\tmylogger.info(\"get pp detail start ...\")\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(\"### %s ###\" % _sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, pkg = ret\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"pp detail reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\tpkg_name, pkg_id = pkg.split('\\t')\n\t\t\tg = get_pp_detail_by_id(int(pkg_id))\n\t\t\tif isinstance(g, EX):\n\t\t\t\terror_times += 1\n\t\t\telif g is not None:\t\n\t\t\t\tcomments_info = get_pp_comments_by_id(int(pkg_id))\n\t\t\t\tcount += 1 \n\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t'name': name,\n\t\t\t\t\t\t\t\t\t\t\t'channel': channel_id,\n\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('content', u''),\n\t\t\t\t\t\t\t\t\t\t\t'version' : g.get('ver', u''),\n\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get('catName', u''),\n\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('fileSize', u''),\n\t\t\t\t\t\t\t\t\t\t\t'comment_num' : comments_info.get('commentCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('downCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t'topic_num_total' : g.get('collectCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t'rating' : g.get('allVerStar', u''),\n\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t'imgs' : g.get('ipadImgs', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\t\t\t\tif count % 50 == 0:\n\t\t\t\t\tsleep(3)\n\t\t\t\t\tmylogger.info(\"pp detail commit %s\" % count)\n\t\t\t\t\tdb_conn.commit()\n\t\t\t\tif count % 20 == 0:\n\t\t\t\t\tsleep(1.23)\n\tmylogger.info(\"get pp detail %s\" % count)\n\tdb_conn.commit()\n\n\nchannel_map = {\n\t\t\t2\t: [46, 47], #18183\n\t\t\t4 \t: [5, 6, 7, 48], #360助手app\n\t\t\t22\t: [2, 52, 53, 54, 55, 56, 57, 58, 59],\t#360助手web\n\t\t\t1\t: [],\t#360游戏大厅web\n\t\t\t28\t: [41, 42],\t#360游戏大厅app\n\t\t\t0\t: [3, 4], #9游web\n\t\t\t20\t: [38], #itools\n\t\t\t24\t: [36], # pp\n\t\t\t8\t: [16, 17, 18],# vivo\n\t\t\t26\t: [39], # xyzs\n\t\t\t13\t: [31, 32], # youku\n\t\t\t18\t: [], # huawei\n\t\t\t21\t: [], # anzhi\n\t\t\t6\t: [], # 小米游戏app\n\t\t\t5\t: [60, 61], #小米游戏app\n\t\t\t3\t: [8, 9, 10, 43], # 应用宝PC\n\t\t\t15\t: [14], #dangle\n\t\t\t19\t: [37], # kuaiyong\n\t\t\t17\t: [], #muzhiwan\n\t\t\t14\t: [33, 34, 51], #sougou\n\t\t\t12\t: [29, 30], # aiqiyi\n\t\t\t16\t: [35], # i4\n\t\t\t7\t: [24, 25, 26, 45], #爱游戏\n\t\t\t29 \t: [11, 12, 13, 44], #百度手机助手app\n\t\t\t11\t: [], # lenovo\n\t\t\t23\t: [27, 28], # wandoujia\n\t\t\t9\t: [21, 22, 23], # coolpad\n\t\t\t27\t: [40], #91play\n\t\t\t10\t: [19,20], # 金立\n\t\t\t25\t: [], # meizu\n\t\t\t999\t: [1, 15, 49, 50], #小米官方\n\t\t\t\t}\n\ndef main():\n\tget_18183_detail(2)\n\tget_360_app_detail(4)\n\tget_360_gamebox_detail(28)\n\tget_9game_detail(0)\n\tget_pp_detail(24)\n\tget_vivo_detail(8)\n\tget_xyzs_app_detail(26)\n\tget_youku_detail(13)\n\tget_appicsh_detail(3)\n\tget_dangle_detail(15)\n\tget_kuaiyong_detail(19)\n\tget_iqiyi_detail(12)\n\tget_i4_app_detail(16)\n\tget_sogou_detail(14)\n\tget_open_play_detail(7)\n\tget_m_baidu_detail(29)\n\tget_wandoujia_detail(23)\n\tget_coolpad_detail(9)\n\tget_91play_detail(27)\n\tget_gionee_detail(10)\n\tget_xiaomi_game_detail(5)\n\ndef get_muzhiwan_detail():\n\tpass\t\n\ndef get_itools_detail():\n\tpass\n\ndef get_360_gamebox_web_detail():\n\tpass\n\nif __name__ == '__main__':\n\tmain()\n"
},
{
"alpha_fraction": 0.7002801299095154,
"alphanum_fraction": 0.7058823704719543,
"avg_line_length": 26.461538314819336,
"blob_id": "1ff8cba5f47fa8d12ac11625d81a5b881405dfcc",
"content_id": "4002758f203f557baebd4ad3129b9256a746ac95",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 357,
"license_type": "no_license",
"max_line_length": 48,
"num_lines": 13,
"path": "/common/create_table.py",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python\n#coding=utf-8\n\nfrom model import *\nfrom define import *\n\nif __name__ == \"__main__\":\n #createtable(GPList, PTPQ_ENGINE)\n #createtable(GPDetail, PTPQ_ENGINE)\n #createtable(MTMapping2, PTPQ_ENGINE)\n #createtable(RankingChannel, PTPQ_ENGINE)\n createtable(HotGameDetailByDay, PTPQ_ENGINE)\n #createtable(IQIYI_TV, PTPQ_ENGINE)\n"
},
{
"alpha_fraction": 0.56243497133255,
"alphanum_fraction": 0.5807340145111084,
"avg_line_length": 34.44396209716797,
"blob_id": "cadfc4c72f8d248c8afafed50ba77667c6250dfa",
"content_id": "c7dec94619988c52fa1374f8b7ab79afcae699af",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 49165,
"license_type": "no_license",
"max_line_length": 298,
"num_lines": 1383,
"path": "/spider/get_game_detail_by_day.py",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#encoding=utf-8\n\nimport requests\nimport json\nimport re\nfrom bs4 import BeautifulSoup\nfrom time import sleep\nimport traceback\nfrom config import *\nimport random\nimport xmltodict\nimport datetime\n\ndb_conn = new_session()\nmylogger = get_logger('get_game_detail')\n\nheaders = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36'}\n\nimport random\n\nclass EX:\n\t\n\tmsg = \"\"\n\n\ndef get_9game_detail():\n\tmylogger.info(\"get 9game detail start ...\")\n\tcount = 0\n\terror_times = 0\n\tsess = requests.session()\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.url!=u'').filter(KC_LIST.source==0).filter(KC_LIST.publish_date>=u'2015-10-01'):\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"9game reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\tp = proxies[random.randrange(len(proxies))]\n\t\t\t\tresponse = sess.get(ret.url, timeout=15, proxies=p)\n\t\t\t\tif response.status_code == 200:\n\t\t\t\t\tcount += 1\n\t\t\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\t\t\tspec_pic = soup.find('div', class_='spec-pic')\n\t\t\t\t\timgs \t= u''\n\t\t\t\t\trating \t= u''\n\t\t\t\t\tgame_type = u''\n\t\t\t\t\tcomments_num = u''\n\t\t\t\t\ttopic_num_day = u''\n\t\t\t\t\ttopic_num_total = u''\n\t\t\t\t\tif spec_pic is not None:\n\t\t\t\t\t\timgs = u','.join([pic.find('img').get('src') for pic in spec_pic.find_all('span', class_='img')])\n\t\t\t\t\ttips = soup.find('div', class_='tips')\n\t\t\t\t\tsummary = tips.text.strip() if tips is not None else u''\n\t\t\t\t\tbbs = soup.find('li', class_='bbs')\n\t\t\t\t\tif bbs is not None:\n\t\t\t\t\t\tif bbs.find('a') is not None:\n\t\t\t\t\t\t\tinfo = get_9game_info_from_bbs(bbs.find('a').get('href'))\n\t\t\t\t\t\t\tif info is not None:\n\t\t\t\t\t\t\t\ttopic_num_day, topic_num_total = info\n\t\t\t\t\tscores = soup.find('div', class_='view-scroe1')\n\t\t\t\t\tif scores is not None:\n\t\t\t\t\t\trating = scores.find('div', class_='big-s').text\n\t\t\t\t\tp_des = soup.find('div', class_='p-des')\n\t\t\t\t\tif p_des is not None:\n\t\t\t\t\t\tif p_des.find('p') is not None:\n\t\t\t\t\t\t\tcontent = re.sub(u'\\r| |\\xa0', u'', p_des.find('p').text)\n\t\t\t\t\t\t\tfor seg in content.split('\\n'):\n\t\t\t\t\t\t\t\tif u'类型' in seg:\n\t\t\t\t\t\t\t\t\tif len(seg.split(u':')) == 2:\n\t\t\t\t\t\t\t\t\t\tgame_type = seg.split(u':')[1].strip()\n\t\t\t\t\t\t\t\telif u'评论' in seg:\n\t\t\t\t\t\t\t\t\tm = re.search('\\d+', seg)\n\t\t\t\t\t\t\t\t\tcomments_num = m.group() if m is not None else u''\n\n\t\t\t\t\titem = GameDetailByDay(**{'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : imgs,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'summary' : summary,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'game_type' : game_type,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'topic_num_day' : topic_num_day,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'topic_num_total' : topic_num_total,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'rating' : rating ,\n\t\t\t\t\t\t\t\t\t\t\t\t\t'comment_num' : comments_num,\n\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\tif count % 50 == 0:\n\t\t\t\t\t\tsleep(3)\n\t\t\t\t\t\tmylogger.info(\"9game detail commit %s\" % count)\n\t\t\t\t\t\tdb_conn.commit()\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"%s\\t%s\" % (ret.url.encode('utf-8'), traceback.format_exc()))\n\n\tmylogger.info(\"get 9game detail %s\" % count)\n\tdb_conn.commit()\n\ndef get_9game_info_from_bbs(url):\n\ttry:\n\t\tp = proxies[random.randrange(len(proxies))]\n\t\tresponse = requests.get(url, timeout=10, proxies=p)\n\t\tif response.status_code == 200:\n\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\ttopics = soup.find('span', 'xs1 xw0 i')\t\n\t\t\tif topics is not None:\n\t\t\t\tnums = topics.find_all('strong')\n\t\t\t\tif len(nums) == 2:\n\t\t\t\t\ttoday_nums, total_nums = [i.text for i in nums]\n\t\t\t\t\treturn today_nums, total_nums\n\texcept Exception,e:\n\t\tmylogger.error(\"%s 9game bbs \\t%s\" % (url.encode('utf-8'), traceback.format_exc()))\n\treturn None\n\ndef get_18183_detail():\n\tmylogger.info(\"get 18183 detail start ...\")\n\tcount = 0 \n\terror_times = 0\n\tsess = requests.session()\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.publish_date>=u'2015-10-01').filter(KC_LIST.url!=u'').filter(KC_LIST.source==2):\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"18183 reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\tresponse = sess.get(ret.url, timeout=10)\n\t\t\t\tcount += 1\n\t\t\t\ttopic_num_total = u''\n\t\t\t\tgame_type = u''\n\t\t\t\tpkg_size = u''\n\t\t\t\tsummary = u''\n\t\t\t\timgs = u''\n\t\t\t\tr = response.text.encode('ISO-8859-1').decode('utf-8')\n\t\t\t\tsoup = BeautifulSoup(r)\n\t\t\t\tfor li1 in soup.find_all('li', class_='li1'):\n\t\t\t\t\tcodes = li1.find_all('code')\n\t\t\t\t\tspans = li1.find_all('span')\n\t\t\t\t\tfor i in xrange(len(codes)):\n\t\t\t\t\t\tif codes[i].text == u'类型:':\n\t\t\t\t\t\t\tgame_type = spans[i].text.strip()\n\t\t\t\t\t\tif codes[i].text == u'关注:':\n\t\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\t\trs = requests.get(spans[i].find('script').get('src'))\n\t\t\t\t\t\t\t\tif rs.status_code == 200:\n\t\t\t\t\t\t\t\t\tm = re.search('\\d+', rs.text)\n\t\t\t\t\t\t\t\t\tif m is not None:\n\t\t\t\t\t\t\t\t\t\ttopic_num_total = m.group()\n\t\t\t\t\t\t\texcept Exception,e:\n\t\t\t\t\t\t\t\tmylogger.error(\"18183 topic page error and sleep 3s %s\" % (traceback.format_exc()))\n\t\t\t\t\t\t\t\tsleep(3)\n\t\t\t\tdwnli = soup.find('li', class_='dwnli')\n\t\t\t\tif dwnli is not None:\n\t\t\t\t\tif dwnli.find('p') is not None:\n\t\t\t\t\t\tif dwnli.find('p') is not None:\n\t\t\t\t\t\t\tpkg_size = dwnli.find('p').text.split(u':')[1]\n\t\t\t\tjianjie_txt = soup.find('div', class_='jianjie_txt')\n\t\t\t\tif jianjie_txt is not None:\n\t\t\t\t\tsummary = jianjie_txt.text.strip()\n\t\t\t\ttabcen_ul = soup.find('ul', class_='tabcen_ul')\n\t\t\t\tif tabcen_ul is not None:\n\t\t\t\t\ticons = []\n\t\t\t\t\tfor ss_body in tabcen_ul.find_all('li', class_='ss_body'):\n\t\t\t\t\t\tif ss_body.find('img') is not None:\n\t\t\t\t\t\t\ticons.append(ss_body.find('img').get('src'))\n\t\t\t\t\tif icons:\n\t\t\t\t\t\timgs = u\",\".join(icons)\n\t\t\t\titem = GameDetailByDay(**{'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : imgs,\n\t\t\t\t\t\t\t\t\t\t\t\t'summary' : summary,\n\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : pkg_size,\n\t\t\t\t\t\t\t\t\t\t\t\t'game_type' : game_type,\n\t\t\t\t\t\t\t\t\t\t\t\t'topic_num_total' : topic_num_total,\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\t\t\t\tif count % 100 == 0:\n\t\t\t\t\tsleep(3)\n\t\t\t\t\tmylogger.info(\"18183 detail commit %s\" % count)\n\t\t\t\t\tdb_conn.commit()\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"%s\\t%s\" % (ret.url.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get 18183 detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_appicsh_detail():\n\tmylogger.info(\"get appicsh detail start ...\")\n\tcount = 0\n\terror_times = 0\n\tsess = requests.session()\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.source==3).filter(KC_LIST.url!=u''):\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"appicsh reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\tresponse = sess.get(ret.url, timeout=10)\n\t\t\t\td = response.json()\n\t\t\t\tif d['obj'] is not None and d['obj']['appInfo'] is not None:\n\t\t\t\t\tappinfo = d['obj']['appInfo']\n\t\t\t\t\tcount += 1\n\t\t\t\t\tpublishtime = appinfo.get('apkPublishTime', u\"\")\n\t\t\t\t\tupdate_time = unicode(datetime.date.fromtimestamp(publishtime)) if publishtime else u\"\"\n\n\t\t\t\t\titem = GameDetailByDay(**{'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join([i for i in appinfo['screenshots']]),\n\t\t\t\t\t\t\t\t\t\t\t\t'summary' : appinfo.get('description', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : appinfo.get('fileSize', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'version' : appinfo.get('versionName', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'rating' : appinfo.get('averageRating', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'download_num' : appinfo.get('appDownCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'author' : appinfo.get('authorName', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'update_time' : update_time\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\tdb_conn.merge(item)\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"%s\\t%s\" % (ret.url.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get appicsh detail %s\" % count)\n\tdb_conn.commit()\n\t\t\t\n\ndef get_xiaomi_new_id_map():\n\tmydict = {}\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.game_id!=u'').filter(KC_LIST.source==5):\n\t\tmydict[int(ret.game_id)] = ret.id\n\treturn mydict\n\n\ndef get_xiaomi_new_detail():\n\tid_map = get_xiaomi_new_id_map()\n\tcount = 0\n\tfor page in xrange(1, 23):\n\t\turl = \"http://app.migc.xiaomi.com/cms/interface/v5/subjectgamelist1.php?pageSize=20&page=%s&subId=138\" % page\n\t\ttry:\n\t\t\tr = requests.get(url, timeout=10)\n\t\t\tif r.status_code == 200:\n\t\t\t\td = r.json()\n\t\t\t\tif d['errCode'] == 200:\n\t\t\t\t\tnew_games_list = d.get('gameList', [])\n\t\t\t\t\tfor g in new_games_list:\n\t\t\t\t\t\tgame_id = g.get('gameId', u'')\n\t\t\t\t\t\tupdate_time = u''\n\t\t\t\t\t\tupdateTime = g.get('updateTime', u'')\n\t\t\t\t\t\tif updateTime:\n\t\t\t\t\t\t\tt = unicode(updateTime)[:10]\n\t\t\t\t\t\t\tupdate_time = unicode(datetime.date.fromtimestamp(int(t)))\n\t\t\t\t\t\tdt = unicode(datetime.date.today())\n\t\t\t\t\t\tif game_id in id_map:\n\t\t\t\t\t\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==id_map[game_id]).filter(GameDetailByDay.dt==dt).first()\n\t\t\t\t\t\t\tif not ins:\n\t\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'kc_id': id_map.get(game_id),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('introduction', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'author' : g.get('publisherName', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get('className', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'rating' : g.get('ratingScore', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'version' : g.get('versionName', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('apkSize', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('downloadCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join([i.get('url') for i in g['screenShot']]),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'topic_num_total' : g.get('ratingCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'update_time' : update_time,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\t\t\telse:\n\t\t\t\t\t\t\t\tins.pkg_size = g.get('apkSize', u'')\n\t\texcept Exception,e:\n\t\t\tmylogger.error(\"%s\\t%s\" % (url, traceback.format_exc()))\n\tdb_conn.commit()\n\tmylogger.info(\"get xiaomi_new detail %s\" % count)\n\t\t\t\t\t\t\t\n\ndef get_xiaomi_rpg_id_map():\n\tmydict = {}\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.game_id!=u'').filter(KC_LIST.source==6):\n\t\tmydict[int(ret.game_id)] = ret.id\n\treturn mydict\n\n\ndef get_xiaomi_rpg_detail():\n\tcount = 0\n\tid_map = get_xiaomi_rpg_id_map()\n\tfor page in xrange(1, 2):\n\t\turl = \"http://app.migc.xiaomi.com/cms/interface/v5/subjectgamelist1.php?subId=203&pageSize=150&page=%s\" % page\n\t\ttry:\n\t\t\tr = requests.get(url, timeout=10)\n\t\t\tif r.status_code == 200:\n\t\t\t\td = r.json()\n\t\t\t\tif d['errCode'] == 200:\n\t\t\t\t\tnew_games_list = d.get('gameList', [])\n\t\t\t\t\tfor g in new_games_list:\n\t\t\t\t\t\tgame_id = g.get('gameId', u'')\n\t\t\t\t\t\tupdate_time = u''\n\t\t\t\t\t\tupdateTime = g.get('updateTime', u'')\n\t\t\t\t\t\tif updateTime:\n\t\t\t\t\t\t\tt = unicode(updateTime)[:10]\n\t\t\t\t\t\t\tupdate_time = unicode(datetime.date.fromtimestamp(int(t)))\n\t\t\t\t\t\tdt = unicode(datetime.date.today())\n\t\t\t\t\t\tif game_id in id_map:\n\t\t\t\t\t\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==id_map[game_id]).filter(GameDetailByDay.dt==dt).first()\n\t\t\t\t\t\t\tif not ins:\n\t\t\t\t\t\t\t\tcount += 1\n\t\t\t\t\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'kc_id': id_map.get(game_id),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('introduction', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'author' : g.get('publisherName', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get('className', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'rating' : g.get('ratingScore', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'version' : g.get('versionName', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('downloadCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('apkSize', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join([i.get('url') for i in g['screenShot']]),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'topic_num_total' : g.get('ratingCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t'update_time' : update_time,\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\t\t\tdb_conn.merge(item)\n\t\texcept Exception,e:\n\t\t\tmylogger.error(\"%s\\t%s\" % (url, traceback.format_exc()))\n\tdb_conn.commit()\n\tmylogger.info(\"get xiaomi rpg detail %s\" % count)\n\t\t\t\t\t\t\t\n\ndef get_open_play_detail():\n\tcount = 0\n\terror_times = 0\n\tsess = requests.session()\n\tmylogger.info(\"get open play detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.game_id!=u'').filter(KC_LIST.source==7):\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"open play detail reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\t_url = u'http://open.play.cn/api/v2/mobile/game_detail.json?game_id=%s' % ret.game_id\n\t\t\ttry:\n\t\t\t\tresponse = sess.get(_url, timeout=10)\n\t\t\t\td = response.json()\n\t\t\t\tif d.get('text', u'') == u'success':\n\t\t\t\t\tcount += 1 \n\t\t\t\t\tg = d['ext']['game_detail']\n\t\t\t\t\ttopic_num_total = u''\n\t\t\t\t\tref_vote_info = d['ext']['ref_vote_info']\n\t\t\t\t\tif ref_vote_info['vote_state'] == 1:\n\t\t\t\t\t\ttopic_num_total = ref_vote_info['vote_up_count'] + ref_vote_info['vote_dn_count']\n\t\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('game_introduction', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'author' : g.get('cp_name', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get('game_class', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'version' : g.get('version', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('game_download_count', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('game_size' u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g['game_view_images']),\n\t\t\t\t\t\t\t\t\t\t\t\t'topic_num_total' : topic_num_total,\n\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\tif count % 100 == 0:\n\t\t\t\t\t\tsleep(3)\n\t\t\t\t\t\tmylogger.info(\"open play detail commit %s\" % count)\n\t\t\t\t\t\tdb_conn.commit()\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"%s\\t%s\" % (_url.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get open play detail %s\" % count)\n\tdb_conn.commit()\n\ndef get_vivo_detail():\n\tcount = 0\n\terror_times = 0\n\tsess = requests.session()\n\tmylogger.info(\"get vivo detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.url!=u'').filter(KC_LIST.source==8):\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"vivo reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\tresponse = sess.get(ret.url, timeout=10)\n\t\t\t\td = response.json()\n\t\t\t\tif d is not None and 'result' in d and d['result']:\n\t\t\t\t\tg = d.get('game')\n\t\t\t\t\tif g is not None:\n\t\t\t\t\t\tcount += 1 \n\t\t\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('desc', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'rating' : g.get('comment', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'author' : g.get('gameDeveloper', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get('type', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'version' : g.get('versonName', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('download', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'comment_num' : g.get('commentNum', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('size' u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t'update_time' : g.get('date', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g['screenshot'].split(u'###')),\n\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"%s\\t%s\" % (ret.url.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get vivo play detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_coolpad_detail():\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get coolpad detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.game_id!=u'').filter(KC_LIST.source==9):\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"coolpad reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\tg = get_coolpad_detail_by_id(ret.game_id)\n\t\t\tif isinstance(g, EX):\n\t\t\t\terror_times += 1\n\t\t\telif g is not None:\n\t\t\t\tcount += 1 \n\t\t\t\timgs = u''\n\t\t\t\tif g['pics'] is not None and g['pics']['picurl'] is not None:\n\t\t\t\t\timgs = u','.join([i for i in g['pics']['picurl'] if i is not None])\n\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('summary', u''),\n\t\t\t\t\t\t\t\t\t\t\t'rating' : g.get('score', u''),\n\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get('levelname', u''),\n\t\t\t\t\t\t\t\t\t\t\t'version' : g.get('version', u''),\n\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('downloadtimes', u''),\n\t\t\t\t\t\t\t\t\t\t\t'comment_num' : g.get('commcount', u''),\n\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('size' u''),\n\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t'imgs' : imgs,\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\tmylogger.info(\"get coolpad detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_coolpad_detail_by_id(resid):\n\turl = \"http://gamecenter.coolyun.com/gameAPI/API/getDetailResInfo?key=0\"\n\traw_data = \"\"\"<?xml version=\"1.0\" encoding=\"utf-8\"?>\n<request username=\"\" cloudId=\"\" openId=\"\" sn=\"865931027730878\" platform=\"1\" platver=\"19\" density=\"480\" screensize=\"1080*1920\" language=\"zh\" mobiletype=\"MI4LTE\" version=\"4\" seq=\"0\" appversion=\"3350\" currentnet=\"WIFI\" channelid=\"coolpad\" networkoperator=\"46001\" simserianumber=\"89860115851040101064\">\n <resid>%s</resid>\n</request>\"\"\" % resid\n\ttry:\n\t\tr = requests.post(url, data=raw_data, headers={'Content-Type': 'application/xml'})\n\t\tif r.status_code == 200:\n\t\t\tt = re.sub(u'\\r|\\n', '', r.text)\n\t\t\tdoc = xmltodict.parse(t)\n\t\t\td = doc['response']['reslist']['res']\n\t\t\tif d['@rid'] != u'':\n\t\t\t\treturn d\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (resid.encode('utf-8'), traceback.format_exc()))\n\t\treturn EX()\n\treturn None\n\ndef get_gionee_detail():\n\tcount = 0\n\terror_times = 0\n\tsess = requests.session()\n\tmylogger.info(\"get gionee detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.game_id!=u'').filter(KC_LIST.source==10):\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"gionee reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\t_url = u\"http://game.gionee.com/Api/Local_Gameinfo/getDetails?gameId=%s\" % ret.game_id\n\t\t\ttry:\n\t\t\t\tresponse = sess.get(_url, timeout=10)\n\t\t\t\td = response.json()\n\t\t\t\tif 'success' in d and d['success']:\n\t\t\t\t\tg = d['data']\n\t\t\t\t\tcount += 1 \n\t\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t\t\t\t'rating' : g.get('score', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('downloadCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'author' : g.get('publisher', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get('category', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'version' : g.get('versionName', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('fileSize' u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g['bannerList']['fullPicture']),\n\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\tdb_conn.merge(item)\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"%s\\t%s\" % (_url.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get gionee play detail %s\" % count)\n\tdb_conn.commit()\n\n\n\ndef get_leveno_detail():\n\tcount = 0\n\terror_times = 0\n\tsess = requests.session()\n\tmylogger.info(\"get lenovo detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.pkg_name!=u'').filter(KC_LIST.source==11):\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"leveno reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\t_url = u\"http://yx.lenovomm.com/business/app!getAppDetail5.action?dpi=480&height=1920&dev=ph&width=1080&cpu=armeabi-v7a&pn=%s&uid=72DB07100FC223A2EDE82F4A44AE96B4&os=4.4.4&perf=hp&model=MI 4LTE&type=0&density=xx&mac=7A031DAB40535B3F5E204582EB961FC5\" % ret.pkg_name\n\t\t\ttry:\n\t\t\t\tp = proxies[random.randrange(len(proxies))]\n\t\t\t\tresponse = sess.get(_url, timeout=10, proxies=p)\n\t\t\t\td = response.json()\n\t\t\t\tif 'app' in d:\n\t\t\t\t\tg = d['app']\n\t\t\t\t\tcount += 1 \n\t\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t\t\t\t'rating' : g.get('averageStar', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get('categoryName', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'version' : g.get('version', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('size' u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('downloadCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('description', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : g['snapList'],\n\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\tdb_conn.merge(item)\n\t\t\texcept Exception,e:\n\t\t\t\tsleep(1.23)\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"%s\\t%s\" % (_url.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get lenovo detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_iqiyi_detail():\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get iqiyi detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.game_id!=u'').filter(KC_LIST.source==12):\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"iqiyi reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\td = get_iqiyi_detail_by_id(ret.game_id)\n\t\t\tif isinstance(d, EX):\n\t\t\t\terror_times += 1\n\t\t\telif d is not None:\n\t\t\t\tg = d['app']\n\t\t\t\tcount += 1 \n\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('desc', u''),\n\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get('cate_name', u''),\n\t\t\t\t\t\t\t\t\t\t\t'version' : g.get('version', u''),\n\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('cnt', u''),\n\t\t\t\t\t\t\t\t\t\t\t'author' : g.get('author', u''),\n\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('l_size' u''),\n\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t'imgs' : u\",\".join([i.get('full_img', u'') for i in d['medias']]),\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\tmylogger.info(\"get iqiyi detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_iqiyi_detail_by_id(qipu_id):\n\turl = \"http://store.iqiyi.com/gc/game/detail?callback=rs&id=%s\" % qipu_id\n\ttry:\n\t\tr = requests.get(url)\n\t\tif r.status_code == 200:\n\t\t\tm = re.search(u'rs\\\\(([\\s\\S]*)\\\\)\\\\;', r.text)\n\t\t\tif m is not None:\n\t\t\t\treturn json.loads(m.group(1))\n\texcept Exception, e:\n\t\tmylogger.error(\"### %s ###\\t%s\" % (qipu_id.encode('utf-8'), traceback.format_exc()))\n\t\treturn EX()\n\treturn None\n\ndef get_sogou_detail():\n\tcount = 0\n\terror_times = 0\n\tsess = requests.session()\n\tmylogger.info(\"get sogou detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.game_id!=u'').filter(KC_LIST.source==14):\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"sogou reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\t_url = u\"http://mobile.zhushou.sogou.com/m/appDetail.html?id=%s\" % ret.game_id\n\t\t\ttry:\n\t\t\t\tresponse = sess.get(_url, timeout=10)\n\t\t\t\td = response.json()\n\t\t\t\tg = d['ainfo']\n\t\t\t\tcount += 1 \n\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t\t\t'rating' : g.get('score', u''),\n\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('desc', u''),\n\t\t\t\t\t\t\t\t\t\t\t'version' : g.get('vn', u''),\n\t\t\t\t\t\t\t\t\t\t\t'game_type' : d['tgroup'].get('name', u''),\n\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('dc', u''),\n\t\t\t\t\t\t\t\t\t\t\t'author' : g.get('author', u''),\n\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('size' u''),\n\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t'imgs' : u\",\".join([i.get('url', u'') for i in d['images']]),\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"%s\\t%s\" % (_url.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get sogou detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_dangle_detail():\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get dangle detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.game_id!=u'').filter(KC_LIST.source==15):\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"dangle reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\tg = get_dangle_detail_by_id(ret.game_id)\n\t\t\tif isinstance(g, EX):\n\t\t\t\terror_times += 1\n\t\t\telif g is not None:\n\t\t\t\tcount += 1 \n\t\t\t\tpackageTOs = {}\n\t\t\t\tif 'packageTOs' in g:\n\t\t\t\t\tpackageTOs = g['packageTOs'][0] if g['packageTOs'] else {}\n\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('description', u''),\n\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get('categoryName', u''),\n\t\t\t\t\t\t\t\t\t\t\t'version' : packageTOs.get('versionName', u''),\n\t\t\t\t\t\t\t\t\t\t\t'rating' : g.get('score', u''),\n\t\t\t\t\t\t\t\t\t\t\t'comment_num' : g.get('commentCnt', u''),\n\t\t\t\t\t\t\t\t\t\t\t'topic_num_total' : g.get('grade', {}).get('personCnt', u''),\n\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('appInstalledCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t'author' : g.get('author', u''),\n\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : packageTOs.get('fileSize', u''),\n\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g['snapshotUrls']),\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\tmylogger.info(\"get dangle detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_dangle_detail_by_id(gid):\n\turl = u\"http://api2014.digua.d.cn/newdiguaserver/res/detail?id=%s&resourceType=5\"% gid\n\theaders = {\"HEAD\": {\n \"stamp\":1447747218496,\n \"verifyCode\":\"78492ba9e8569f3b9d9173ac4e4b6cb9\",\n \"it\":2,\n \"resolutionWidth\":1080,\n \"imei\":\"865931027730878\",\n \"clientChannelId\":\"100327\",\n \"versionCode\":750,\n \"mac\":\"34:80:b3:4d:69:87\",\n \"vender\":\"Qualcomm\",\n \"vp\":\"\",\n \"version\":\"7.5\",\n \"sign\":\"cfd1b8d1b60f85c4\",\n \"dd\":480,\n \"sswdp\":\"360\",\n \"hasRoot\":0,\n \"glEsVersion\":196608,\n \"device\":\"MI_4LTE\",\n \"ss\":2,\n \"local\":\"zh_CN\",\n \"language\":\"2\",\n \"sdk\":19,\n \"resolutionHeight\":1920,\n \"osName\":\"4.4.4\",\n \"gpu\":\"Adreno (TM) 330\"\n\t}}\n\ttry:\n\t\tr = requests.post(url, headers=headers, timeout=30)\n\t\tif r.status_code == 200:\n\t\t\treturn r.json()\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (url.encode('utf-8'), traceback.format_exc()))\n\t\treturn EX()\n\treturn None\n\ndef get_muzhiwan_detail():\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get muzhiwan detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.url!=u'').filter(KC_LIST.source==17):\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"muzhiwan reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\tg = get_muzhiwan_detail_by_id(ret.url)\n\t\t\tif isinstance(g, EX):\n\t\t\t\terror_times += 1\n\t\t\telif g:\n\t\t\t\t#m = re.search(u'(\\d+)个', g.get(u'评论数', u''))\n\t\t\t\t#comment_num = m.group(1) if m is not None else u''\n\t\t\t\tcount += 1 \n\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('description', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'version' : g.get(u'版本', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get(u'分类', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'comment_num' : g.get('comments', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get(u'大小' u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g.get('imgs', [])),\n\t\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\t\t\t\tif count % 100 == 0:\n\t\t\t\t\tsleep(1.23)\n\t\t\t\t\tmylogger.info(\"muzhiwan detail %s commit ... \" % count)\n\tmylogger.info(\"get muzhiwan detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_muzhiwan_comment_by_gid(gid):\n\ttry:\n\t\turl = u'http://www.muzhiwan.com/index.php?action=game&opt=readHit&gid=%s' % gid\n\t\tr = requests.get(url)\n\t\tif r.status_code == 200:\n\t\t\treturn r.text\n\texcept Exception,e:\n\t\tmylogger.error(\"get muzhiwan comments %s\\t%s\" % (url, traceback.format_exc()))\n\treturn None\n\ndef get_muzhiwan_detail_by_id(url):\n\tmydict = {}\n\ttry:\n\t\tresponse = requests.get(url, timeout=10)\n\t\tsoup = BeautifulSoup(response.text)\n\t\tinfo = soup.find('div', class_='detail_info')\n\t\tgid = soup.find('input', id='gid')\n\t\tif gid is not None:\n\t\t\tcomments = get_muzhiwan_comment_by_gid(gid.get('value'))\n\t\t\tif comments is not None:\n\t\t\t\tmydict['comments'] = comments\n\t\tif info is not None:\n\t\t\tfor ret in info.find('div', class_='clearfix').find_all('li'):\n\t\t\t\tsegs = ret.text.split(u':')\n\t\t\t\tif len(segs) == 2:\n\t\t\t\t\tmydict[segs[0]] = segs[1]\n\t\timgs = soup.find('div', class_=\"img_screen\")\t\n\t\tif imgs is not None:\n\t\t\tmydict['imgs'] = [i.find('img').get('src') for i in imgs.find_all('li')]\n\t\tsummary = soup.find('p', itemprop=\"description\")\n\t\tif summary is not None:\n\t\t\tmydict['description'] = summary.text\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (url.encode('utf-8'), traceback.format_exc()))\n\t\treturn EX()\n\treturn mydict\n\n\ndef get_huawei_detail():\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get huawei detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.url!=u'').filter(KC_LIST.source==18):\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"huawei reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\tg = get_huawei_detail_by_id(ret.url)\n\t\t\tif isinstance(g, EX):\n\t\t\t\terror_times += 1\n\t\t\telif g:\n\t\t\t\tcount += 1 \n\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('description', u''),\n\t\t\t\t\t\t\t\t\t\t\t'version' : g.get(u'版本', u''),\n\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get(u'分类', u''),\n\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('download_num', u''),\n\t\t\t\t\t\t\t\t\t\t\t'comment_num' : g.get('comment_num', u''),\n\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get(u'大小', u''),\n\t\t\t\t\t\t\t\t\t\t\t'author' : g.get('author', u''),\n\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g.get('imgs', [])),\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\t\t\t\tif count % 100 == 0:\n\t\t\t\t\tmylogger.info(\"huawei detail commit %s\" % count)\n\t\t\t\t\tdb_conn.commit()\n\tmylogger.info(\"get huawei detail %s\" % count)\n\tdb_conn.commit()\n\ndef get_huawei_detail_by_id(url):\n\tmydict = {}\n\ttry:\n\t\tp = proxies[random.randrange(len(proxies))]\n\t\tresponse = requests.get(url, timeout=20, proxies=p)\n\t\tsoup = BeautifulSoup(response.text)\n\t\tfor d in soup.find_all('li', class_='ul-li-detail'):\n\t\t\tif u'开发者:' in d.text:\n\t\t\t\tmydict['author'] = d.find('span').get('title')\n\t\t\telse:\n\t\t\t\tsegs = d.text.split(u':')\n\t\t\t\tif len(segs) == 2:\n\t\t\t\t\tmydict[segs[0]] = segs[1]\n\t\tinfo = soup.find('ul', class_='app-info-ul nofloat')\n\t\tif info is not None:\n\t\t\tlis = info.find_all('li')\n\t\t\tif len(lis) >= 2:\n\t\t\t\tdownload_li = lis[1]\n\t\t\t\tdownload_span = download_li.find('span', class_='grey sub')\n\t\t\t\tif download_span is not None:\n\t\t\t\t\tm = re.search('\\d+', download_span.text)\n\t\t\t\t\tif m is not None:\n\t\t\t\t\t\tmydict['download_num'] = m.group()\n\t\timgs = soup.find('ul', class_=\"imgul\")\t\n\t\tif imgs is not None:\n\t\t\tmydict['imgs'] = [i.find('img').get('src') for i in imgs.find_all('li')]\n\t\tsummary = soup.find('div', id=\"app_strdesc\")\n\t\tif summary is not None:\n\t\t\tmydict['description'] = summary.text\n\t\tcomment_list = soup.find('div', id='comment_list')\n\t\tif comment_list is not None:\n\t\t\tcomment = comment_list.find('span', class_='title')\n\t\t\tif comment is not None:\n\t\t\t\tm = re.search('\\d+', comment.text)\n\t\t\t\tif m is not None:\n\t\t\t\t\tmydict['comment_num'] = m.group()\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (url.encode('utf-8'), traceback.format_exc()))\n\t\tsleep(5)\n\t\treturn EX()\n\treturn mydict\n\ndef get_kuaiyong_detail():\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get kuaiyong detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.url!=u'').filter(KC_LIST.source==19):\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"kuaiyong reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\tg = get_kuaiyong_detail_by_id(ret.url)\n\t\t\tif isinstance(g, EX):\n\t\t\t\terror_times += 1\n\t\t\telif g:\n\t\t\t\tcount += 1 \n\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('description', u''),\n\t\t\t\t\t\t\t\t\t\t\t'version' : g.get(u'版 本', u''),\n\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get(u'类 别', u''),\n\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get(u'大 小', u''),\n\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get(u'下载', u''),\n\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t'rating' : g.get('rating', u''),\n\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g.get('imgs', [])),\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\t\t\t\tif count % 100 == 0:\n\t\t\t\t\tmylogger.info(\"kuaiyong detail commit %s\" % count)\n\t\t\t\t\tdb_conn.commit()\n\tmylogger.info(\"get kuaiyong detail %s\" % count)\n\tdb_conn.commit()\n\ndef get_kuaiyong_detail_by_id(URL):\n\tmydict = {}\n\ttry:\n\t\tresponse = requests.get(URL, timeout=10)\n\t\tsoup = BeautifulSoup(response.text)\n\t\tbase_right = soup.find('div', class_='base-right')\n\t\tmydict = {}\n\t\tif base_right is not None:\n\t\t\tif base_right.find('h1') is not None:\n\t\t\t\tmydict[u'title'] = base_right.find('h1').text\n\t\t\tbase_list = base_right.find('div', class_='base-list')\n\t\t\tif base_list is not None:\n\t\t\t\tfor ret in base_list.find_all('p'):\n\t\t\t\t\tif ret.text:\n\t\t\t\t\t\tsegs = ret.text.split(u':')\n\t\t\t\t\t\tif len(segs) == 2:\n\t\t\t\t\t\t\tmydict[segs[0]] = segs[1]\n\t\t\t\t\t\telif len(segs)==1 and u'次下载' in ret.text:\n\t\t\t\t\t\t\tmydict[u'下载'] = re.sub(u'次下载|\\n|\\r', u'', ret.text)\n\t\t\t\tapp_star = base_list.find('p', class_='app-star') \n\t\t\t\tif app_star is not None:\n\t\t\t\t\tmydict['rating'] = len(app_star.find_all('span', class_='highlight'))\n\t\tdetail = soup.find('div', class_='detail')\n\t\tif detail is not None:\n\t\t\tpreview_contents = detail.find('div', class_='preview-content')\n\t\t\tif preview_contents is not None:\n\t\t\t\tmydict['imgs'] = [p.get('src') for p in preview_contents.find_all('img')]\n\t\tdetail_content = soup.find('div', class_='detail-content-inner')\n\t\tif detail_content is not None:\n\t\t\tmydict['description'] = detail_content.text\n\texcept Exception,e:\n\t\t#sleep(3.21)\n\t\tmylogger.error(\"%s\\t%s\" % (URL.encode('utf-8'), traceback.format_exc()))\n\t\treturn EX()\n\treturn mydict\n\n\ndef get_anzhi_detail():\n\t\n\tcount = 0\n\tmylogger.info(\"get kuaiyong detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.url!=u'').filter(KC_LIST.source==21):\n\t\tcount += 1 \n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\tg = get_anzhi_detail_by_id(ret.url)\n\t\t\tif g:\n\t\t\t\tdt = unicode(datetime.date.today())\n\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t'summary' : g.get('description', u''),\n\t\t\t\t\t\t\t\t\t'version' : g.get(u'版 本', u''),\n\t\t\t\t\t\t\t\t\t'game_type' : g.get(u'类 别', u''),\n\t\t\t\t\t\t\t\t\t'pkg_size' : g.get(u'大 小', u''),\n\t\t\t\t\t\t\t\t\t'download_num' : g.get(u'下载', u''),\n\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t'rating' : g.get('rating', u''),\n\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g.get('imgs', [])),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\tdb_conn.merge(item)\n\t\t\tif count % 100 == 0:\n\t\t\t\tmylogger.info(\"kuaiyong detail commit %s\" % count)\n\t\t\t\tdb_conn.commit()\n\tmylogger.info(\"get kuaiyong detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_anzhi_detail_by_id(URL):\n\tmydict = {}\n\ttry:\n\t\tresponse = s.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tsoup = BeautifulSoup(response.text)\n\t\t\tdetail_icon = soup.find('div', class_='detail_icon')\n\t\t\tif detail_icon is not None:\n\t\t\t\timg_div = detail_icon.find('img')\n\t\t\t\tif img_div is not None:\n\t\t\t\t\tmydict['img'] = u\"http://www.anzhi.com%s\" % img_div.get('src')\n\t\t\tdetail_line_ul = soup.find('ul', id='detail_line_ul')\n\t\t\tif detail_line_ul is not None:\n\t\t\t\tfor li in detail_line_ul.find_all('li'):\n\t\t\t\t\tsegs = li.text.split(u':')\n\t\t\t\t\tif len(segs) == 2:\n\t\t\t\t\t\tmydict[segs[0]] = segs[1]\n\t\t\tstars_detail = soup.find('div', id='stars_detail')\n\t\t\tif stars_detail is not None:\n\t\t\t\tm = re.search('(\\d+)px', stars_detail.get('style'))\n\t\t\t\tif m is not None:\n\t\t\t\t\tmydict['rating'] = round(m.group(1)/30.0, 1)\n\t\t\tapp_detail_infor = soup.find('div', class_='app_detail_infor')\n\t\t\tif app_detail_infor is not None:\n\t\t\t\tmydict['description'] = app_detail_infor.text.strip()\n\t\t\tsection_body = soup.find('div', class_='section-body')\n\t\t\tif section_body is not None:\n\t\t\t\tmydict['imgs'] = [u\"http://www.anzhi.com%s\" % i.get('src') for i in section_body.find_all('img')]\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL.encode('utf-8'), traceback.format_exc()))\n\treturn mydict\n\ndef get_wandoujia_detail():\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get wandoujia detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.url!=u'').filter(KC_LIST.source==23):\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"wandoujia reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\tg = get_wandoujia_detail_by_id(ret.url)\n\t\t\tif isinstance(g, EX):\n\t\t\t\terror_times += 1\n\t\t\telif g is not None:\n\t\t\t\tcount += 1 \n\t\t\t\tcategories = g.get('categories', [])\n\t\t\t\tgame_type = u\",\".join([c['name'] for c in categories if c['level']==2])\n\t\t\t\tapk = {}\n\t\t\t\tapk_list = g.get('apk', [])\n\t\t\t\tif len(apk_list) >= 1:\n\t\t\t\t\tapk = apk_list[0]\n\t\t\t\tdeveloper = g.get('developer', {})\n\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('description', u''),\n\t\t\t\t\t\t\t\t\t\t\t'version' : apk.get('versionName', u''),\n\t\t\t\t\t\t\t\t\t\t\t'game_type' : game_type,\n\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : apk.get('size', u''),\n\t\t\t\t\t\t\t\t\t\t\t'comment_num' : g.get('commentsCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('downloadCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t'author' : developer.get('name', u''),\n\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g.get('screenshots',{}).get('normal', [])),\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\t\t\t\tif count % 100 == 0:\n\t\t\t\t\tmylogger.info(\"wandoujia detail commit %s\" % count)\n\t\t\t\t\tdb_conn.commit()\n\tmylogger.info(\"get wandoujia detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_wandoujia_detail_by_id(url):\n\ttry:\n\t\tr = requests.get(url, timeout=10)\n\t\tif r.status_code == 200:\n\t\t\td = r.json()\n\t\t\tentity = d['entity']\n\t\t\tif entity:\n\t\t\t\tdetail = entity[0].get('detail', {})['appDetail']\n\t\t\t\treturn detail\n\texcept Exception,e:\n\t\tmylogger.error(\"### %s ### %s\" % (url.encode('utf-8'), traceback.format_exc()))\n\t\treturn EX()\n\treturn None\n\n\ndef get_meizu_detail_by_id(gid):\n\tURL = u\"http://api-game.meizu.com/games/public/detail/%s\" % gid\n\ttry:\n\t\tresponse = requests.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tj = response.json()\n\t\t\tif 'value' in j:\n\t\t\t\treturn j['value']\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL.encode('utf-8'), traceback.format_exc()))\n\t\treturn EX()\n\treturn None\n\n\ndef get_meizu_detail():\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get meizu detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.game_id!=u'').filter(KC_LIST.source==25):\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"meizu reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\tg = get_meizu_detail_by_id(ret.game_id)\n\t\t\tif isinstance(g, EX):\n\t\t\t\terror_times += 1\n\t\t\telif g is not None:\t\n\t\t\t\tcount += 1 \n\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t'summary' : g.get('description', u''),\n\t\t\t\t\t\t\t\t\t'version' : g.get('version_name', u''),\n\t\t\t\t\t\t\t\t\t'game_type' : g.get('category_name', u''),\n\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('size', u''),\n\t\t\t\t\t\t\t\t\t'comment_num' : g.get('evaluate_count', u''),\n\t\t\t\t\t\t\t\t\t'download_num' : g.get('download_count', u''),\n\t\t\t\t\t\t\t\t\t'author' : g.get('publisher', u''),\n\t\t\t\t\t\t\t\t\t'rating' : g.get('avg_score', u''),\n\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t'imgs' : u','.join([i.get('image') for i in g.get('images', [])]),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\tmylogger.info(\"get meizu detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_youku_detail_by_id(app_id):\n\tURL = u\"http://api.gamex.mobile.youku.com/v2/app/detail?product_id=1&app_id=%s\" % app_id\n\ttry:\n\t\tresponse = requests.get(URL, timeout=10)\n\t\tif response.status_code == 200:\n\t\t\tj = response.json()\n\t\t\treturn j['app']\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\\t%s\" % (URL.encode('utf-8'), traceback.format_exc()))\n\t\treturn EX()\n\treturn None\n\ndef get_youku_detail():\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get youku detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.game_id!=u'').filter(KC_LIST.source==13):\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"youku reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\tg = get_youku_detail_by_id(ret.game_id)\n\t\t\tif isinstance(g, EX):\n\t\t\t\terror_times += 1\n\t\t\telif g is not None:\t\n\t\t\t\tcount += 1 \n\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t'summary' : g.get('desc', u''),\n\t\t\t\t\t\t\t\t\t'version' : g.get('version', u''),\n\t\t\t\t\t\t\t\t\t'game_type' : g.get('type', u''),\n\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('size', u''),\n\t\t\t\t\t\t\t\t\t'rating' : g.get('score', u''),\n\t\t\t\t\t\t\t\t\t'download_num' : g.get('total_downloads', u''),\n\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g.get('screenshot', [])),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\tmylogger.info(\"get youku detail %s\" % count)\n\tdb_conn.commit()\n\ndef get_360zhushou_app_detail():\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get 360zhushou app detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.pkg_name!=u'').filter(KC_LIST.source==4):\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"360zhushou reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\turl = \"http://125.88.193.234/mintf/getAppInfoByIds?pname=%s\" % ret.pkg_name\n\t\t\ttry:\n\t\t\t\tr = requests.get(url, timeout=10)\n\t\t\t\tif r.status_code == 200:\n\t\t\t\t\tj = r.json()\n\t\t\t\t\tif len(j['data'])>=1:\n\t\t\t\t\t\tg = j['data'][0]\n\t\t\t\t\t\tcount += 1 \n\t\t\t\t\t\tcomments_url = \"http://comment.mobilem.360.cn/comment/getCommentTags?objid=%s\" % ret.game_id\n\t\t\t\t\t\tcomments_num = u''\n\t\t\t\t\t\ttry:\n\t\t\t\t\t\t\tget_comments_r = requests.get(comments_url)\n\t\t\t\t\t\t\tif get_comments_r.status_code == 200:\n\t\t\t\t\t\t\t\tcomments_j = get_comments_r.json()\n\t\t\t\t\t\t\t\tfor tag in comments_j['data']['tag']:\n\t\t\t\t\t\t\t\t\tif tag.get('title', u'') == u'全部':\n\t\t\t\t\t\t\t\t\t\tcomments_num = tag.get('num', u'')\n\t\t\t\t\t\texcept Exception,e :\n\t\t\t\t\t\t\tmylogger.error(\"360zhushou app comments #### #### \\t%s\" % (traceback.format_exc()))\n\t\t\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t'summary' : g.get('brief', u''),\n\t\t\t\t\t\t\t\t\t'version' : g.get('version_name', u''),\n\t\t\t\t\t\t\t\t\t'game_type' : g.get('category_name', u''),\n\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('size', u''),\n\t\t\t\t\t\t\t\t\t'rating' : g.get('rating', u''),\n\t\t\t\t\t\t\t\t\t'author' : g.get('corp', u''),\n\t\t\t\t\t\t\t\t\t'comment_num' : comments_num,\n\t\t\t\t\t\t\t\t\t'download_num' : g.get('download_times', u''),\n\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g.get('trumb', u'').split(u'|')),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"360zhushou app #### %s #### \\t%s\" % (ret.pkg_name.encode('utf-8'), traceback.format_exc()))\n\t\t\t\t\n\tmylogger.info(\"get 360 app detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_i4_app_detail():\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get i4 app detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.game_id!=u'').filter(KC_LIST.source==16):\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"i4 reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\turl = u\"http://app3.i4.cn/controller/action/online.go?store=3&module=1&id=%s&reqtype=5\" % ret.game_id\n\t\t\ttry:\n\t\t\t\tr = requests.get(url, timeout=10)\n\t\t\t\tif r.status_code == 200:\n\n\t\t\t\t\tj = r.json()\n\t\t\t\t\tif j['result']['list'] is not None and len(j['result']['list']) >= 1:\n\t\t\t\t\t\tg = j['result']['list'][0]\n\t\t\t\t\t\tcount += 1 \n\t\t\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t'summary' : g.get('shortNote', u''),\n\t\t\t\t\t\t\t\t\t'version' : g.get('shortVersion', u''),\n\t\t\t\t\t\t\t\t\t'game_type' : g.get('typeName', u''),\n\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('sizeByte', u''),\n\t\t\t\t\t\t\t\t\t'author' : g.get('company', u''),\n\t\t\t\t\t\t\t\t\t'download_num' : g.get('downloadCount', u''),\n\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t'imgs' : u','.join([u\"http://d.image.i4.cn/image/%s\" % img.get('url') for img in json.loads(g.get('image', []))]),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"i4 app #### %s #### \\t%s\" % (ret.game_id.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get i4 app detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_xyzs_app_detail():\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get xyzs app detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.game_id!=u'').filter(KC_LIST.source==26):\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"xyzs reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\turl = \"http://interface.xyzs.com/v2/ios/c01/app\"\n\t\t\t\td = {'itunesid': ret.game_id}\n\t\t\t\tr = requests.get(url, params=d, timeout=10)\n\t\t\t\tif r.status_code == 200:\n\t\t\t\t\tj = r.json()\n\t\t\t\t\tif j['code'] == 200:\n\t\t\t\t\t\tg = j['data']['app']\n\t\t\t\t\t\tcount += 1 \n\t\t\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t'summary' : g.get('content', u''),\n\t\t\t\t\t\t\t\t\t'version' : g.get('version', u''),\n\t\t\t\t\t\t\t\t\t'game_type' : g.get('apptypesno', u''),\n\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('size', u''),\n\t\t\t\t\t\t\t\t\t'download_num' : g.get('downloadnum', u''),\n\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t'imgs' : u','.join(g.get('iphoneimg', [])),\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"xyzs app #### %s #### \\t%s\" % (ret.game_id.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get xyzs app detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_91play_detail():\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get 91play app detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.game_id!=u'').filter(KC_LIST.source==27):\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"91play reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\turl = \"http://play.91.com/api.php/Api/index\"\n\t\t\t\traw_data = {\"id\": int(ret.game_id),\"firmware\":\"19\",\"time\":1449458211590,\"device\":1,\"action\":30005,\"app_version\":302,\"action_version\":4,\"mac\":\"7b715ce093480b34d6987\",\"debug\":0}\n\t\t\t\tresponse = requests.post(url, data=raw_data, timeout=10)\n\t\t\t\tif response.status_code == 200:\n\t\t\t\t\tj = response.json() \n\t\t\t\t\tif j['data'] is not None:\n\t\t\t\t\t\tg = json.loads(j['data'])\n\t\t\t\t\t\tcount += 1 \n\t\t\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t'summary' : g.get('content', u''),\n\t\t\t\t\t\t\t\t\t'rating' : g.get('score', u''),\n\t\t\t\t\t\t\t\t\t'version' : g.get('version', u''),\n\t\t\t\t\t\t\t\t\t'game_type' : g.get('type_name', u''),\n\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('app_size', u''),\n\t\t\t\t\t\t\t\t\t'author' : g.get('developer', u''),\n\t\t\t\t\t\t\t\t\t'download_num' : g.get('download_count', u''),\n\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t'imgs' : g.get('img_urls', u'')\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"91play app detail #### %s #### \\t%s\" % (ret.game_id.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get 91play app detail %s\" % count)\n\tdb_conn.commit()\n\ndef get_360_gamebox_detail():\n\tcount = 0\n\terror_times = 0\n\tmylogger.info(\"get 360_gamebox app detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.pkg_name!=u'').filter(KC_LIST.source==28):\n\t\tif error_times >= 10:\n\t\t\tmylogger.info(\"360_gamebox reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\turl = \"http://next.gamebox.360.cn/7/xgamebox/getappintro?pname=%s\" % ret.pkg_name\n\t\t\t\tresponse = requests.get(url, timeout=10)\n\t\t\t\tif response.status_code == 200:\n\t\t\t\t\tj = response.json() \n\t\t\t\t\tif j['data'] is not None and j['data']['info'] is not None and j['data']['info']:\n\t\t\t\t\t\tg = j['data']['info']\n\t\t\t\t\t\tcount += 1 \n\t\t\t\t\t\t#for k, v in g.iteritems():\n\t\t\t\t\t\t#\tprint k, v\n\t\t\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t'summary' : g.get('brief', u''),\n\t\t\t\t\t\t\t\t\t'rating' : g.get('rating', u''),\n\t\t\t\t\t\t\t\t\t'version' : g.get('version_name', u''),\n\t\t\t\t\t\t\t\t\t'game_type' : g.get('category_name', u''),\n\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('size', u''),\n\t\t\t\t\t\t\t\t\t'author' : g.get('corp', u''),\n\t\t\t\t\t\t\t\t\t'download_num' : g.get('download_times', u''),\n\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t'imgs' : u\",\".join(g.get('trumb', u'').split(u'|'))\n\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\t\tdb_conn.merge(item)\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tmylogger.error(\"360_gamebox app detail #### %s #### \\t%s\" % (ret.pkg_name.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get 360_gamebox app detail %s\" % count)\n\tdb_conn.commit()\n\ndef step1():\n\tget_xiaomi_new_detail()\n\tget_xiaomi_rpg_detail()\n\tget_open_play_detail()\n\tget_9game_detail()\n\tget_18183_detail()\n\tget_appicsh_detail()\n\tget_vivo_detail()\n\tget_coolpad_detail()\n\tget_gionee_detail()\n\tget_leveno_detail()\n\tget_iqiyi_detail()\n\tget_sogou_detail()\n\tget_dangle_detail()\n\tget_muzhiwan_detail()\n\tget_meizu_detail()\n\ndef step2():\n\tget_huawei_detail()\n\tget_wandoujia_detail()\n\tget_kuaiyong_detail()\n\tget_youku_detail()\n\tget_360zhushou_app_detail()\n\tget_i4_app_detail()\n\tget_xyzs_app_detail()\n\tget_91play_detail()\n\tget_360_gamebox_detail()\n\nif __name__ == '__main__':\n\tstep1()\n"
},
{
"alpha_fraction": 0.5993431806564331,
"alphanum_fraction": 0.6305418610572815,
"avg_line_length": 21.518518447875977,
"blob_id": "0ddfb9b68e7b4dcb4d5313d1884135ed1cdabdc9",
"content_id": "409e49bf558fed77f65ab641df45782f1a55f33e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1230,
"license_type": "no_license",
"max_line_length": 74,
"num_lines": 54,
"path": "/common/define.py",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport logging\n\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker, scoped_session\n\nimport socket\n\nlocalIP = socket.gethostbyname(socket.gethostname())#这个得到本地ip\n\nif localIP == u'192.168.1.215':\n\tPTPQ_DB_HOST = '127.0.0.1'\n\tPTPQ_DB_PORT = '3307'\n\tPTPQ_DB_USER = 'root'\n\tPTPQ_DB_PASS = 'dc@2013'\n\tPTPQ_DB_NAME = 'new_publish_game'\n\tLOG_FILE = \"/root/yanpengchen/logs\"\nelse:\n\t#sys.path.append('/home/cyp/Utils/common')\n\tPTPQ_DB_HOST = '127.0.0.1'\n\tPTPQ_DB_PORT = '3306'\n\tPTPQ_DB_USER = 'root'\n\tPTPQ_DB_PASS = 'admin'\n\tPTPQ_DB_NAME = 'dataeye'\n\tLOG_FILE = \"/home/cyp/logs\"\n\n\n\nPTPQ_ENGINE = create_engine(\n 'mysql+mysqldb://%s:%s@%s:%s/%s?charset=utf8' % (\n #'mysql+mysqldb://%s:%s@%s:%s/%s?charset=utf8' % (\n PTPQ_DB_USER,\n PTPQ_DB_PASS,\n PTPQ_DB_HOST,\n PTPQ_DB_PORT,\n PTPQ_DB_NAME\n ),\n echo=False,\n pool_recycle=14400,\n)\n\ndef new_session():\n return scoped_session(sessionmaker(bind=PTPQ_ENGINE, autoflush=False))\n\nsession = new_session()\n\ndef createtable(model, engine):\n try:\n pass\n model.__table__.drop(engine)\n except:\n pass\n model.__table__.create(engine)\n\n\n"
},
{
"alpha_fraction": 0.595433235168457,
"alphanum_fraction": 0.6674473285675049,
"avg_line_length": 39.66666793823242,
"blob_id": "d6e0a9046e3d4493476b4cc2654b4a69e68450ef",
"content_id": "736178aebe80bd263205e46d2789a36a6bbd43cd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "R",
"length_bytes": 1708,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 42,
"path": "/r_project/user_payment.R",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#! /usr/bin/env Rscript\n\nclusters <- 5\ntt <- read.delim(\"/home/cyp/data_eye/r_project/uid_rfm_payment_d30\", header=TRUE)\n#tt <- read.delim(\"/home/cyp/data_eye/r_project/test_set\", header=TRUE)\nd <- data.frame(tt[, c(2,10,11,12,13)], row.names=tt$uid)\nd$playtimes_d30 <- round(ifelse(d$logintimes_d30==0, 0, (d$duration_d30 / 30 / 60)), digits=2)\n#d$playtimes_d30 <- round(ifelse(d$logintimes_d30==0, 0, (d$duration_d30 / d$logintimes_d30 / 60)), digits=2)\n#summary(d$playtimes_d30)\n#d$level[d$playtimes_d30>=0 & d$playtimes_d30<5] <- 1\n#d$level[d$playtimes_d30>=5 & d$playtimes_d30<10] <- 2\n#d$level[d$playtimes_d30>=10 & d$playtimes_d30<30] <- 3\n#d$level[d$playtimes_d30>=30 & d$playtimes_d30<60] <- 4\n#d$level[d$playtimes_d30>=60] <- 5\n#mt <- with(d, table(d$level))\n#mt\n#d$logintimes_d30 <- NULL\nd$duration_d30 <- NULL\ncl <- kmeans(scale(d), clusters, iter.max = 20)\nrs <- data.frame(cl$cluster)\nmytable <- with(rs, table(rs$cl.cluster))\nmytable\n#dev.off()\nd <- cbind(d, rs)\n#d[which(d$cl.cluster==2),][1:10,]\npaytimes_d30 <- c()\npayamount_d30 <- c()\nplaytimes_d30 <- c()\ndate_diff <- c()\ntotal <- c()\nfor (i in 1:clusters) {\n\tc <- d[which(d$cl.cluster==i),]\n\tpaytimes_d30 <- append(paytimes_d30, round(median(c$paytimes_d30), digits=0))\n\tpayamount_d30 <- append(payamount_d30, round(median(c$payamount_d30), digits=2))\n\tplaytimes_d30 <- append(playtimes_d30, round(median(c$playtimes_d30), digits=2))\n\tdate_diff <- append(date_diff, round(median(c$date_diff), digits=2))\n\ttotal <- append(total, mytable[i])\n\tprint(paste(\"cluster \", i, \" size \", nrow(c)))\n\tprint(summary(c))}\nout <- data.frame(paytimes_d30, payamount_d30, playtimes_d30, date_diff, total)\nprint(out)\nwrite.table(out, \"out.txt\", sep=\"\\t\")\n"
},
{
"alpha_fraction": 0.591803252696991,
"alphanum_fraction": 0.6065573692321777,
"avg_line_length": 26.727272033691406,
"blob_id": "d43527668902d4bd7c1b5771589c9ecbc92efbc1",
"content_id": "4c5e7e1ce8859ccedf7644a59ed6aa7b47b945c5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2440,
"license_type": "no_license",
"max_line_length": 115,
"num_lines": 88,
"path": "/spider/get_pp_detail_by_day.py",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#encoding=utf-8\n\nimport requests\nimport json\nimport re\nfrom bs4 import BeautifulSoup\nfrom time import sleep\nimport traceback\nfrom config import *\nimport random\nimport xmltodict\nimport datetime\n\ndb_conn = new_session()\n\nfrom get_game_detail_by_day import mylogger, step2\n\nimport random\n\nclass T:\n\t\n\tdef __init__(self, status_code):\n\t\tself.status_code = status_code\n\nclass EX:\n\t\n\tmsg = \"\"\n\ndef get_pp_detail():\n\tcount = 0\n\tmylogger.info(\"get pp detail start ...\")\n\tfor ret in db_conn.query(KC_LIST).filter(KC_LIST.game_id!=u'').filter(KC_LIST.source==24):\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(GameDetailByDay).filter(GameDetailByDay.kc_id==ret.id).filter(GameDetailByDay.dt==dt).first()\n\t\tif not ins:\n\t\t\tg = get_pp_detail_by_id(ret.game_id)\n\t\t\tif g is not None:\t\n\t\t\t\tcomments_info = get_pp_comments_by_id(ret.game_id)\n\t\t\t\tcount += 1 \n\t\t\t\titem = GameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t'kc_id': ret.id,\n\t\t\t\t\t\t\t\t\t\t\t'summary' : g.get('content', u''),\n\t\t\t\t\t\t\t\t\t\t\t'version' : g.get('ver', u''),\n\t\t\t\t\t\t\t\t\t\t\t'game_type' : g.get('catName', u''),\n\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : g.get('fileSize', u''),\n\t\t\t\t\t\t\t\t\t\t\t'comment_num' : comments_info.get('commentCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t'download_num' : g.get('downCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t'topic_num_total' : g.get('collectCount', u''),\n\t\t\t\t\t\t\t\t\t\t\t'rating' : g.get('allVerStar', u''),\n\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t'imgs' : g.get('ipadImgs', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\tdb_conn.merge(item)\n\t\t\t\tif count % 50 == 0:\n\t\t\t\t\tsleep(3)\n\t\t\t\t\tmylogger.info(\"pp detail commit %s\" % count)\n\t\t\t\t\tdb_conn.commit()\n\t\t\t\tif count % 20 == 0:\n\t\t\t\t\tsleep(1.23)\n\tmylogger.info(\"get pp detail %s\" % count)\n\tdb_conn.commit()\n\n\ndef get_pp_detail_by_id(gid):\n\ttry:\n\t\td = {\"site\":1, \"id\": gid}\n\t\tp = proxies[random.randrange(len(proxies))]\n\t\tr = requests.post('http://pppc2.25pp.com/pp_api/ios_appdetail.php', data=d, proxies=p)\n\t\treturn r.json()\n\texcept Exception,e:\n\t\tmylogger.error(\"get %s detail \\t%s\" % (gid.encode('utf-8'), traceback.format_exc()))\n\treturn None\n\ndef get_pp_comments_by_id(gid):\n\ttry:\n\t\td = {\"s\":1, \"a\":101, \"i\": gid, \"p\":1, \"l\":1}\n\t\tp = proxies[random.randrange(len(proxies))]\n\t\tr = requests.post('http://pppc2.25pp.com/pp_api/comment.php', data=d, proxies=p)\n\t\tif r.status_code == 200:\n\t\t\treturn r.json()\n\texcept Exception,e:\n\t\tmylogger.error(\"get %s comments \\t%s\" % (gid.encode('utf-8'), traceback.format_exc()))\n\treturn {}\n\nif __name__ == '__main__':\n\tget_pp_detail()\n\tstep2()\n"
},
{
"alpha_fraction": 0.5125486254692078,
"alphanum_fraction": 0.587486743927002,
"avg_line_length": 21.80645179748535,
"blob_id": "4b1d69408d526a568341a142941ef4006c7c5baa",
"content_id": "7b7a6a354fbcd1dc9b9a0680a3aea238c0bf624b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3617,
"license_type": "no_license",
"max_line_length": 137,
"num_lines": 124,
"path": "/spider/check_proxy.py",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#encoding=utf-8\n\nimport sys\nimport requests\nimport json\nimport urllib\nimport traceback\nfrom config import *\nimport re\nfrom bs4 import BeautifulSoup\nimport time\nimport datetime\n\nmylogger = get_logger('proxy_list')\n\ns = requests.session()\ndb_conn = new_session()\n\nheaders = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36'}\n\n\ndef get_proxies():\n\treturn [{rc.type: u\"%s:%s\" % (rc.ip, rc.port)} for rc in db_conn.query(ProxyList)]\n\t\t\n\ndef check_proxy(proxy):\n\tstart = time.time()\n\ttry:\n\t\tr = requests.get(\"http://www.sogou.com/\", headers=headers)\n\t\t#r = requests.get(\"http://www.douban.com/\", headers=headers, proxies = proxy)\n\t\tif r.status_code == 200:\n\t\t\tend = time.time()\n\t\t\tprint proxy, end - start\n\texcept Exception,e:\n\t\tmylogger.error(\"%s\" % (traceback.format_exc()))\n\t\t\n\ndef test():\n\tcount = 0\n\tURL = \"http://zhushou.360.cn/list/index/cid/2/order/newest/?page=1\"\n\tfor p in get_proxies():\n\t\tr = s.get(URL, timeout=10)\n\t\t#r = s.get(URL, timeout=10, proxies=p)\n\t\tprint p, r.status_code\n\ndef f():\n\tfor re in db_conn.query(HotGames):\n\t\tre.dt = unicode(re.create_date.date())\n\tdb_conn.commit()\n\nif __name__ == '__main__':\n\tsource_map = {\n\t\t\tu\"百度手机助手web\"\t: 0,\n\t\t\tu\"小米游戏活跃榜\": 1,\n\t\t\tu\"360助手网络游戏\"\t: 2,\n\t\t\tu\"9游新游热榜\"\t: 3,\n\t\t\tu\"9游新游期待榜\"\t: 4,\n\t\t\tu\"360助手app单机榜\"\t: 5,\n\t\t\tu\"360助手app网游榜\"\t: 6,\n\t\t\tu\"360助手app新游榜\"\t: 7,\n\t\t\tu\"应用宝pc端单机榜\"\t: 8,#应用宝\n\t\t\tu\"应用宝pc端网游榜\"\t: 9,#应用宝\n\t\t\tu\"应用宝pc端新游榜\"\t: 10,#应用宝\n\t\t\tu\"百度手机助手app单机榜\"\t: 11,\n\t\t\tu\"百度手机助手app网游榜\"\t: 12,\n\t\t\tu\"百度手机助手app新游榜\"\t: 13,\n\t\t\tu\"当乐新游榜\"\t: 14,\n\t\t\tu\"小米游戏新品榜\"\t: 15,\n\t\t\tu\"vivo单机榜\"\t: 16,\n\t\t\tu\"vivo网游榜\"\t: 17,\n\t\t\tu\"vivo新游榜\"\t: 18,\n\t\t\tu\"金立活跃榜\"\t: 19,\n\t\t\tu\"金立飙升榜\"\t: 20,\n\t\t\tu\"酷派总榜\"\t: 21,\n\t\t\tu\"酷派网游榜\"\t: 22,\n\t\t\tu\"酷派新游榜\"\t: 23,\n\t\t\tu\"爱游戏下载榜\"\t: 24,#爱游戏榜单\n\t\t\tu\"爱游戏免费榜\"\t: 25,#爱游戏榜单\n\t\t\tu\"爱游戏网游榜\"\t: 26,#爱游戏榜单\n\t\t\tu\"豌豆荚单机榜\"\t: 27,\n\t\t\tu\"豌豆荚网游榜\"\t: 28,\n\t\t\tu\"爱奇艺下载榜\"\t: 29,\n\t\t\tu\"爱奇艺飙升榜\"\t: 30,\n\t\t\tu\"优酷单机榜\"\t: 31,\n\t\t\tu\"优酷网游榜\"\t: 32,\n\t\t\tu\"搜狗单机榜\"\t: 33,\n\t\t\tu\"搜狗网游榜\"\t: 34,\n\t\t\tu\"爱思助手排行榜\"\t: 35,\n\t\t\tu\"pp助手排行榜\"\t: 36,\n\t\t\tu\"快用助手排行榜\"\t: 37,\n\t\t\tu\"itools排行榜\"\t: 38,\n\t\t\tu\"xy助手\"\t: 39,\n\t\t\tu\"酷玩汇下载榜\"\t: 40,\n\t\t\tu\"360游戏大厅单机榜\"\t: 41,\n\t\t\tu\"360游戏大厅网游榜\"\t: 42,\n\t\t\tu\"应用宝pc端下载榜\"\t: 43,\n\t\t\tu\"百度手机助手app精品榜\"\t: 44,\n\t\t\tu\"爱游戏飙升榜\"\t: 45,\n\t\t\tu\"18183新游期待榜\"\t: 46,\n\t\t\tu\"18183热门手游榜\"\t: 47,\n\t\t\tu\"360助手app期待榜\"\t: 48,\n\t\t\tu\"小米游戏下载榜\"\t: 49,\n\t\t\tu\"小米游戏新网游\"\t: 50,\n\t\t\tu\"搜狗下载榜\"\t: 51,\n\t\t\t\"360助手儿童游戏\"\t\t: \"52\", \n\t\t\t\"360助手主角扮演\"\t\t: \"53\", \n\t\t\t\"360助手动作冒险\"\t\t: \"54\", \n\t\t\t\"360助手休闲益智\"\t\t: \"55\", #休闲益智\n\t\t\t\"360助手体育运动\"\t\t: \"56\", \n\t\t\t\"360助手飞行射击\"\t\t: \"57\", #飞行射击\n\t\t\t\"360助手经营策略\"\t\t: \"58\", \n\t\t\t\"360助手棋牌天地\"\t\t: \"59\", \n\t\t\t\"小米游戏app下载榜\"\t\t\t: \"60\", \n\t\t\t\"小米游戏app畅销榜\"\t\t\t: \"61\", \n\t\t\t\t}\n\tfor k,v in source_map.iteritems():\n\t\tins = db_conn.query(RankingChannel).filter(RankingChannel.id==v).first()\n\t\tif not ins:\n\t\t\titem = RankingChannel(**{'id': v, 'name':k})\n\t\t\tdb_conn.merge(item)\n\t\telse:\n\t\t\tins.name = k\n\tdb_conn.commit()\n\n"
},
{
"alpha_fraction": 0.5674123167991638,
"alphanum_fraction": 0.588573157787323,
"avg_line_length": 30.504762649536133,
"blob_id": "29849b6ae76f66418f13e62afa803255727f32e0",
"content_id": "08b4a889929c90b1bc99907f80d9ff63e8cf343c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3324,
"license_type": "no_license",
"max_line_length": 168,
"num_lines": 105,
"path": "/spider/get_360_detail_by_day.py",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#encoding=utf-8\n\nimport requests\nimport json\nimport re\nfrom bs4 import BeautifulSoup\nfrom time import sleep\nimport traceback\nfrom config import *\nimport random\nimport xmltodict\nimport datetime\n\nimport random\ndb_conn = new_session()\n\nfrom get_hot_game_detail_by_day import channel_map, mylogger\n\n\nheaders = {'user-agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/44.0.2403.125 Safari/537.36'}\n\n\ndef get_360zhushou_web_detail(channel_id):\n\tcount = 0\n\terror_times = 0\n\tsess = requests.session()\n\tmylogger.info(\"get 360zhushou web detail start ...\")\n\tids = channel_map.get(channel_id)\n\t_sql = \"select name, url from hot_games where source in (%s) and url!='' group by name, url\" % \",\".join([str(i) for i in ids])\n\tmylogger.info(\"### %s ###\" % _sql)\n\tfor ret in db_conn.execute(_sql):\n\t\tname, url = ret\n\t\tif error_times >= 20:\n\t\t\tmylogger.info(\"360zhushou web detail reach max error times ... \")\n\t\t\tbreak\n\t\tdt = unicode(datetime.date.today())\n\t\tins = db_conn.query(HotGameDetailByDay).filter(HotGameDetailByDay.name==name).filter(HotGameDetailByDay.dt==dt).filter(HotGameDetailByDay.channel==channel_id).first()\n\t\tif not ins:\n\t\t\ttry:\n\t\t\t\tp = proxies[random.randrange(len(proxies))]\n\t\t\t\tr = sess.get(url, timeout=20, headers=headers, proxies=p)\n\t\t\t\tif r.status_code == 200:\n\t\t\t\t\tsoup = BeautifulSoup(r.text)\n\t\t\t\t\timgs = u''\n\t\t\t\t\trating = u''\n\t\t\t\t\tsummary = u''\n\t\t\t\t\tcomment_num = u''\n\t\t\t\t\tdownload_num = u''\n\t\t\t\t\tpkg_size = u''\n\t\t\t\t\tpf = soup.find('div', class_='pf')\n\t\t\t\t\tif pf is not None:\n\t\t\t\t\t\tfor li in pf.find_all('span'):\n\t\t\t\t\t\t\tif u'分' in li.text:\n\t\t\t\t\t\t\t\tif re.search('\\d+\\.*\\d+', li.text) is not None:\n\t\t\t\t\t\t\t\t\trating = re.search('\\d+\\.*\\d+', li.text).group()\n\t\t\t\t\t\t\t#elif u'评价' in li.text:\n\t\t\t\t\t\t\t#\tif re.search('\\d+', li.text) is not None:\n\t\t\t\t\t\t\t#\t\tcomment_num = re.search('\\d+', li.text).group()\n\t\t\t\t\t\t\telif u'下载' in li.text:\n\t\t\t\t\t\t\t\t#if re.search('\\d+', li.text) is not None:\n\t\t\t\t\t\t\t\tdownload_num = li.text\n\t\t\t\t\t\t\telif u'M' in li.text:\n\t\t\t\t\t\t\t\tpkg_size = li.text\n\t\t\t\t\tbreif = soup.find('div', class_='html-brief')\n\t\t\t\t\ticons = []\n\t\t\t\t\tif breif is not None:\n\t\t\t\t\t\tsummary = breif.text\n\t\t\t\t\t\ticons = [img.get('src') for img in breif.find_all('img')]\n\t\t\t\t\tif icons:\n\t\t\t\t\t\timgs = u','.join(icons)\n\t\t\t\t\tmydict = {}\n\t\t\t\t\tbase_info = soup.find('div', class_=\"base-info\")\n\t\t\t\t\tif base_info is not None:\n\t\t\t\t\t\tfor td in base_info.find_all('td'):\n\t\t\t\t\t\t\tsegs = td.text.split(u':')\n\t\t\t\t\t\t\tif len(segs) == 2:\n\t\t\t\t\t\t\t\tmydict[segs[0]] = segs[1]\n\t\t\t\t\tcount += 1\n\t\t\t\t\titem = HotGameDetailByDay(**{\n\t\t\t\t\t\t\t\t\t\t\t\t'name': name,\n\t\t\t\t\t\t\t\t\t\t\t\t'channel': channel_id,\n\t\t\t\t\t\t\t\t\t\t\t\t'dt' : dt,\n\t\t\t\t\t\t\t\t\t\t\t\t'imgs' : imgs,\n\t\t\t\t\t\t\t\t\t\t\t\t'summary' : summary,\n\t\t\t\t\t\t\t\t\t\t\t\t'pkg_size' : pkg_size,\n\t\t\t\t\t\t\t\t\t\t\t\t'rating' : rating,\n\t\t\t\t\t\t\t\t\t\t\t\t'author' : mydict.get(u'作者', u''),\n\t\t\t\t\t\t\t\t\t\t\t\t'comment_num' : comment_num,\n\t\t\t\t\t\t\t\t\t\t\t\t'download_num' : download_num,\n\t\t\t\t\t\t\t\t\t\t\t\t})\n\t\t\t\t\tdb_conn.merge(item)\n\t\t\t\t\tif count % 100 == 0:\n\t\t\t\t\t\tmylogger.info(\"360 detail %s commit\" % count)\n\t\t\t\t\t\tdb_conn.commit()\n\t\t\texcept Exception,e:\n\t\t\t\terror_times += 1\n\t\t\t\tsleep(3.21)\n\t\t\t\tmylogger.error(\"%s\\t%s\" % (url.encode('utf-8'), traceback.format_exc()))\n\tmylogger.info(\"get 360zhushou web detail %s\" % count)\n\tdb_conn.commit()\n\n\nif __name__ == '__main__':\n\tget_360zhushou_web_detail(22)\n"
},
{
"alpha_fraction": 0.7162871956825256,
"alphanum_fraction": 0.7460595369338989,
"avg_line_length": 32.588233947753906,
"blob_id": "ac4b58d0d9a9e7f697ba85d9608eeedfe45dfe07",
"content_id": "5a06ca61513548500823052c65905c5f0e6a5d4f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 617,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 17,
"path": "/common/get_logger.py",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\nimport os\nimport logging\nfrom logging.handlers import RotatingFileHandler\nfrom define import LOG_FILE\n\n\n#定义一个RotatingFileHandler,最多备份5个日志文件,每个日志文件最大10M\ndef get_logger(logname):\n Rthandler = RotatingFileHandler('%s/%s.log' % (LOG_FILE, logname), maxBytes=10*1024*1024, backupCount=5)\n formatter = logging.Formatter('%(levelname)s\\t%(asctime)-15s\\t%(message)s')\n Rthandler.setFormatter(formatter)\n logger = logging.getLogger(logname)\n logger.setLevel(logging.INFO)\n logger.addHandler(Rthandler)\n return logger\n"
},
{
"alpha_fraction": 0.5456998348236084,
"alphanum_fraction": 0.5979763865470886,
"avg_line_length": 29.88541603088379,
"blob_id": "fd04155a42bbdd6d7923adff66403a271ce54e2d",
"content_id": "0ea0ceef0b4dd41117bced661a8852b93548d023",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6170,
"license_type": "no_license",
"max_line_length": 132,
"num_lines": 192,
"path": "/spider/get_entries.py",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#encoding=utf-8\n\nimport sys\nsys.path.append('/home/cyp/Utils/common')\nfrom define import *\nfrom model import *\nimport requests\nimport json\nimport re\nfrom bs4 import BeautifulSoup\n\ndb_conn = new_session()\ns = requests.session()\n\ntv_names = \"虎妈猫爸,嘿老头,酷爸俏妈,待嫁老爸\"\nnames = \"爸爸去哪儿,爸爸回来了\"\n\nurl = \"http://so.iqiyi.com/so/q_%s\"\n\ndef func():\n\tURLS = [(i, url %i) for i in names.split(',')[:1]]\n\tfor i in URLS:\n\t\tr = s.get(i[1])\n\t\tsoup = BeautifulSoup(r.text)\n\t\tfor link in soup.find_all(\"a\", class_=\"album_link\"):\n\t\t\tif 'javascript' not in link.get('href'):\n\t\t\t\t#href = link.get('href')\n\t\t\t\t#m = re.search('data-player-tvid=\\\"(\\d+)\\\"', s.get(href).text)\n\t\t\t\t#tvid = m.group(1) if m is not None else ''\n\t\t\t\t#m2 = re.search('data-qitancomment-qitanid=\\\"(\\d+)\\\"', s.get(href).text)\n\t\t\t\t#qitanid = m2.group(1) if m2 is not None else ''\n\t\t\t\t#if tvid and qitanid:\n\t\t\t\t#\tprint i[0], link.get('title').encode('utf-8'), link.get('href').encode('utf-8'), tvid, qitanid\n\t\t\t\tif re.search(u'第\\d+集', link.get('title')) is not None: \n\t\t\t\t\tprint i[0], link.get('title').encode('utf-8'), link.get('href').encode('utf-8')\n\n\ndef func2():\n\tURLS = [(i, url %i) for i in tv_names.split(',')[2:3]]\n\tfor i in URLS:\n\t\tr = s.get(i[1])\n\t\tsoup = BeautifulSoup(r.text)\n\t\tfor link in soup.find_all(\"a\", class_=\"album_link\"):\n\t\t\tif 'javascript' not in link.get('href'):\n\t\t\t\t#href = link.get('href')\n\t\t\t\t#m = re.search('data-player-tvid=\\\"(\\d+)\\\"', s.get(href).text)\n\t\t\t\t#tvid = m.group(1) if m is not None else ''\n\t\t\t\t#m2 = re.search('data-qitancomment-qitanid=\\\"(\\d+)\\\"', s.get(href).text)\n\t\t\t\t#qitanid = m2.group(1) if m2 is not None else ''\n\t\t\t\t#if tvid and qitanid:\n\t\t\t\tprint i[0], link.get('title').encode('utf-8'), link.get('href').encode('utf-8')\n\t\t\t\t\t#print i[0], link.get('title').encode('utf-8'), link.get('href').encode('utf-8'), tvid.encode('utf-8'), qitanid.encode('utf-8')\n\t\t\t\ndef process():\n\twith open('id_list') as f:\n\t\tfor line in f.readlines():\n\t\t\ttv_name, episode, url, tvid, qitanid = line.rstrip().split()\n\t\t\tins = db_conn.query(IQIYI_TV).filter(IQIYI_TV.tv_name==tv_name).filter(IQIYI_TV.episode==episode).first()\n\t\t\tif not ins:\n\t\t\t\titem = IQIYI_TV(**{'tv_name':tv_name, 'episode':episode, 'url':url, 'tvid':int(tvid), 'qitanid' : int(qitanid)})\n\t\t\t\tdb_conn.add(item)\n\tdb_conn.commit()\n\n\ndef get_link_from_file():\n\tf = open('kbqm')\n\tsoup = BeautifulSoup(f.read().decode('utf-8'))\n\tfor i in soup.find_all(\"a\", class_=\"album_link\"):\n\t\tif 'javascript' not in i.get('href'):\n\t\t\tprint i.get('title'), i.get('href')\n\ndef get_baba_comeback_entry():\n\twith open('babaqunar') as f:\n\t\tfor line in f.readlines():\n\t\t\tr = s.get(line.rstrip())\n\t\t\tm = re.search('data-player-tvid=\\\"(\\d+)\\\"', r.text)\n\t\t\ttvid = m.group(1) if m is not None else ''\n\t\t\tm2 = re.search('data-qitancomment-qitanid=\\\"(\\d+)\\\"', r.text)\n\t\t\tqitanid = m2.group(1) if m2 is not None else ''\n\t\t\t#if tvid and qitanid:\n\t\t\tprint tvid, qitanid\n\t\t\ttv_name = '爸爸去哪儿'\n\t\t\titem = IQIYI_TV(**{'tv_name':tv_name, 'episode':tvid, 'url':line.rstrip(), 'tvid':int(tvid), 'qitanid' : int(qitanid)})\n\t\t\tdb_conn.add(item)\n\tdb_conn.commit()\n\t\t\t\ndef get_xiaomi():\n\tf = open('xm')\n\tsoup = BeautifulSoup(f.read().decode('utf-8'))\n\tll = [re.split('\\_|\\.', i.get('href'))[-2] for i in soup.find_all(\"a\")]\n\tprint len(ll)\n\t#for i in soup.find_all(\"a\"):\n#\t\thref = i.get('href')\n#\t\tprint re.split('\\_|\\.', href)\n\n\n#_category_list_360 = [19, 20, 51, 52, 53, 54, 101587, 102238, 100451]\n_category_list_360 = [11, 12, 14, 15,16, 17,18, 102228, 102230, 102231, 102232, 102233, 102239]\n\ndef get_360_list(cid, page):\n\trs = []\n\tr = s.get('http://zhushou.360.cn/list/index/cid/%s?page=%s' % (cid, page))\n\tsoup = BeautifulSoup(r.text)\n\tfor i in soup.find(\"ul\", class_=\"iconList\").find_all(\"li\"):\n\t\titem = i.find('h3').find('a')\n\t\trs.append((item.text, item.get('sid')))\n\treturn rs\n\ndef get_360_tags(sid):\n\tr = s.get('http://zhushou.360.cn/detail/index/soft_id/%s' % sid)\n\tsoup = BeautifulSoup(r.text)\n\ttags = soup.find(\"div\", class_=\"app-tags\")\n\tif tags is not None:\n\t\treturn u\",\".join([i.text for i in tags.find_all(\"a\")])\n\treturn u\"\"\n\ndef get_360_main():\n\tcount = 0\n\tfor c in _category_list_360:\n\t\t#category = gameid2category.get(str(c))\n\t\tcategory = id2category.get(str(c))\n\t\tfor i in xrange(1, 51):\n\t\t\ticon_list = get_360_list(c, i)\n\t\t\t#print category, \",\".join([i[0] for i in icon_list])\n\t\t\tfor icon in icon_list:\n\t\t\t\tprint \"%s\\t%s\\t%s\" % (icon[1], icon[0].encode('utf-8'), category)\n#\t\t\t\ttags = get_360_tags(icon[1])\n#\t\t\t\t#print icon[0], icon[1], tags\n#\t\t\t\tcount += 1\n#\t\t\t\t#ins = db_conn.query(APPLIST2).filter(APPLIST2.sid==int(icon[1])).first()\n#\t\t\t\t#if not ins:\n#\t\t\t\titem = APPLIST2(**{'sid': int(icon[1]), 'app_name': icon[0], 'tags': tags, 'category':category})\n#\t\t\t\tdb_conn.merge(item)\n#\t\t\t\tif count % 1000 == 0:\n#\t\t\t\t\tprint \"%s commit\" % count\n#\t\t\t\t\tdb_conn.commit()\n#\tdb_conn.commit()\n\nid2category = {\n\"11\"\t :\"系统安全\", \n\"12\" \t :\"通讯社交\",\n\"14\"\t :\"影音视听\",\n\"15\"\t :\"新闻阅读\",\n\"16\"\t :\"生活休闲\",\n\"18\" \t :\"主题壁纸\",\n\"17\" \t :\"办公商务\",\n\"102228\" :\"摄影摄像\",\n\"102230\" :\"购物优惠\",\n\"102231\" :\"地图旅游\",\n\"102232\" :\"教育学习\",\n\"102139\" :\"金融理财\",\n\"102233\" :\"健康医疗\"}\n\n\ngameid2category = {\n\"20\": \t\t\"动作冒险\", \n\"19\": \t\t\"休闲益智\",\n\"54\": \t\t\"棋牌天地\",\n\"51\": \t\t\"体育竞速\",\n\"53\": \t\t\"经营策略\",\n\"52\": \t\t\"飞行射击\",\n\"100451\": \t\"网络游戏\",\n\"102238\": \t\"儿童游戏\",\n\"101587\": \t\"角色扮演\"\n}\n\ndef match():\n\twith open('dataeye_games') as f:\n\t\tfor line in f.readlines()[:]:\n\t\t\tapp = line.rstrip()\n\t\t\t#print \"****\", app\n\t\t\tins = db_conn.query(APPLIST2).filter(APPLIST2.app_name==app).filter(APPLIST2.tags!=u'').first()\n\t\t\tif ins:\n\t\t\t\tif len(ins.tags) != 0:\n\t\t\t\t\tprint \"%s\\t%s\" % (app, ins.tags.encode('utf-8'))\n\n\ndef get_ip_info():\n\tURL = \"http://ip.chinaz.com/\"\n\tpayload = {'IP': '058.205.255.255,183.13.153.142,058.206.159.2551'}\n\tr = s.get(URL, params=payload)\n\tsoup = BeautifulSoup(r.text)\n\tfor i in soup.find(\"span\", id=\"status\").find_all('strong'):\n\t\tsegs = i.text.split(\": \")[1].split(\"==>>\")\n\t\t\n\nif __name__ == '__main__':\n\t#get_360_tags(1838349)\n\tget_360_main()\n\t#match()\n\t#get_ip_info()\n"
},
{
"alpha_fraction": 0.5367231369018555,
"alphanum_fraction": 0.6836158037185669,
"avg_line_length": 38.69230651855469,
"blob_id": "e099600044695bfdea1785df1bc27bc1c5c4e00f",
"content_id": "6bbd35875e8da319caf97ef2c11d78e1d1661a05",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 531,
"license_type": "no_license",
"max_line_length": 105,
"num_lines": 13,
"path": "/bi_report/define.py",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python\r\n#-*- coding:utf-8 -*-\r\nimport MySQLdb\r\n\r\n#dc_business_user\r\nconn1 = MySQLdb.connect(host=\"192.168.1.175\",port=3306,user=\"dbuser\",passwd=\"user#2013!\",charset=\"utf8\")\r\n#companyid < 382 and companyid !=49\r\nconn2 = MySQLdb.connect(host=\"192.168.1.171\",port=3307,user=\"dbuser\",passwd=\"user#2013!\",charset=\"utf8\")\r\nconn3 = MySQLdb.connect(host=\"192.168.1.175\",port=3307,user=\"dbuser\",passwd=\"user#2013!\",charset=\"utf8\")\r\n\r\ndb_175_3306 = conn1.cursor()\r\ndb_171_3306 = conn2.cursor()\r\ndb_175_3307 = conn3.cursor()\r\n\r\n"
},
{
"alpha_fraction": 0.6491228342056274,
"alphanum_fraction": 0.6666666865348816,
"avg_line_length": 29.176469802856445,
"blob_id": "7c5f38fbe960aa08ad47bc36e6295dd44316c4d5",
"content_id": "7cc2aa302ec9cdd2fbb9e346bbdcc1b8e598ac24",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1030,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 34,
"path": "/spider/selenium_demo.py",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#encoding=utf-8\n\nfrom selenium import webdriver\nfrom selenium.webdriver.common.by import By\nfrom get_kc_list import *\n\ndef func():\n\tdriver = webdriver.Firefox()\n\t#driver.get(\"http://data.auto.qq.com/car_brand/index.shtml#_其他___\")\n\tdriver.get(\"http://data.auto.qq.com/car_brand/index.shtml?type=serial\")\n\t#print driver.page_source.encode('utf-8')\n\tsoup = BeautifulSoup(driver.page_source)\n\tfor rs in soup.find_all('div', class_='listAll'):\n\t\tid = rs.get('id').encode('utf-8')\n\t\tfor i in rs.find_all('div', class_='listData'):\n\t\t\tfor j in i.find('ul').find_all('li'):\n\t\t\t\tdt = j.find('dt')\n\t\t\t\tprint id,dt.find('a').get('href').encode('utf-8'), dt.text.encode('utf-8')\n\t\t\t\tfor k in j.find_all('dd'):\n\t\t\t\t\tprint k.text.encode('utf-8')\n\tdriver.close()\n\n\n\ndef func2():\n\tdriver = webdriver.Firefox()\n\tdriver.get(\"http://car.auto.ifeng.com/series/2382/spec/37691/\")\n\treturn driver.page_source.encode('utf-8')\n\t#soup = BeautifulSoup(driver.page_source)\n\tdriver.close()\n\nif __name__ == '__main__':\n\tprint func2()\n"
},
{
"alpha_fraction": 0.6185907125473022,
"alphanum_fraction": 0.643478274345398,
"avg_line_length": 31.37864112854004,
"blob_id": "170616ffbc605df856411613e57fb9aa1d6e2d3c",
"content_id": "1181ea803fe00510b793229a81d3159d6d761daa",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3353,
"license_type": "no_license",
"max_line_length": 295,
"num_lines": 103,
"path": "/spider/get_comments.py",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n#encoding=utf-8\n\nimport sys\nsys.path.append('/home/cyp/Utils/common')\nfrom define import *\nfrom model import *\nimport requests\nimport traceback\nimport json\nimport re\nfrom bs4 import BeautifulSoup\nfrom time import sleep\n\ns = requests.session()\n\nIQIYI_SORT_TYPE = ['hot', 'add_time']\n\n\ndef get_iqiyi_comments(qitanid, page, page_size, tvid):\n\ttry:\n\t\turl = \"http://api.t.iqiyi.com/qx_api/comment/get_video_comments?aid=%s&categoryid=6&cb=fnsucc&escape=true&need_reply=true&need_total=1&page=%s&page_size=%s&page_size_reply=3&qitan_comment_type=1&qitancallback=fnsucc&sort=add_time&qitanid=%s&tvid=%s\" % (qitanid, page, page_size, qitanid, tvid)\n\t\tr = s.get(url, timeout=10)\n\t\tp = re.compile(u'var\\s*?fnsucc=([\\s\\S]*)')\n\t\tm = p.search(r.text.strip())\n\t\tif m is not None:\n\t\t\troot = json.loads(m.group(1))\n\t\t\treturn root['data']['comments']\n\texcept Exception,e:\n\t\tprint traceback.format_exc()\n\treturn None\n\t#for i in root['data']['comments']:\n\t#\t\tprint i['content']\n\ndef get_hunan_comments():\n\turl = \"http://comment.hunantv.com/video_comment/list/?callback=callback&type=hunantv2014&subject_id=1005517&page=2\"\n\tr = s.get(url)\n\tp = re.compile('callback\\(([\\s\\S]*)\\)')\n\tm = p.search(r.text.strip())\n\troot = json.loads(m.group(1))\n\tfor i in root['comments']:\n\t\tprint i['content']\n\ndef get_letv_comments(pagesize, page, xid):\n\turl = \"http://api.my.letv.com/vcm/api/list?jsonp=callback&type=video&rows=%s&page=%s&sort=&xid=%s&pid=0\" % (pagesize, page, xid)\n\tr = s.get(url)\n\tp = re.compile('callback\\(([\\s\\S]*)\\)')\n\tm = p.search(r.text.strip())\n\tif m is not None:\n\t\troot = json.loads(m.group(1))\n\t\treturn root['data']\n\treturn None\n\ndef main():\n\tcount = 0\n\tfor ret in session.execute(u\"select tv_name, episode, tvid, qitanid from iqiyi_tv where tv_name='爸爸去哪儿'\"):\n\t\ttv_name, episode, tvid, qitanid = ret\n\t\tprint tv_name, episode, tvid, qitanid\n\t\tfor i in xrange(1, 11):\n\t\t\ttry:\n\t\t\t\tcomments = get_iqiyi_comments(qitanid, i, 500, tvid)\n\t\t\t\tsleep(1.11)\n\t\t\t\tif comments is not None:\n\t\t\t\t for ret in comments:\n\t\t\t\t\t if ret['content']:\n\t\t\t\t\t\t count += 1\n\t\t\t\t\t\t item = IQIYI_TV_COMMENTS(**{'comment_id': ret['contentId'], 'comment': ret['content'],\n\t\t\t\t\t\t\t\t\t\t\t\t'tv_name': tv_name, 'episode': episode})\n\t\t\t\t\t\t session.merge(item)\n\t\t\t\t\t\t if count % 2000 == 0:\n\t\t\t\t\t\t\t\tprint \"%s commit\" % count\n\t\t\t\t\t\t\t\tsession.commit()\n\t\t\texcept Exception,e:\n\t\t\t\tprint traceback.format_exc()\n\t\t\t\tsession.rollback()\n\tsession.commit()\n\ndef get_kbqm_comments():\n\ttv_name = \"酷爸俏妈\"\n\tf = open('kbqm')\n\tsoup = BeautifulSoup(f.read().decode('utf-8'))\n\t_episode = set([])\n\tfor i in soup.find_all(\"a\", class_=\"album_link\"):\n\t\tif 'javascript' not in i.get('href'):\n\t\t\tif i.get('title') not in _episode:\n\t\t\t\txid = re.search(u'\\d+', i.get('href')).group()\n\t\t\t\tprint i.get('title'), xid\n\t\t\t\t_episode.add(i.get('title'))\n\t\t\t\tcomments = get_letv_comments(500, 1, xid)\n\t\t\t\tif comments is not None:\n\t\t\t\t\tfor ret in comments:\n\t\t\t\t\t\tif ret['content']:\n\t\t\t\t\t\t\titem = LETV_TV_COMMENTS(**{'comment_id': ret['_id'], 'comment': ret['content'],'tv_name': tv_name, 'episode': i.get('title')})\n\t\t\t\t\t\t\tsession.merge(item)\n\tsession.commit()\n\n\nif __name__ == '__main__':\n\t#get_iqiyi_comments(20, 500, IQIYI_SORT_TYPE[1], babaqunar_tv_id[1])\n\t#print get_iqiyi_comments(1155064, 1, 100, 218444100)\n\t#get_letv_comments(20, 1, 22463310)\n\t#get_kbqm_comments()\n\tmain()\n"
},
{
"alpha_fraction": 0.6133751273155212,
"alphanum_fraction": 0.6429815292358398,
"avg_line_length": 32.38372039794922,
"blob_id": "4f39570f77add78dccae8aa59e0dd3dd82fa58ab",
"content_id": "30fcd679cb07906ded05f4421a78fd81b1b0084c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2933,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 86,
"path": "/spider/to_excel.py",
"repo_name": "cash2one/data_eye",
"src_encoding": "UTF-8",
"text": "#!usr/bGin/env python\n#-*- coding:utf-8 -*-\n\nimport urllib\nimport os\nimport socket\nimport sys\nsys.path.append('/home/cyp/Utils/common')\nfrom define import *\nfrom model import *\nfrom bs4 import BeautifulSoup\nimport traceback\nfrom get_logger import *\nmylogger = get_logger('hot_game')\n\ndb_conn = new_session()\nimport xlsxwriter\n\n\ndef to_excel():\n\tworkbook = xlsxwriter.Workbook('demo.xlsx')\n\t#worksheet = workbook.add_worksheet(u\"百度游戏\")\n\t#bold = workbook.add_format({'bold': True})\n\t#worksheet.write(0, 0, u'排名', bold)\n\t#worksheet.write(0, 1, u'游戏名', bold)\n\t#worksheet.set_column(0, 1, 20)\n\t#worksheet.write(0, 2, u'ICON', bold)\n\t#_row = 1\n\tmydict = {}\n\tid2source = {\n\t\t\t\t\"0\": u\"百度游戏\",\n\t\t\t\t\"1\": u\"小米游戏\",\n\t\t\t\t\"2\": u\"360游戏\",\n\t\t\t\t\"3\": u\"9游游戏\",\n\t\t\t\t\"4\": u\"appannie游戏\",\n\t\t\t\t}\n\tfor ret in db_conn.query(HotGames).filter(HotGames.create_date==\"2015-09-02\").filter(HotGames.source==3):\n\t#for ret in db_conn.query(HotGames).filter(HotGames.create_date==\"2015-09-02\"):\n\t\tsource = id2source.get(str(ret.source))\n\t\tif source in mydict:\n\t\t\tmydict[source].append((ret.rank, ret.name, ret.source))\n\t\telse:\n\t\t\tmydict[source] = [(ret.rank, ret.name, ret.source)]\n\tfor source_name, d in mydict.iteritems():\n\t\tprint source_name, len(d)\n\t\tworksheet = workbook.add_worksheet(source_name)\n\t\tbold = workbook.add_format({'bold': True})\n\t\tworksheet.write(0, 0, u'排名', bold)\n\t\tworksheet.write(0, 1, u'游戏名', bold)\n\t\tworksheet.set_column(0, 1, 20)\n\t\tworksheet.write(0, 2, u'ICON', bold)\n\t\t_row = 1\n\t#for ret in db_conn.query(HotGames).filter(HotGames.create_date==\"2015-09-02\").filter(HotGames.source==0):\n\t\t#worksheet.set_row(_row, 50)\n\t\tfor ret in d:\n\t\t\ttry:\n\t\t\t\trank, name, source = ret\n\t\t\t\tworksheet.write(_row, 0, rank)\n\t\t\t\tworksheet.write(_row, 1, name)\n\t\t\t\tpic_name = u\"/home/cyp/data_eye/spider/pics/%s_%s\" % (name, source)\n\t\t\t\t#pic_name = u\"/home/cyp/data_eye/spider/pics/%s_%s\" % (name.encode('utf-8'), str(source))\n\t\t\t\tif source_name == u\"360游戏\":\n\t\t\t\t\tworksheet.insert_image('C%s' % str(_row+1), pic_name, {'x_scale': 1, 'y_scale': 1})\n\t\t\t\telse:\n\t\t\t\t\tworksheet.insert_image(_row, 2, pic_name, {'x_offset': 40, 'y_offset': 40})\n\t\t\t\t\t#worksheet.insert_image('C%s' % str(_row+1), pic_name, {'x_scale': 0.4, 'y_scale': 0.3})\n\t\t\t\tworksheet.set_row(_row, 80)\n\t\t\t\t_row += 6\n\t\t\texcept Exception,e:\n\t\t\t\tprint name, \"\\n\",traceback.format_exc()\n\tworkbook.close()\n\ndef check_and_convert():\n\tfrom PIL import Image\n\tfor f in os.listdir(\"/home/cyp/data_eye/spider/pics\"):\n\t\tim = Image.open(\"/home/cyp/data_eye/spider/pics/%s\" % f)\n\t\tif im.format == \"GIF\":\n\t\t\tprint f\n\t\t\tos.rename(\"/home/cyp/data_eye/spider/pics/%s\" % f, \"/home/cyp/data_eye/spider/pics/%s_old\" % f) \n\t\t\tim.save(\"/home/cyp/data_eye/spider/pics/%s.png\" % f)\n\t\t\tos.rename(\"/home/cyp/data_eye/spider/pics/%s.png\" % f, \"/home/cyp/data_eye/spider/pics/%s\" % f) \n\nif __name__ == '__main__':\n\t#download_pic()\n\tto_excel()\n\t#check_and_convert()\n"
}
] | 22 |
shenlong95/Robust-GAN-Scatter | https://github.com/shenlong95/Robust-GAN-Scatter | 9ba6555308971a1e0e90ee583cd0d8b31cd04e8a | 29d12a20964ed76ad226364f9849e435e673a336 | 0075aa37b9c0a6f1a7abb49ee774440671ca75d0 | refs/heads/master | 2022-02-26T04:17:09.686139 | 2019-03-06T01:11:19 | 2019-03-06T01:11:19 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7254902124404907,
"alphanum_fraction": 0.741830050945282,
"avg_line_length": 42.71428680419922,
"blob_id": "196fc5d692c11a904515932f013e35be888d2f14",
"content_id": "642809402365d7d7419494d15f6b92e89bf88bba",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 306,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 7,
"path": "/README.md",
"repo_name": "shenlong95/Robust-GAN-Scatter",
"src_encoding": "UTF-8",
"text": "# Robust Estimation for Scatter (Covariance) via GANs.\nThis repository provides a PyTorch implementation of **[Chao Gao, Yuan Yao and Weizhi Zhu, \"\nGenerative Adversarial Nets for Robust Scatter Estimation: A Proper Scoring Rule Perspective\"].**\n\n## Environment\n* Python 3.6\n* [PyTorch 0.4.1](http://pytorch.org/)\n"
},
{
"alpha_fraction": 0.6224783658981323,
"alphanum_fraction": 0.6253602504730225,
"avg_line_length": 19.47058868408203,
"blob_id": "df5405aac4c8e48ba28255640c8ae65cf8e45e61",
"content_id": "cb4d50a7b4ca8f26b2d12752b29979bd951b5338",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 347,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 17,
"path": "/main.py",
"repo_name": "shenlong95/Robust-GAN-Scatter",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\nimport os\nimport logging\nfrom fgan import fgan\nfrom config import get_config\n\nlogger = logging.getLogger('InfoLog')\n\ndef main(config):\n logger.info(f'***START TRAINING ***'.upper())\n logger.info(config.__dict__)\n f = fgan(config)\n f.train()\n\nif __name__ == '__main__':\n config = get_config()\n main(config)"
},
{
"alpha_fraction": 0.4830062985420227,
"alphanum_fraction": 0.49467745423316956,
"avg_line_length": 42.9295768737793,
"blob_id": "4233a59af592e3f46ce36b7ff00c7b1fed1014ec",
"content_id": "f4249abd9d8b3b62e5dcc99749fd5ebb2fecd825",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 15594,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 355,
"path": "/fgan.py",
"repo_name": "shenlong95/Robust-GAN-Scatter",
"src_encoding": "UTF-8",
"text": "import os\nimport logging\nimport numpy as np\nfrom scipy.optimize import bisect\n\nimport torch\nfrom torch import nn,optim\nimport torch.nn.functional as F\nimport torch.utils.data as data\nfrom torch.distributions import Normal, Chi2, StudentT\n\nfrom models.network import *\nfrom utils.sampler import HuberSampler\nfrom utils.metrices import AveMeter, Timer\nfrom utils.utils import kendall\nfrom tensorboardX import SummaryWriter\n\nlogger = logging.getLogger('InfoLog')\ndevice = torch.device('cuda:0' if torch.cuda.is_available else 'cpu')\n\nclass fgan(object):\n def __init__(self, config):\n self.config = config\n self.timer = Timer()\n self.writer = SummaryWriter(log_dir=self.config.rcd_dir)\n self._dist_init()\n self._network_init()\n self._optim_init()\n\n def _dist_init(self):\n self.real = self.config.real\n self.cont = self.config.cont\n if self.config.gnrt is not None:\n self.gnrt = self.config.gnrt\n if self.gnrt == 'Student':\n self.g_df = self.config.g_df\n self.chi2 = Chi2(df=self.g_df)\n self.dim = self.config.dim\n self.eps = self.config.eps\n\n self.HuberX = HuberSampler(**self.config.__dict__)\n self.HuberDataset = data.TensorDataset(self.HuberX)\n self.HuberLoader = data.DataLoader(self.HuberDataset,\n batch_size=self.config.batch_size,\n shuffle=False,\n num_workers=self.config.worker)\n logger.info('----------------------------------------------------')\n logger.info('Initialize Dataset under Huber\\'s Contamination Mode')\n\n def _network_init(self):\n self.use_weight = self.config.use_weight\n self.use_bias = self.config.use_bias\n self.use_el = self.config.use_el\n self.use_prob = self.config.use_prob\n\n if self.use_el:\n self.netGXi = GeneratorXi(activation=self.config.gxi_act,\n hidden_units=self.config.gxi_hidden_units)\n self.netGXi.to(device)\n self.netG = Generator(dim=self.dim,\n use_weight=self.use_weight,\n use_bias=self.use_bias,\n use_el=self.use_el)\n self.netG.to(device)\n self.netD = Discriminator(dim=self.dim,\n hidden_units=self.config.d_hidden_units,\n activation_1=self.config.d_act_1,\n activation='LeakyReLU',\n activation_n=self.config.d_act_n,\n use_prob=self.use_prob)\n self.netD.to(device)\n logger.info('Initialize Network')\n\n # initialization\n self._init_G()\n self._init_D(std=self.config.d_init_std)\n\n def _train_one_epoch(self, ep):\n self.netG.train()\n if self.use_el:\n self.netGXi.train()\n self.netD.train()\n if self.config.d_decay < 1.0:\n self.d_scheduler.step()\n if self.config.g_decay < 1.0:\n self.g_scheduler.step()\n\n lossD = AveMeter()\n lossG = AveMeter()\n d_iter = 1\n\n for ind, (xb,) in enumerate(self.HuberLoader):\n\n # update Discriminator\n r_x = xb.to(device)\n _, r_sc = self.netD(r_x)\n if (self.floss == 'js') or (self.floss == 'ls'):\n r_lossD = self.criterion(r_sc, torch.ones(len(xb)).to(device))\n elif self.floss == 'beta':\n r_coef = - ((r_sc+self.config.delta)**(self.alpha0-1)) * ((1-r_sc)**self.beta0)\n r_sc.backward(r_coef/len(xb))\n\n zb = torch.randn(len(xb), self.dim).to(device)\n if not self.use_el:\n if self.gnrt == 'Student':\n zb.data.div_(\n torch.sqrt(self.chi2.sample((len(xb),1)).to(device)/self.g_df) + self.config.delta\n )\n f_x = self.netG(zb).detach()\n else:\n zb.div_(zb.norm(2, dim=1).view(-1,1) + self.config.delta)\n if self.config.use_ig:\n ub1 = torch.randn(len(xb), self.netGXi.input_dim//2).to(device)\n ub2 = torch.randn(len(xb), self.netGXi.input_dim - self.netGXi.input_dim//2).to(device)\n ub2.data.div_(torch.abs(ub2.data) + self.config.delta)\n ub = torch.cat([ub1, ub2], dim=1)\n else:\n ub = torch.randn(len(xb), self.netGXi.input_dim).to(device)\n xib = self.netGXi(ub)\n f_x = self.netG(zb, xib).detach()\n _, f_sc = self.netD(f_x)\n if (self.floss == 'js') or (self.floss == 'ls'):\n f_lossD = self.criterion(f_sc, torch.zeros(len(xb)).to(device))\n elif self.floss == 'beta':\n f_coef = (f_sc ** self.alpha0) * ((1-f_sc+self.config.delta) ** (self.beta0-1))\n f_sc.backward(f_coef/len(xb))\n lossD.update(-1., len(xb))\n loss = r_lossD + f_lossD\n lossD.update(loss.cpu().item(), len(xb))\n\n self.netD.zero_grad()\n loss.backward()\n self.optD.step()\n if d_iter < self.d_steps:\n d_iter += 1\n continue\n else:\n d_iter = 1\n\n # update Generator\n for _ in range(self.g_steps):\n zb = torch.randn(len(xb), self.dim).to(device)\n if not self.use_el:\n if self.gnrt == 'Student':\n zb.data.div_(\n torch.sqrt(self.chi2.sample((len(xb), 1)).to(device) / self.g_df) + self.config.delta\n )\n f_x = self.netG(zb)\n else:\n zb.div_(zb.norm(2, dim=1).view(-1, 1) + self.config.delta)\n if self.config.use_ig:\n ub1 = torch.randn(len(xb), self.netGXi.input_dim // 2).to(device)\n ub2 = torch.randn(len(xb), self.netGXi.input_dim - self.netGXi.input_dim // 2).to(device)\n ub2.data.div_(torch.abs(ub2.data) + self.config.delta)\n ub = torch.cat([ub1, ub2], dim=1)\n else:\n ub = torch.randn(len(xb), self.netGXi.input_dim).to(device)\n xib = self.netGXi(ub)\n f_x = self.netG(zb, xib)\n _, f_sc = self.netD(f_x)\n if (self.floss == 'js') or (self.floss == 'ls'):\n f_lossG = - self.criterion(f_sc, torch.zeros(len(xb)).to(device))\n elif self.floss == 'beta':\n f_coef = - (f_sc ** self.alpha0) * ((1 - f_sc + self.config.delta) ** (self.beta0 - 1))\n f_sc.backward(f_coef / len(xb))\n lossG.update(-1., len(xb))\n\n self.netG.zero_grad()\n if self.use_el:\n self.netGXi.zero_grad()\n f_lossG.backward()\n self.optG.step()\n lossG.update(f_lossG.cpu().item(), len(xb))\n # logger.info(f'Epoch: [{ep}/{self.epochs} |'\n # f'Time: {self.timer.timeSince()} |'\n # f'LossD: {lossD.avg:.4f} |'\n # f'LossG: {lossG.avg:.4f} |')\n self.writer.add_scalar('lossD', lossD.avg, ep)\n self.writer.add_scalar('lossG', lossG.avg, ep)\n\n def train(self):\n self.epochs = self.config.epochs\n self.floss = self.config.floss\n if self.floss == 'js':\n self.criterion = nn.BCEWithLogitsLoss()\n elif self.floss == 'ls':\n self.criterion = nn.MSELoss()\n elif self.floss == 'beta':\n self.alpha0 = self.config.alpha0\n self.beta0 = self.config.beta0\n\n if self.use_weight:\n cov_est_record = []\n if self.use_bias:\n loc_est_record = []\n\n for ep in range(1, self.config.epochs+1):\n\n self._train_one_epoch(ep)\n\n if ep % self.config.val_period == 0:\n logger.info(f'Epoch: [{ep}/{self.config.epochs}]')\n logger.info(f'Validation Starts: ')\n if self.use_weight:\n cov_error = self._cov_error()\n logger.info(f'Scatter Matrix Estimation Error: %.4f' % cov_error)\n self.writer.add_scalar('ScatterError', cov_error, ep)\n if self.use_bias:\n loc_error = self._loc_error()\n logger.info(f'Location Estimation Error: %.4f' % loc_error)\n self.writer.add_scalar('LocationError', loc_error, ep)\n\n if ep > (self.config.epochs - self.config.avg_epochs):\n if self.use_weight:\n if self.use_el:\n fact = self._reweight() + self.config.delta\n cov_est_record.append(1/fact * self.netG.weight.data.clone().cpu())\n else:\n cov_est_record.append(self.netG.weight.data.clone().cpu())\n if self.use_bias:\n loc_est_record.append(self.netG.bias.data.clone().cpu())\n\n if self.use_weight:\n avg_cov_est = sum(cov_est_record)/len(cov_est_record)\n avg_cov_err = self._cov_error(weight = avg_cov_est)\n last_cov_err = self._cov_error()\n logger.info(f'----------------------Final Result------------------------------'\n f'Average/Final Scatter Estimation Error: {avg_cov_err:.4f} {last_cov_err:.4f}')\n if self.use_bias:\n avg_loc_est = sum(loc_est_record)/len(loc_est_record)\n avg_loc_err = self._loc_error(loc=avg_loc_est)\n last_loc_err = self._loc_error()\n logger.info(f'----------------------Final Result------------------------------'\n f'Average/Final Location Estimation Error: {avg_loc_err:.4f} {last_loc_err:.4f}')\n logger.info(f'End within {self.timer.timeSince()}')\n\n self.writer.close()\n\n def _init_G(self):\n if self.use_weight:\n # scaled Kendall's \\tau estimator\n if self.config.g_init == 'kendall':\n cov_init = kendall(self.HuberX, self.config)\n if self.config.g_init == 'diag':\n medX2 = np.median(self.HuberX.numpy()**2, axis=0)\n cov_init = np.diag(medX2)\n # cov = USU^T, W = S^(1/2)U^T\n u, s, vt = np.linalg.svd(cov_init)\n weight_init = np.matmul(np.diag(s)**(1/2), vt)\n self.netG.weight.data.copy_(torch.from_numpy(weight_init).float().to(device))\n init_cov_error = self._cov_error()\n logger.info('Initialization Scatter Matrix Error: %.4f' % init_cov_error)\n self.writer.add_scalar('ScatterError', init_cov_error, 0)\n if self.use_bias:\n Xmed = torch.median(self.HuberX, dim=0)[0]\n self.netG.bias.data.copy_(Xmed.to(device))\n init_loc_error = self._loc_error()\n logger.info('Initialization Location Error: %.4f' % init_loc_error)\n self.writer.add_scalar('LocationError', init_loc_error, 0)\n if self.use_el:\n self.netGXi.apply(weights_init_xavier)\n\n def _init_D(self, std):\n self.netD.apply(weights_init_xavier)\n if std is not None:\n self.netD.feature.lyr1.weight.data.normal_(0, std)\n\n def _cov_error(self, weight=None):\n with torch.no_grad():\n if weight is None:\n cov_est = torch.mm(self.netG.weight.transpose(1,0), self.netG.weight)\n if self.use_el:\n fact = self._reweight() + self.config.delta\n cov_est.data.div_(fact**2)\n else:\n cov_est = torch.mm(weight.transpose(1, 0), weight)\n cov_err = np.linalg.norm(cov_est.cpu().numpy() - self.config.r_cov, ord=2)\n return cov_err\n\n def _loc_error(self, loc=None):\n if loc is None:\n loc_err = (self.netG.bias.cpu() - self.t_loc).norm(2).item()\n else:\n loc_err = (loc.cpu() - self.t_loc).norm(2).item()\n return loc_err\n\n def _reweight(self, N=100000):\n # Expect value: \\mathbb{E}_{x~X}Ramp(|x|)\n if not hasattr(self, 'epv'):\n self.Hfunc = self.config.Hfunc\n # self.Hfunc = 'ramp'\n if self.real == 'Student':\n tdist = StudentT(df=self.config.r_df)\n x = tdist.sample((5000000,))\n elif self.real == 'Gaussian':\n ndist = Normal(0, 1)\n x = ndist.sample((5000000,))\n self.epv = self._HFunc(x, mode=self.Hfunc).mean().item()\n\n def sov_func(a, bs=1000):\n # find a suitable factor a to match expected value.\n r = AveMeter()\n for _ in range(N//bs):\n if self.config.use_ig:\n ub1 = torch.randn(bs, self.netGXi.input_dim//2).to(device)\n ub2 = torch.randn(bs, self.netGXi.input_dim - self.netGXi.input_dim//2).to(device)\n ub2.data.div_(torch.abs(ub2.data) + self.config.delta)\n ub = torch.cat([ub1, ub2], dim=1)\n else:\n ub = torch.randn(bs, self.netGXi.input_dim).to(device)\n with torch.no_grad():\n xib = self.netGXi(ub)\n zb = torch.randn(bs, self.dim).to(device)\n vu = (zb[:,0].div_(zb.norm(2, dim=1)) + self.config.delta).to(device)\n r.update(self._HFunc(a * xib * vu, mode=self.Hfunc).mean().item(), bs)\n return r.avg - self.epv\n # if sov_func(1) > 0: down,up= 0,3\n # elif sov_func(3) > 0: down,up = 0,5\n # elif sov_func(10) > 0: down,up = 1,12\n # elif sov_func(25) > 0: down,up = 8,27\n # elif sov_func(75) > 0: down,up = 23,77\n if sov_func(250) > 0:\n down, up = 0, 3000\n else:\n logger.info('Factor is larger than 2500!')\n return 250\n factor = bisect(sov_func, down, up)\n print(factor)\n return factor\n\n def _HFunc(self, x, mode):\n if mode == 'abs':\n return torch.abs(x)\n elif mode == 'ramp':\n return F.hardtanh(torch.abs(x))\n\n def _optim_init(self):\n if self.use_el:\n self.optG = optim.SGD(params=list(self.netG.parameters())+list(self.netGXi.parameters()),\n lr=self.config.g_lr)\n else:\n self.optG = optim.SGD(params=self.netG.parameters(),\n lr=self.config.g_lr)\n self.optD = optim.SGD(params=self.netD.parameters(),\n lr=self.config.d_lr)\n self.g_steps = self.config.g_steps\n self.d_steps = self.config.d_steps\n if self.config.d_decay < 1.0:\n self.d_scheduler = optim.lr_scheduler.StepLR(self.optD,\n step_size=self.config.d_sch,\n gamma=self.config.d_decay)\n if self.config.g_decay < 1.0:\n self.g_scheduler = optim.lr_scheduler.StepLR(self.optG,\n step_size=self.config.g_sch,\n gamma=self.config.g_decay)"
},
{
"alpha_fraction": 0.5519434809684753,
"alphanum_fraction": 0.554063618183136,
"avg_line_length": 38.33333206176758,
"blob_id": "916ac3bdd265b2f1e23498a9c4957e3d9c4943c2",
"content_id": "0e847ed6446ad5e6659dc61ee785ac6cbf18c2d6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1415,
"license_type": "no_license",
"max_line_length": 87,
"num_lines": 36,
"path": "/utils/sampler.py",
"repo_name": "shenlong95/Robust-GAN-Scatter",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport torch\n\n\ndef Sampler(dist, n, loc=None, cov=None, df=None, delta=None, a=None, b=None, p=None):\n\n assert dist in ['Gaussian', 'Student', 'Uniform', 'Delta']\n if dist == 'Gaussian':\n x = np.random.multivariate_normal(np.array(loc), np.array(cov), size=(n,))\n elif dist == 'Student':\n assert df is not None\n z = np.random.multivariate_normal(np.zeros(len(cov)), np.array(cov), size=(n,))\n y = np.random.chisquare(df, n) / df\n x = np.array(loc) + z / np.sqrt(y).reshape(-1, 1)\n elif dist == 'Uniform':\n assert (a is not None) and (b is not None) and (p is not None)\n x = np.random.uniform(a, b, size=(n, p))\n elif dist == 'Delta':\n assert (delta is not None) and (p is not None)\n x = delta * np.ones((n, p))\n\n return torch.from_numpy(x).float()\n\n\ndef HuberSampler(**kwargs):\n\n c_n = int(kwargs['ns'] * kwargs['eps'])\n r_n = kwargs['ns'] - c_n\n realX = Sampler(dist=kwargs['real'], n=r_n, p=kwargs['dim'],\n loc=kwargs['r_loc'], cov=kwargs['r_cov'], df=kwargs['r_df'],\n delta=None, a=None, b=None)\n contX = Sampler(dist=kwargs['cont'], n=c_n, p=kwargs['dim'],\n loc=kwargs['c_loc'], cov=kwargs['c_cov'], df=kwargs['c_df'],\n delta=kwargs['c_delta'], a=kwargs['c_a'], b=kwargs['c_b'])\n\n return torch.cat([realX, contX], dim=0)"
},
{
"alpha_fraction": 0.6281769871711731,
"alphanum_fraction": 0.6439703106880188,
"avg_line_length": 48.03076934814453,
"blob_id": "4f9ed066344efa833b7f9ab76fc9575cd117277a",
"content_id": "ba3e208db204ff6cb715c55ddfa8f81c07fd4487",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9561,
"license_type": "no_license",
"max_line_length": 118,
"num_lines": 195,
"path": "/config.py",
"repo_name": "shenlong95/Robust-GAN-Scatter",
"src_encoding": "UTF-8",
"text": "import os\nimport logging\nimport argparse\nimport numpy as np\n\nparser = argparse.ArgumentParser()\n\nparser.add_argument('--real', default='Gaussian', type=str, choices=['Gaussian', 'Student', 'Cauchy'])\nparser.add_argument('--cont', default='Gaussian', type=str,\n choices=['Gaussian', 'Student', 'Cauchy', 'Uniform', 'Delta'])\nparser.add_argument('--gnrt', default=None, type=str, choices=['Gaussian', 'Student'])\nparser.add_argument('--dim', type=int, default=100)\nparser.add_argument('--eps', type=float, default=0.2)\nparser.add_argument('--ns', type=int, default=50000)\n\nparser.add_argument('--r_loc', default=None, type=float)\nparser.add_argument('--c_loc', default=None, type=float)\nparser.add_argument('--r_cov_type', default=None, type=str, choices=['spherical', 'ar', 'wis', 'sp'])\nparser.add_argument('--c_cov_type', default=None, type=str, choices=['spherical', 'ar', 'wis', 'sp'])\nparser.add_argument('--r_var', default=None, type=float)\nparser.add_argument('--c_var', default=None, type=float)\n# Student t distribution degree of freedom\nparser.add_argument('--r_df', default=None, type=float)\nparser.add_argument('--c_df', default=None, type=float)\nparser.add_argument('--g_df', default=None, type=float)\n# Uniform distribution parameter\nparser.add_argument('--c_a', default=None, type=float)\nparser.add_argument('--c_b', default=None, type=float)\n# Delta distribution parameter\nparser.add_argument('--c_delta', default=None, type=float)\n\n# Use default hyper-parameter\nparser.add_argument('--use_default', type=bool, default=True)\n\n# Network structure\nparser.add_argument('--d_hidden_units', nargs='+', default=None, type=int)\nparser.add_argument('--d_act_1', type=str, default=None, choices=['LeakyReLU', 'LogReLU', 'Sigmoid', 'ReLU'])\nparser.add_argument('--d_act_n', type=str, default=None, choices=['LeakyReLU', 'Sigmoid', 'ReLU'])\nparser.add_argument('--d_init_std', type=float, default=None)\nparser.add_argument('--gxi_hidden_units', default=None, nargs='+', type=int)\nparser.add_argument('--gxi_act', type=str, default=None, choices=['LeakyReLU', 'Sigmoid', 'ReLU'])\nparser.add_argument('--g_init', type=str, default=None, choices=['diag', 'kendall'])\nparser.add_argument('--use_el', '-el', action='store_true')\nparser.add_argument('--use_prob', '-pb', action='store_true')\nparser.add_argument('--use_weight', type=bool, default=True)\nparser.add_argument('--use_bias', type=bool, default=False)\nparser.add_argument('--use_ig', type=bool, default=True)\n\n# Optimizer Arguments\nparser.add_argument('--d_lr', type=float, default=None)\nparser.add_argument('--d_steps', type=int, default=None)\nparser.add_argument('--d_decay', type=float, default=None)\nparser.add_argument('--d_sch', type=int, default=None)\nparser.add_argument('--g_lr', type=float, default=None)\nparser.add_argument('--g_steps', type=int, default=None)\nparser.add_argument('--g_decay', type=float, default=None)\nparser.add_argument('--g_sch', type=int, default=None)\nparser.add_argument('--epochs', type=int, default=None)\nparser.add_argument('--avg_epochs', type=int, default=None)\nparser.add_argument('--batch_size', type=int, default=None)\n\n# Training Settings\nparser.add_argument('--floss', default='js', choices=['js', 'ls', 'beta'], type=str)\nparser.add_argument('--rcd_dir', type=str, default='./results/')\nparser.add_argument('--rcd_name', type=str)\nparser.add_argument('--val_period', default=None, type=int)\nparser.add_argument('--delta', default=1e-5, type=float)\nparser.add_argument('--worker', default=1, type=int)\nparser.add_argument('--Hfunc', default='abs', type=str, choices=['abs', 'ramp'])\nparser.add_argument('--subsample', default=5000, type=int)\n\ndef get_config():\n\n config = parser.parse_args()\n\n # Huber\\'s Contamination Model Settings\n for attr in ['real', 'cont', 'gnrt']:\n if getattr(config, attr) == 'Cauchy':\n setattr(config, attr, 'Student')\n setattr(config, attr[0]+'_df', 1)\n\n if config.r_cov_type is None:\n config.r_cov_type = 'spherical'\n config.r_var = 1.0\n if config.r_loc is None:\n config.r_loc = np.zeros(config.dim)\n else:\n config.r_loc = config.r_loc * np.ones(config.dim)\n\n if config.r_cov_type == 'spherical':\n assert config.r_var is not None\n config.r_cov = config.r_var * np.diag(np.ones(config.dim))\n else:\n assert config.dim == 100\n if config.r_cov_type == 'ar':\n config.r_cov = np.load('./datasets/cov/ar_p100_k1.0_t0.5.npy')\n elif config.r_cov_type == 'wis':\n config.r_cov = np.load('./datasets/cov/wis_p100_df100_sc1.0.npy')\n elif config.r_cov_type == 'sp':\n config.r_cov = np.load('./datasets/cov/sp_p100_s0.5.npy')\n else:\n config.r_cov = None\n\n if config.cont in ['Gaussian', 'Student']:\n assert config.c_loc is not None\n config.c_loc = config.c_loc * np.ones(config.dim)\n if config.c_cov_type == 'spherical':\n assert config.c_var is not None\n config.c_cov = config.c_var * np.diag(np.ones(config.dim))\n else:\n assert config.dim == 100\n if config.c_cov_type == 'ar':\n config.c_cov = np.load('./datasets/cov/ar_p100_k5.0_t0.8.npy')\n elif config.c_cov_type == 'wis':\n config.c_cov = np.load('./datasets/cov/wis_p100_df100_sc5.0.npy')\n elif config.c_cov_type == 'sp':\n config.c_cov = np.load('./datasets/cov/sp_p100_s0.5.npy')\n else:\n config.c_cov = None\n else:\n config.c_cov = None\n\n # Network Structure Settings\n if not config.use_el:\n if config.gnrt == None:\n # unless specified particularly, we use the real distribution for the choice of generator.\n config.gnrt = config.real\n config.g_df = config.r_df\n else:\n if config.gnrt == 'Student':\n assert config.g_df is not None\n\n # Training Settings\n assert config.rcd_name is not None\n config.rcd_dir = os.path.join(config.rcd_dir, config.rcd_name)\n if not os.path.exists(config.rcd_dir):\n os.mkdir(config.rcd_dir)\n if config.val_period is None:\n if config.use_el:\n config.val_period = 25\n else:\n config.val_period = 10\n\n if config.use_default:\n if not config.use_el:\n config.g_lr = 0.1 if config.g_lr is None else config.g_lr\n config.d_lr = 0.025 if config.d_lr is None else config.d_lr\n config.d_decay = 1.0 if config.d_decay is None else config.d_decay\n config.g_decay = 0.2 if config.g_decay is None else config.g_decay\n config.g_sch = 200 if config.g_sch is None else config.g_sch\n config.g_steps = 3 if config.g_steps is None else config.g_steps\n config.d_steps = 12 if config.d_steps is None else config.d_steps\n config.d_init_std = .0025 if config.d_init_std is None else config.d_init_std\n config.g_init = 'kendall' if config.g_init is None else config.g_init\n config.epochs = 450 if config.epochs is None else config.epochs\n config.avg_epochs = 25 if config.avg_epochs is None else config.avg_epochs\n config.batch_size = 500 if config.batch_size is None else config.batch_size\n config.d_act_1 = 'LeakyReLU' if config.d_act_1 is None else config.d_act_1\n config.d_act_n = 'Sigmoid' if config.d_act_n is None else config.d_act_n\n config.d_hidden_units = [200, 25] if config.d_hidden_units is None else config.d_hidden_units\n else:\n config.g_lr = 0.025 if config.g_lr is None else config.g_lr\n config.d_lr = 0.05 if config.d_lr is None else config.d_lr\n config.d_decay = 1.0 if config.d_decay is None else config.d_decay\n config.g_decay = 0.2 if config.g_decay is None else config.g_decay\n config.g_sch = 200 if config.g_sch is None else config.g_sch\n config.g_steps = 1 if config.g_steps is None else config.g_steps\n config.d_steps = 5 if config.d_steps is None else config.d_steps\n config.d_init_std = .025 if config.d_init_std is None else config.d_init_std\n config.g_init = 'diag' if config.g_init is None else config.g_init\n config.epochs = 450 if config.epochs is None else config.epochs\n config.avg_epochs = 25 if config.avg_epochs is None else config.avg_epochs\n config.batch_size = 500 if config.batch_size is None else config.batch_size\n config.d_act_1 = 'LeakyReLU' if config.d_act_1 is None else config.d_act_1\n config.d_act_n = 'Sigmoid' if config.d_act_n is None else config.d_act_n\n config.d_hidden_units = [200, 25] if config.d_hidden_units is None else config.d_hidden_units\n config.gxi_hidden_units = [48, 32, 24, 12] if config.gxi_hidden_units is None else config.gxi_hidden_units\n config.gxi_act = 'LeakyReLU' if config.gxi_act is None else config.gxi_act\n\n # Logger\n logger = logging.getLogger('InfoLog')\n logger.setLevel(level=logging.INFO)\n handler = logging.FileHandler(os.path.join(config.rcd_dir, f'log.txt'))\n handler.setLevel(logging.INFO)\n formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')\n handler.setFormatter(formatter)\n\n console = logging.StreamHandler()\n console.setLevel(logging.INFO)\n console.setFormatter(formatter)\n\n logger.addHandler(handler)\n logger.addHandler(console)\n\n return config\n"
},
{
"alpha_fraction": 0.5287439227104187,
"alphanum_fraction": 0.5404577255249023,
"avg_line_length": 35.27450942993164,
"blob_id": "6ad64ca63f668228c90ee1085ecdd99ed36387af",
"content_id": "49aa3a00a0508e4ad1ab15dff29f88db981a33da",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5549,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 153,
"path": "/models/network.py",
"repo_name": "shenlong95/Robust-GAN-Scatter",
"src_encoding": "UTF-8",
"text": "import torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.nn.init import xavier_normal_ as xavier_normal_\nfrom collections import OrderedDict\n\n\n# Some candidate activation functions\nclass myact_Ramp(nn.Module):\n\n def __init__(self):\n super(myact_Ramp, self).__init__()\n\n def forward(self, x):\n return .5 * (F.hardtanh(input, min_val=-0.5, max_val=0.5) + 1)\n\n\nclass myact_LogReLU(nn.Module):\n def __init__(self):\n super(myact_LogReLU, self).__init__()\n\n def forward(self, x):\n return torch.log(1 + F.relu(x))\n\n\nclass GeneratorXi(nn.Module):\n def __init__(self, activation=None, hidden_units=None, input_dim=None):\n # activation, 'Sigmoid'/'ReLU'/'LeakyReLU'\n super(GeneratorXi, self).__init__()\n self.arg = {'negative_slope': 0.2} if (activation == 'LeakyReLU') else {}\n self.activation = activation\n if input_dim is None:\n self.input_dim = hidden_units[0]\n else:\n self.input_dim = input_dim\n self.hidden_units = hidden_units\n self.layers = len(self.hidden_units)\n self.map = self._make_layers()\n\n def _make_layers(self):\n\n layer_list = []\n for lyr in range(self.layers):\n if lyr == 0:\n layer_list += [('lyr%d' % (lyr + 1), nn.Linear(self.input_dim, self.hidden_units[lyr])),\n ('act%d' % (lyr + 1), getattr(nn, self.activation)(**self.arg))]\n else:\n layer_list += [('lyr%d' % (lyr + 1), nn.Linear(self.hidden_units[lyr - 1], self.hidden_units[lyr])),\n ('act%d' % (lyr + 1), getattr(nn, self.activation)(**self.arg))]\n\n layer_list += [('lyr%d' % (self.layers + 1), nn.Linear(self.hidden_units[-1], 1))]\n\n return nn.Sequential(OrderedDict(layer_list))\n\n def forward(self, z):\n\n xi = self.map(z.view(-1, self.input_dim))\n xi = torch.abs(xi)\n\n return xi\n\n\nclass Generator(nn.Module):\n def __init__(self, dim, use_weight=True, use_bias=True, use_el=False):\n\n super(Generator, self).__init__()\n self.dim = dim\n self.use_weight = use_weight\n self.use_bias = use_bias\n if self.use_weight:\n # Note covariance matrix is W^TW\n self.weight = nn.Parameter(torch.eye(self.dim))\n if self.use_bias:\n self.bias = nn.Parameter(torch.zeros(self.dim))\n self.ues_el = use_el\n\n def forward(self, z, xi=None):\n if self.use_weight:\n x = z.view(-1, self.dim).mm(self.weight)\n else:\n x = z.view(-1, self.dim)\n if self.ues_el:\n x = xi * x\n if self.use_bias:\n x = x + self.bias\n return x\n\n\nclass Discriminator(nn.Module):\n def __init__(self, dim, hidden_units,\n activation_1, activation, activation_n, use_prob=False):\n super(Discriminator, self).__init__()\n self.dim = dim\n self.use_prob = use_prob\n\n assert activation in ['ReLU', 'Sigmoid', 'LeakyReLU']\n assert activation_1 in ['LogReLU', 'Sigmoid', 'ReLU', 'LeakyReLU']\n assert activation_n in ['ReLU', 'Sigmoid', 'LeakyReLU']\n self.arg = {'negative_slope': 0.2} if (activation == 'LeakyReLU') else {}\n self.activation = activation\n self.arg_1 = {'negative_slope': 0.2} if (activation_1 == 'LeakyReLU') else {}\n self.activation_1 = activation_1\n self.arg_n = {'negative_slope': 0.2} if (activation_n == 'LeakyReLU') else {}\n self.activation_n = activation_n\n\n self.layers = len(hidden_units)\n self.hidden_units = hidden_units\n\n self.feature = self._make_layers()\n self.map_last = nn.Linear(self.hidden_units[-1], 1)\n if self.use_prob:\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n x = self.feature(x.view(-1, self.dim))\n d = self.map_last(x).squeeze()\n if self.use_prob:\n d = self.sigmoid(d)\n return x, d\n\n def _make_layers(self):\n\n layer_list = []\n for lyr in range(self.layers):\n if lyr == 0:\n if self.activation_1 in ['Sigmoid', 'ReLU', 'LeakyReLU']:\n layer_list += [('lyr%d' % (lyr + 1), nn.Linear(self.dim, self.hidden_units[lyr])),\n ('act%d' % (lyr + 1), getattr(nn, self.activation_1)(**self.arg_1))]\n elif self.activation_1 in ['LogReLU']:\n layer_list += [('lyr%d' % (lyr + 1), nn.Linear(self.dim, self.hidden_units[lyr])),\n ('act%d' % (lyr + 1), eval('myact_' + self.activation_1)())]\n elif lyr == (self.layers - 1):\n layer_list += [('lyr%d' % (lyr + 1), nn.Linear(self.hidden_units[lyr - 1], self.hidden_units[lyr])),\n ('act%d' % (lyr + 1), getattr(nn, self.activation_n)(**self.arg_n))]\n else:\n layer_list += [('lyr%d' % (lyr + 1), nn.Linear(self.hidden_units[lyr - 1], self.hidden_units[lyr])),\n ('act%d' % (lyr + 1), getattr(nn, self.activation)(**self.arg))]\n\n return nn.Sequential(OrderedDict(layer_list))\n\n\ndef weights_init_xavier(m):\n classname = m.__class__.__name__\n if classname.find('Linear') != -1:\n xavier_normal_(m.weight)\n m.bias.data.fill_(0.0)\n\n\ndef weights_init_normal(m):\n classname = m.__class__.__name__\n if classname.find('Linear') != -1:\n m.weight.data.normal_(0.0, 0.02)\n m.bias.data.fill_(0.0)"
},
{
"alpha_fraction": 0.5128665566444397,
"alphanum_fraction": 0.5284261107444763,
"avg_line_length": 31.134614944458008,
"blob_id": "46fa888f943d3bde48544c24ee2d8888e844f64a",
"content_id": "33b8d319e9700a50a8be751adb6688ec5b9ffa49",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1671,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 52,
"path": "/utils/utils.py",
"repo_name": "shenlong95/Robust-GAN-Scatter",
"src_encoding": "UTF-8",
"text": "import numpy as np\nfrom scipy.stats import kendalltau, t, norm\n\n# def scale_kendall(X, subsample=None):\n# # scaling factor\n# medX = np.median(X, axis=0)\n# X = X - medX\n# s = np.median(X**2, axis=0)**(1/2)\n# # kendall's \\tau correlation with sub-sampling\n# if subsample is not None:\n# assert subsample < len(X)\n# indices = np.random.choice(len(X), size=subsample, replace=False)\n# X = X[indices]\n# n, p = X.shape\n# kenmat = np.zeros((p, p))\n# for i in range(n):\n# for j in range(i):\n# v = X[i] - X[j]\n# kenmat += np.outer(v, v)/np.inner(v, v)\n# kenmat = kenmat * 2 / (n*(n-1))\n# # scaling\n# cov = s.reshape(p, 1) * kenmat * s.reshape(1, p)\n# return cov\n\n\ndef kendall(Y, config, subsample=None):\n # X is torch.tensor N by p\n X = Y.numpy()\n # scaling factor\n medX = np.median(X, axis=0)\n X = X - medX\n # median absolute deviation\n s = np.median(np.abs(X), axis=0)\n # std = k * MAD with k = 1/F^{-1}(3/4), where F is dist of real\n if config.real == 'Gaussian':\n k = 1/norm.ppf(3/4)\n elif config.real == 'Student':\n k = 1/t.ppf(3/4, df=config.r_df)\n s = k * s\n # sub-sampling\n if subsample is not None:\n assert subsample <= len(X)\n indices = np.random.choice(len(X), size=subsample, replace=False)\n X = X[indices]\n _, p = X.shape\n corr = np.zeros((p, p))\n for i in range(p):\n for j in range(i + 1):\n corr[i, j] = np.sin(np.pi / 2 * kendalltau(Y[:, i], Y[:, j])[0])\n corr[j, i] = corr[i, j]\n cov = s.reshape(p, 1) * corr * s.reshape(1, p)\n return cov\n"
}
] | 7 |
dengrongkai/coresetapi | https://github.com/dengrongkai/coresetapi | f90fb1c59a0fd9b859ef7d0f6dc4f0791b8fb507 | 0b4e316386b429c75f049fc0078addc1815585d6 | c6ff928e7d0335f0b75369725b437b01e4c459ca | refs/heads/master | 2022-07-05T04:38:21.059735 | 2020-05-15T03:52:25 | 2020-05-15T03:52:25 | 263,844,822 | 1 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.45562130212783813,
"alphanum_fraction": 0.45562130212783813,
"avg_line_length": 16.77777862548828,
"blob_id": "f3a1470879c6bbda0ca30ca04a26f5a3529991bb",
"content_id": "23fd0c1184d38ddf39ed447fa41185dc49fca8a7",
"detected_licenses": [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 169,
"license_type": "permissive",
"max_line_length": 45,
"num_lines": 9,
"path": "/binding.gyp",
"repo_name": "dengrongkai/coresetapi",
"src_encoding": "UTF-8",
"text": "{\r\n \"targets\": [\r\n {\r\n \"target_name\": \"CoreSetApi\",\r\n \"sources\": [ \"./src/core_setting.mm\" ],\r\n \"libraries\": [\"-framework CoreAudio\"]\r\n }\r\n ]\r\n}\r\n"
},
{
"alpha_fraction": 0.6848816275596619,
"alphanum_fraction": 0.6903460621833801,
"avg_line_length": 36.78571319580078,
"blob_id": "2e8080a30541a27df68c2e390f2b8076a6b153e1",
"content_id": "9ac748e8d0684ffca217e43714da2b3bd171a2f8",
"detected_licenses": [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 549,
"license_type": "permissive",
"max_line_length": 112,
"num_lines": 14,
"path": "/test/test.js",
"repo_name": "dengrongkai/coresetapi",
"src_encoding": "UTF-8",
"text": "\r\nrequire('ffi-napi')\r\nvar addon = require('../build/Release/CoreSetApi.node');\r\n\r\n//exports.CoreSet = function () {\r\n// console.log(\"addon.AudioHardwareSet('BoomAudioDevice') ret=\" + addon.AudioHardwareSet('BoomAudioDevice'));\r\n// return addon.AudioHardwareSet('BoomAudioDevice');\r\n//}\r\n\r\n\r\nconsole.log(\"cur device:\" + addon.AudioHardwareGet());\r\nconsole.log(\"all devices:\" + addon.AudioHardwareGetList());\r\n\r\nconst setDevice = '116';\r\nconsole.log(\"addon.AudioHardwareSet('\" + setDevice + \"') ret=\" + addon.AudioHardwareSet(setDevice));\r\n\r\n\r\n"
},
{
"alpha_fraction": 0.6780487895011902,
"alphanum_fraction": 0.6829268336296082,
"avg_line_length": 15.083333015441895,
"blob_id": "6725a8d17d7e5e84529d01dd436fa3a271157305",
"content_id": "176eca431c7171dbd45d78150ee4dfa1768ee608",
"detected_licenses": [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 205,
"license_type": "permissive",
"max_line_length": 50,
"num_lines": 12,
"path": "/README.md",
"repo_name": "dengrongkai/coresetapi",
"src_encoding": "UTF-8",
"text": "# nodejs-natvie-addon\r\n\r\n##build\r\nnode-gyp configure\r\nnode-gyp build\r\n\r\n##build out dir is \"build/Release/CoreSetApi.node\"\r\n##test\r\ncd test\r\nnode test.js\r\n\r\n#### License [CC0 (Public Domain)](LICENSE.md)\r\n"
},
{
"alpha_fraction": 0.6420233249664307,
"alphanum_fraction": 0.6420233249664307,
"avg_line_length": 28.235294342041016,
"blob_id": "3ea7957abbb2bed8a16fef3d98a0614b03e7fb9d",
"content_id": "0689697b5262ecf74cc8d8ff380681bfd2727210",
"detected_licenses": [
"CC0-1.0",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 514,
"license_type": "permissive",
"max_line_length": 61,
"num_lines": 17,
"path": "/index.js",
"repo_name": "dengrongkai/coresetapi",
"src_encoding": "UTF-8",
"text": "const coreSetApi\r\n = require(\"./build/Release/CoreSetApi.node\");\r\n\r\n/**\r\n * Set mac system audio output device\r\n * Returns the set result\r\n * @param {string} deviceName - The audio output device id.\r\n * @returns {string} \"OK\" or error\r\n * only for Mac OS\r\n */\r\nmodule.exports = function(deviceName) {\r\n if(typeof deviceName !== \"string\" || deviceName === '') {\r\n return undefined;\r\n }\r\n // if success return \"OK\" else return \"error msg\"\r\n return coreSetApi.AudioHardwareSet(deviceName);\r\n};\r\n"
}
] | 4 |
pcon-jsr/Scraper | https://github.com/pcon-jsr/Scraper | 791554dd338aadf0db2d60c53ce15d001e51d8b3 | 7fb2885b1b6d80af39624a9db70e7b4a3468664f | 0c289a82518fd8a5093aaee76a17bac15fe2b43f | refs/heads/master | 2020-03-19T13:19:46.734465 | 2018-05-31T15:56:53 | 2018-05-31T15:56:53 | 136,573,597 | 0 | 0 | null | 2018-06-08T06:02:08 | 2018-06-02T06:30:26 | 2018-05-31T15:57:10 | null | [
{
"alpha_fraction": 0.801857590675354,
"alphanum_fraction": 0.801857590675354,
"avg_line_length": 45.28571319580078,
"blob_id": "7c7960ac9d576f669720b8a67191b0b73a3a40ae",
"content_id": "ea2bb76095d5e0ab42b99631a85a5788f4f4de1a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 323,
"license_type": "no_license",
"max_line_length": 177,
"num_lines": 7,
"path": "/README.md",
"repo_name": "pcon-jsr/Scraper",
"src_encoding": "UTF-8",
"text": "# Scraper\n\nIt scraps RegNo ,Name and Cgpa of undergrad Computer Science students at NIT JAMSHEDPUR.\nIt calculates rank of each student according to CGPA by using \"sort_values()\" method of Pandas Dataframe according to specific column no and finally stores result into csv file.\n\n### Packages\nSelenium,Pandas,Beautiful Soup."
},
{
"alpha_fraction": 0.6290149688720703,
"alphanum_fraction": 0.6541755795478821,
"avg_line_length": 31.771930694580078,
"blob_id": "7bd1e88b9478ce182a2ff8f371ce7775400db036",
"content_id": "6429166e6c9c1fd2df561e6a250510bb3f810242",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1868,
"license_type": "no_license",
"max_line_length": 70,
"num_lines": 57,
"path": "/scrap.py",
"repo_name": "pcon-jsr/Scraper",
"src_encoding": "UTF-8",
"text": "from selenium import webdriver\nfrom selenium.webdriver.common.keys import Keys\nfrom selenium.webdriver.support.ui import Select\nfrom selenium.webdriver.support import expected_conditions as EC\nfrom selenium.common.exceptions import UnexpectedAlertPresentException\nfrom selenium.common.exceptions import NoAlertPresentException\nimport bs4\nimport csv\nimport pandas as pd\nimport numpy as np\n\ndef is_alert_present():\n try: driver.switch_to_alert().accept()\n except NoAlertPresentException, e: return False\n return True\n\ndriver = webdriver.Firefox()\ndriver.get('http://14.139.205.172/web_new/Default.aspx')\n\nwith open('result.csv', 'w') as f:\n f.write(\"RegId\" + \",\" + \"Name\" + \",\" + \"CGPA\" + \"\\n\")\n\nfor i in range(1,93):\n roll = str(i)\n if i<10:\n regno = '2015UGCS00' + roll\n else: \n regno = '2015UGCS0' + roll\n \n driver.find_element_by_name('txtRegno').clear()\n driver.find_element_by_name('txtRegno').send_keys(regno)\n driver.find_element_by_name('btnimgShow').click()\n\n if is_alert_present() == True:\n \tdriver.close()\n \tdriver = webdriver.Firefox()\n \tdriver.get('http://14.139.205.172/web_new/Default.aspx')\n else:\n sem = Select(driver.find_element_by_name('ddlSemester'))\n sem.select_by_value('6')\n showresult = driver.find_element_by_name('btnimgShowResult')\n showresult.click()\n res = driver.page_source\n soup = bs4.BeautifulSoup(res,'lxml')\n name = soup.select('#lblSName')\n name = str(name[0].text)\n cg = soup.select('#lblCPI')\n cg = float(cg[0].text)\n cg=str(cg)\n\n with open('result.csv', 'a') as f:\n f.write(regno+\",\"+name+\",\"+cg+\"\\n\")\n\ndf=pd.read_csv('result.csv')\ndf=df.sort_values('CGPA',ascending=[False])\ndf.insert(0, 'Rank', range(1,1+len(df)))\ndf.to_csv('output.csv', encoding='utf-8', index=False)\n"
}
] | 2 |
srijanshah09/todo-list | https://github.com/srijanshah09/todo-list | 9f2900395071bd6bb9f49397820f9679b7266d6c | 4e9d5671cf4dcb5c90876e7c83fb71e51029f107 | f696082ccf74aa0a82d4cc8a213a3e417303d712 | refs/heads/master | 2020-03-30T06:56:35.356951 | 2018-10-02T05:39:34 | 2018-10-02T05:39:34 | 150,901,525 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6641541123390198,
"alphanum_fraction": 0.6683416962623596,
"avg_line_length": 29.58974266052246,
"blob_id": "96311d1aa48a5585511b7ca92042896f6759c00f",
"content_id": "814fe6186a4f84bd5a04870232b00c6783e68096",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1194,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 39,
"path": "/todo/forms.py",
"repo_name": "srijanshah09/todo-list",
"src_encoding": "UTF-8",
"text": "from django import forms\n\nfrom django.contrib.auth.models import User\nfrom .models import Task\n\nclass LoginForm(forms.ModelForm):\n\tclass Meta:\n\t\tmodel = User\n\t\tfields = ['username','password']\n\t\twidgets = {\n\t\t\t'username': forms.TextInput(\n\t\t\t\tattrs={'class':'form-control', id:'username', 'aria-describedby':'emailHelp', 'placeholder':'Username'}\n\t\t\t\t),\n\t\t\t'password': forms.PasswordInput(\n\t\t\t\tattrs={'class':'form-control', id:'password', 'aria-describedby':'emailHelp', 'placeholder':'Password'}\n\t\t\t\t)\n\n\t\t}\n\nclass RegistrationForm(forms.ModelForm):\n\tpassword1 = forms.CharField(widget=forms.PasswordInput(\n\t\t\t\tattrs={\n\t\t\t\t'class':'form-control', \n\t\t\t\tid:'password1', \n\t\t\t\t'aria-describedby':'emailHelp', \n\t\t\t\t'placeholder':'Re-enter Password'}\n\t\t\t\t), required=True, max_length=128)\n\n\tclass Meta():\n\t\tmodel = User\n\t\tfields = ['username','password','password1']\n\t\twidgets = {\n\t\t\t'username': forms.TextInput(\n\t\t\t\tattrs={'class':'form-control', id:'username', 'aria-describedby':'emailHelp', 'placeholder':'Enter Username'}\n\t\t\t\t),\n\t\t\t'password': forms.PasswordInput(\n\t\t\t\tattrs={'class':'form-control', id:'password', 'aria-describedby':'emailHelp', 'placeholder':'Enter Password'}\n\t\t\t\t),\n\t\t\t}\n\n"
},
{
"alpha_fraction": 0.7064777612686157,
"alphanum_fraction": 0.7064777612686157,
"avg_line_length": 32,
"blob_id": "abcadf1bacdd4ec36aef9145f79adba5b9d2d0fa",
"content_id": "8624d24d607b3086e4ec897d6c9041bcf27a3dd2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 494,
"license_type": "no_license",
"max_line_length": 72,
"num_lines": 15,
"path": "/todo/urls.py",
"repo_name": "srijanshah09/todo-list",
"src_encoding": "UTF-8",
"text": "from django.urls import path\n\nfrom .import views\n\n\nurlpatterns = [\n\tpath('', views.home, name='home'),\n\tpath('home/', views.home, name='home'),\n\tpath('register/', views.register, name='register'),\n\tpath('account/', views.index, name='index'),\n\tpath('addTask/',views.addTask, name='addTask'),\n\tpath('deleteCompleted/',views.deleteCompleted, name='deleteCompleted'),\n\tpath('deleteAll/',views.deleteAll, name='deleteAll'),\n\tpath('updateStatus/<int:id>/',views.updateStatus,name='updateStatus'),\t\n]"
},
{
"alpha_fraction": 0.6939350962638855,
"alphanum_fraction": 0.7038081884384155,
"avg_line_length": 25.296297073364258,
"blob_id": "e1a354d1c3d5d1d21f5829f52fb7fd90b36a0e85",
"content_id": "21ba70481f27c76ace6f455ea3264ccd19c3a871",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 709,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 27,
"path": "/todo/models.py",
"repo_name": "srijanshah09/todo-list",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom django.contrib.auth.models import User\n\nimport datetime\n# Create your models here.\nTYPE_CHOICES = (\n\t('PERSONAL','PERSONAL'),\n ('WORK', 'WORK')\n\t)\n\nPRIORITY_CHOICES = (\n ('HIGH','HIGH'),\n ('MEDIUM', 'MEDIUM'),\n ('LOW','LOW')\n)\n\nclass Task(models.Model):\n\t\n\tuser = models.ForeignKey(User, on_delete=models.CASCADE)\n\ttask_type = models.CharField(max_length=10, choices=TYPE_CHOICES, default='PERSONAL')\n\ttask_date = models.DateField()\n\ttask_text = models.CharField(max_length=100)\n\ttask_priority = models.CharField(max_length=10, choices=PRIORITY_CHOICES, default='LOW')\n\ttask_status = models.BooleanField(default=False)\n\n\tdef __str__(self):\n\t\treturn self.task_text"
},
{
"alpha_fraction": 0.5295031070709229,
"alphanum_fraction": 0.5807453393936157,
"avg_line_length": 25.83333396911621,
"blob_id": "b66e82b897e34e1e7a6c75e981f84e86d77d78f4",
"content_id": "746cd881ccc3438b7eaee9e58e3b9edbdfdd0a94",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 644,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 24,
"path": "/todo/migrations/0004_auto_20181002_0309.py",
"repo_name": "srijanshah09/todo-list",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.1.1 on 2018-10-01 21:39\n\nimport datetime\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('todo', '0003_auto_20181002_0307'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='task',\n name='task_date',\n field=models.DateField(default=datetime.datetime.now),\n ),\n migrations.AlterField(\n model_name='task',\n name='task_type',\n field=models.CharField(choices=[('PERSONAL', 'PERSONAL'), ('WORK', 'WORK')], default='PERSONAL', max_length=10),\n ),\n ]\n"
},
{
"alpha_fraction": 0.5091819763183594,
"alphanum_fraction": 0.544240415096283,
"avg_line_length": 25.04347801208496,
"blob_id": "e82c046386a768b642544c6ba426925d80c44828",
"content_id": "a4bc631039e616cf62187d15e3f988e643f35824",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 599,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 23,
"path": "/todo/migrations/0002_auto_20181002_0303.py",
"repo_name": "srijanshah09/todo-list",
"src_encoding": "UTF-8",
"text": "# Generated by Django 2.1.1 on 2018-10-01 21:33\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('todo', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='task',\n name='task_date',\n field=models.DateField(),\n ),\n migrations.AlterField(\n model_name='task',\n name='task_priority',\n field=models.CharField(choices=[('high', 'HIGH'), ('medium', 'MEDIUM'), ('low', 'LOW')], default='LOW', max_length=10),\n ),\n ]\n"
},
{
"alpha_fraction": 0.7152542471885681,
"alphanum_fraction": 0.7161017060279846,
"avg_line_length": 29.791303634643555,
"blob_id": "8fe57b33cec4dc90d75277a56c8dc913e406caec",
"content_id": "133ec423dd1bd059c3dcb6daa5eaf82b9dce19cf",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3540,
"license_type": "no_license",
"max_line_length": 153,
"num_lines": 115,
"path": "/todo/views.py",
"repo_name": "srijanshah09/todo-list",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render, redirect\nfrom django.contrib.auth import authenticate, login\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.decorators import login_required\n\nfrom .forms import *\nfrom .models import Task\n\nimport datetime\n\n# Create your views here.\ndef home(request):\n\tif request.POST:\n\t\tform = LoginForm(request.POST)\n\t\tusername = request.POST['username']\n\t\tpassword = request.POST['password']\n\t\tuser = authenticate(request, username=username, password=password)\n\t\tif user is not None:\n\t\t\tlogin(request, user)\n\t\t\treturn redirect('index')\n\t\telse:\n\t\t\tusername_auth = User.objects.filter(username__exact=username)\n\t\t\tif not username_auth:\n\t\t\t\terror = 'Invalid Username'\t\n\t\t\telse:\n\t\t\t\terror = 'Incorrect Password'\t\n\t\t\tform = LoginForm()\n\t\t\tcontext = {'form' : form, 'error': error}\n\t\t\treturn render(request, 'todo/home.html', context)\n\t\t\n\n\telse:\t\t\n\t\tform = LoginForm()\n\t\tcontext = {'form' : form}\n\t\treturn render(request, 'todo/home.html', context)\n\n\ndef register(request):\n\tif request.POST:\n\t\tform = RegistrationForm(request.POST)\n\t\tusername = request.POST['username']\n\t\tpassword = request.POST['password']\n\t\tpassword1 = request.POST['password1']\n\t\tif User.objects.filter(username__exact=username):\n\t\t\terror = 'Username unavailable. Please try another.'\n\t\telif password != password1:\n\t\t\terror = 'Passwords do not match. Please try again'\n\t\telse:\n\t\t\tUser.objects.create_user(username=username,password=password)\n\t\t\treturn redirect('home')\t\n\t\t\n\t\tform = RegistrationForm()\n\t\tcontext = {'form':form, 'error':error}\n\t\treturn render(request, 'todo/register.html', context)\n\t\n\telse:\n\t\tform = RegistrationForm()\n\t\tcontext = {'form' : form }\n\t\treturn render(request, 'todo/register.html', context)\n\t\t\n\n@login_required(login_url=\"/\")\ndef index(request):\n\tuser = request.user\n\tif request.POST.get('search_date') is None or request.POST.get('search_date') == '':\n\t\tdate = datetime.datetime.now().date()\n\telse:\n\t\tdate = request.POST.get('search_date')\n\t\tdate = datetime.datetime.strptime(date, \"%Y-%m-%d\").date()\n\n\ttasks= Task.objects.filter(user_id__exact=user,task_date__exact=date)\n\tcontext = {'tasks':tasks, 'date':date}\n\treturn render(request, 'todo/index.html',context)\n\n\n@login_required(login_url='/')\ndef addTask(request):\n\tuser = request.user\n\ttask_type = request.POST.get('task_type')\n\ttask_date = request.POST.get('task_date')\n\ttask_text = request.POST.get('task_text')\n\ttask_priority = request.POST.get('task_priority')\n\ttask = Task(user_id=user.id,task_type=task_type,task_date=task_date,task_text=task_text,task_priority=task_priority)\n\ttask.save()\t\n\treturn redirect('index')\n\n\n@login_required(login_url='/')\ndef deleteCompleted(request):\n\tselected_date = request.POST.get('selected_date')\n\ttask_type = request.POST.get('task_type')\n\tprint(selected_date)\n\t#tasks = Task.objects.filter(user_id=request.user.id).filter(task_date__exact=selected_date).filter(task_type__exact=task_type).filter(task_status=True)\n\t#tasks.delete()\n\treturn redirect('index')\n\n\n@login_required(login_url='/')\ndef deleteAll(request):\n\tselected_date = request.POST.get('selected_date')\n\ttask_type = request.POST.get('task_type')\n\ttasks = Task.objects.filter(user_id=request.user.id).filter(task_date__exact=selected_date).filter(task_type__exact=task_type)\t\n\ttasks.delete()\n\treturn redirect('index')\t\n\n\n@login_required(login_url='/')\ndef updateStatus(request,id):\n\ttask= Task.objects.get(id=id)\n\tif task.task_status == True:\n\t\ttask.task_status = False\n\telse:\n\t\ttask.task_status = True\n\ttask.save()\t\n\treturn redirect('index')"
},
{
"alpha_fraction": 0.542894721031189,
"alphanum_fraction": 0.5496052503585815,
"avg_line_length": 37.38888931274414,
"blob_id": "ca7087f7066ea2c75185e16def237d5335a9f56f",
"content_id": "59d97718751688b88413c1363dc5a7885e75422d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "HTML",
"length_bytes": 7600,
"license_type": "no_license",
"max_line_length": 129,
"num_lines": 198,
"path": "/todo/templates/todo/index.html",
"repo_name": "srijanshah09/todo-list",
"src_encoding": "UTF-8",
"text": "{% load static %}\n<!DOCTYPE html>\n<html lang=\"en\">\n<head>\n\t<meta charset=\"UTF-8\">\n\t<meta http-equiv=\"X-UA-Compatible\" content=\"IE=edge\">\n\t<meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n\t<title>PROFILE</title>\n\n\t<!-- Bootstrap CDN -->\n\t<link rel=\"stylesheet\" type=\"text/css\" href=\"{% static 'todo/bs/css/flatly.min.css'%}\">\n\t\n\n\t<!-- FontAwesome CDN -->\n\t<link rel=\"stylesheet\" href=\"https://use.fontawesome.com/releases/v5.3.1/css/all.css\" integrity=\"sha384-mzrmE5qonljUremFsqc01SB46JvROS7bZs3IO2EmfFsd15uHvIt+Y8vEf7N7fWAU\" crossorigin=\"anonymous\">\n\n\t<!-- Oswald font CDN-->\t\n\t<link href=\"https://fonts.googleapis.com/css?family=Oswald\" rel=\"stylesheet\">\n\t\n\t<!-- style css -->\n\t<link rel=\"stylesheet\" type=\"text/css\" href=\"{% static 'todo/style_1.css' %}\">\n</head>\n<body>\n\t<nav class=\"navbar navbar-light bg-light\">\n\t\t<a class=\"navbar-brand\" href=\"#\">TO-DO</a>\n\t\t<a class=\"\" href=\"{% url 'logout' %}\">LOGOUT</a>\n\t</nav>\n\t\n\t<div class=\"container-fluid\" id=\"wrapper\">\n\t\t<div class=\"row justify-content-center\">\n\t\t\t<div id=\"content\" class=\"px-5\">\n\t\t\t\t<div class=\"row justify-content-center bg-info\">\n\t\t\t\t\t<h1 class=\"py-2\">TO-DO APP</h1>\n\t\t\t\t</div>\n\t\t\t\t\n\t\t\t\t<h4 class=\"pt-3\">Add Task :</h4>\n\t\t\t\t\t<form class=\"\" action=\"{% url 'addTask' %}\" method=\"POST\">\n\t\t\t\t\t\t{% csrf_token%}\n\t\t\t\t\t\t<div class=\"form-group\">\n\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t<div class=\"justify-content-center input-group\">\n\t\t\t\t\t\t\t\t<select class=\"form-control field\" name=\"task_type\" id=\"exampleSelect1\" placeholder=\"Task Type\">\n\t\t\t\t\t\t\t\t\t<option selected hidden>TYPE</option>\n\t\t\t\t\t\t\t <option>PERSONAL</option>\n\t\t\t\t\t\t\t <option>WORK</option>\n\t\t\t\t\t\t\t </select>\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t<input type=\"date\" name=\"task_date\" class=\"form-control field\" placeholder=\"Date\">\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t<input type=\"text\" name=\"task_text\" placeholder=\"Enter your task here\" class=\"form-control field\">\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t<select class=\"form-control field\" name=\"task_priority\" id=\"exampleSelect1\" placeholder=\"Task Type\">\n\t\t\t\t\t\t\t <option selected hidden>PRIORITY</option>\n\t\t\t\t\t\t\t <option>HIGH</option>\n\t\t\t\t\t\t\t <option>MEDIUM</option>\n\t\t\t\t\t\t\t <option>LOW</option>\n\t\t\t\t\t\t\t </select>\n\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t<span class=\"input-group-btn\" id=\"add\">\n\t\t\t\t\t\t\t\t\t<button class=\"btn btn-success add\">ADD</button>\n\t\t\t\t\t\t\t\t</span>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\n\t\t\t\t\t</form>\n\t\t\t\t\n\t\t\t\t\n\t\t\t\t<div class=\"row justify-content-center pt-3\">\n\t\t\t\t\t<h2 class=\"bg-danger py-2 px-3\">TASK LIST</h2>\n\t\t\t\t</div>\n\t\t\t\t\n\t\t\t\t<div class=\"row justify-content-center pt-1\">\n\t\t\t\t\t<h4 class=\"align-self-end px-3\">Select date to view task list :</h4>\n\t\t\t\t\t<form class=\"form-inline\" action=\"{% url 'index' %}\" method='POST'>{% csrf_token %}\n\t\t\t\t\t<input type=\"date\" name=\"search_date\" class=\"form-control field\" placeholder=\"Date\">\n\t\t\t\t\t<span class=\"input-group-btn\" id=\"search\">\n\t\t\t\t\t\t<button class=\"btn btn-success add\"><i class=\"fas fa-search\"></i></button>\n\t\t\t\t\t</span>\n\t\t\t\t\t</form>\n\t\t\t\t</div>\n\t\t\t\t\n\t\t\t\t<div class=\"row justify-content-center mt-4\">\n\t\t\t\t\t<h2>{{date}}</h2>\n\t\t\t\t</div>\n\n\t\t\t\t<div class=\"row justify-content-center mt-4\">\n\t\t\t\t\t<div class=\"card bg-primary pt-2 col-md-6 mt-3\">\n\t\t\t\t\t\t<div class=\"card-header justify-content-center\">\n\t\t\t\t\t\t\t<h3 class=\"text-white\">PERSONAL</h3>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<ul class=\"list-group\">\n\t\t\t\t\t\t{% for task in tasks %}\n\t\t\t\t\t\t\t{% if task.task_type == 'PERSONAL' %}\n\t\t\t\t\t\t\t\t{% if task.task_status %}\n\t\t\t\t\t\t\t\t\t<li class=\"list-group-item todo-completed d-flex justify-content-between\">\n\t\t\t\t\t\t\t\t\t\t<span>{{task.task_text}}</span>\n\t\t\t\t\t\t\t\t\t\t<a href=\"{% url 'updateStatus' task.id %}\"><span class=\"align-self-end\"><i class=\"fas fa-undo-alt\"></i></span></a>\n\t\t\t\t\t\t\t\t\t</li>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t{% else %}\n\t\t\t\t\t\t\t\t\t<li class=\"list-group-item d-flex justify-content-between\">\n\t\t\t\t\t\t\t\t\t\t<a href=\"{% url 'updateStatus' task.id %}\">{{ task.task_text }}</a>\n\t\t\t\t\t\t\t\t\t\t{% if task.task_priority == 'HIGH' %}\n\t\t\t\t\t\t\t\t\t\t\t<span class=\"badge badge-danger align-self-end\">{{task.task_priority}}</span>\n\t\t\t\t\t\t\t\t\t\t{% elif task.task_priority == 'MEDIUM'%}\n\t\t\t\t\t\t\t\t\t\t\t<span class=\"badge badge-warning align-self-end\">{{task.task_priority}}</span>\n\t\t\t\t\t\t\t\t\t\t{% else %}\n\t\t\t\t\t\t\t\t\t\t\t<span class=\"badge badge-info align-self-end\">{{task.task_priority}}</span>\n\t\t\t\t\t\t\t\t\t\t{% endif %}\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t</li>\n\t\t\t\t\t\t\t\t{% endif %}\n\t\t\t\t\t\t\t{% endif %}\t\n\t\t\t\t\t\t{% endfor %}\n\n\t\t\t\t\t\t<div class=\"row t10\">\n\t\t\t\t\t\t\t<div class=\"btn-toolbar px-2\">\n\t\t\t\t\t\t\t\t<div class=\" btn btn-group\">\n\t\t\t\t\t\t\t\t\t<form action=\"{% url 'deleteCompleted' %}\" method='POST'>\n\t\t\t\t\t\t\t\t\t\t{% csrf_token %}\n\t\t\t\t\t\t\t\t\t\t<input type=\"date\" name=\"selected_date\" value=\"{{date|date:'Y-m-d'}}\" hidden>\n\t\t\t\t\t\t\t\t\t\t<input type=\"text\" name=\"task_type\" value=\"PERSONAL\" hidden>\n\t\t\t\t\t\t\t\t\t\t<button class=\"btn btn-warning\"><i class=\"fas fa-trash-alt\"></i> DELETE COMPLETED</button>\n\t\t\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\" btn btn-group\">\n\t\t\t\t\t\t\t\t\t<form action=\"{% url 'deleteAll' %}\" method='POST'>\n\t\t\t\t\t\t\t\t\t\t{% csrf_token %}\n\t\t\t\t\t\t\t\t\t\t<input type=\"date\" name=\"selected_date\" value=\"{{date|date:'Y-m-d'}}\" hidden>\n\t\t\t\t\t\t\t\t\t\t<input type=\"text\" name=\"task_type\" value=\"PERSONAL\" hidden>\n\t\t\t\t\t\t\t\t\t\t<button class=\"btn btn-warning\"><i class=\"fas fa-trash-alt\"></i> DELETE ALL</button>\n\t\t\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t\t<div class=\"card bg-secondary p-2 col-md-6 mt-3\">\n\t\t\t\t\t\t<div class=\"card-header justify-content-center\">\n\t\t\t\t\t\t\t<h3>WORK</h3>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t\t<ul class=\"list-group\">\n\t\t\t\t\t\t{% for task in tasks %}\n\t\t\t\t\t\t\t{% if task.task_type == 'WORK' %}\n\t\t\t\t\t\t\t\t{% if task.task_status %}\n\t\t\t\t\t\t\t\t\t<li class=\"list-group-item todo-completed d-flex justify-content-between\">\n\t\t\t\t\t\t\t\t\t\t<span>{{task.task_text}}</span>\n\t\t\t\t\t\t\t\t\t\t<a href=\"{% url 'updateStatus' task.id %}\"><span class=\"align-self-end\"><i class=\"fas fa-undo-alt\"></i></span></a>\n\t\t\t\t\t\t\t\t\t</li>\n\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t{% else %}\n\t\t\t\t\t\t\t\t\t<li class=\"list-group-item d-flex justify-content-between\">\n\t\t\t\t\t\t\t\t\t\t<a href=\"{% url 'updateStatus' task.id %}\">{{ task.task_text }}</a>\n\t\t\t\t\t\t\t\t\t\t{% if task.task_priority == 'HIGH' %}\n\t\t\t\t\t\t\t\t\t\t\t<span class=\"badge badge-danger align-self-end\">{{task.task_priority}}</span>\n\t\t\t\t\t\t\t\t\t\t{% elif task.task_priority == 'MEDIUM'%}\n\t\t\t\t\t\t\t\t\t\t\t<span class=\"badge badge-warning align-self-end\">{{task.task_priority}}</span>\n\t\t\t\t\t\t\t\t\t\t{% else %}\n\t\t\t\t\t\t\t\t\t\t\t<span class=\"badge badge-info align-self-end\">{{task.task_priority}}</span>\n\t\t\t\t\t\t\t\t\t\t{% endif %}\t\t\t\t\t\t\t\t\t\t\n\t\t\t\t\t\t\t\t\t</li>\n\t\t\t\t\t\t\t\t{% endif %}\n\t\t\t\t\t\t\t{% endif %}\t\n\t\t\t\t\t\t{% endfor %}\n\t\t\t\t\t\t</ul>\n\t\t\t\t\t\t<div class=\"row t10\">\n\t\t\t\t\t\t\t<div class=\"btn-toolbar px-2\">\n\t\t\t\t\t\t\t\t<div class=\" btn btn-group\">\n\t\t\t\t\t\t\t\t\t<form action=\"{% url 'deleteCompleted' %}\" method='POST'>\n\t\t\t\t\t\t\t\t\t\t{% csrf_token %}\n\t\t\t\t\t\t\t\t\t\t<input type=\"date\" name=\"selected_date\" value=\"{{date|date:'Y-m-d'}}\" hidden>\n\t\t\t\t\t\t\t\t\t\t<input type=\"text\" name=\"task_type\" value=\"WORK\" hidden>\n\t\t\t\t\t\t\t\t\t\t<button class=\"btn btn-warning\"><i class=\"fas fa-trash-alt\"></i> DELETE COMPLETED</button>\n\t\t\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t\t<div class=\" btn btn-group\">\n\t\t\t\t\t\t\t\t\t<form action=\"{% url 'deleteAll' %}\" method='POST'>\n\t\t\t\t\t\t\t\t\t\t{% csrf_token %}\n\t\t\t\t\t\t\t\t\t\t<input type=\"date\" name=\"selected_date\" value=\"{{date|date:'Y-m-d'}}\" hidden>\n\t\t\t\t\t\t\t\t\t\t<input type=\"text\" name=\"task_type\" value=\"WORK\" hidden>\n\t\t\t\t\t\t\t\t\t\t<button class=\"btn btn-warning\"><i class=\"fas fa-trash-alt\"></i> DELETE ALL</button>\n\t\t\t\t\t\t\t\t\t</form>\n\t\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t\t</div>\n\t\t\t\t\t\t</div>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t\t</div>\n\t\t</div>\n\t\t<footer>\n\t\t\t<div class=\"row pad p-3\">\n\t\t\t\t\t<div class=\"col-lg-12 text-center\">\n\t\t\t\t\t\tCopyright © 2017 <strong>To-Do App</strong>\n\t\t\t\t\t</div>\n\t\t\t\t</div>\n\t\t</footer>\n\t</div>\n\t\t\n</body>\n</html>"
}
] | 7 |
YuriAR/Lab12and13 | https://github.com/YuriAR/Lab12and13 | 7ffb649c422a104871823cbe56b72a546208ae45 | 70494aed4a95a4cfbbd8a47fb93c96d87b5e1692 | e63b2dd93b27f33390f93b74e5c3a1802c59db4b | refs/heads/master | 2021-01-10T14:39:33.949539 | 2015-12-09T15:33:49 | 2015-12-09T15:33:49 | 47,268,875 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6700738072395325,
"alphanum_fraction": 0.6763202548027039,
"avg_line_length": 28.847457885742188,
"blob_id": "0bcb2b8bb636ab4d36c6c3edd70f6f94b3ebbf37",
"content_id": "e5882e3bd23ef585e4b1390c757eb0df6bb90230",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3522,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 118,
"path": "/my_application/server.py",
"repo_name": "YuriAR/Lab12and13",
"src_encoding": "UTF-8",
"text": "import requests\nimport boto\nimport boto.sqs\nimport boto.sqs.queue\nfrom boto.sqs.message import Message\nfrom boto.sqs.connection import SQSConnection\nfrom boto.exception import SQSError\nimport sys\nimport os\nimport json\nfrom subprocess import Popen, PIPE\nfrom flask import Flask, Response, render_template , request, redirect, url_for\nfrom werkzeug import secure_filename\nfrom tempfile import mkdtemp\n\napp = Flask(__name__)\n\ndef get_conn():\n\turl = \"http://ec2-52-30-7-5.eu-west-1.compute.amazonaws.com:81/key\"\n\tdata = requests.get(url).text\n\tkeys = data.split(\":\")\n\tkey_id = keys[0]\t\n\tsecret_access_key = keys[1]\n\treturn boto.sqs.connect_to_region(\"eu-west-1\",aws_access_key_id=key_id,aws_secret_access_key=secret_access_key)\n\[email protected](\"/\", methods=[\"GET\"])\ndef index():\n\treturn Response(response=json.dumps(boto.Version), mimetype=\"application/json\")\n\[email protected](\"/queues\", methods=[\"GET\"])\ndef list_queues():\n\tall = []\n\tconn = get_conn()\n\trs = conn.get_all_queues()\n\tfor q in rs:\n\t\tall.append(q.name)\n\tresp = json.dumps(all)\n\treturn Response(response=resp,mimetype=\"application/json\")\t\n\[email protected](\"/queues\", methods=[\"POST\"])\ndef create_queue():\n\tconn = get_conn()\n\tbody = request.get_json(force=True)\n\tname = body[\"name\"]\n\tqueue = conn.create_queue(name)\n\tif queue is None:\n\t\tresp = json.dumps(\"Error - Queue not created\\n\")\n\telse:\n\t\tresp = json.dumps(\"Queue \" + name + \" created\\n\")\n\treturn Response(response=resp,mimetype=\"application/json\")\n\[email protected](\"/queues/<name>\", methods=[\"DELETE\"])\ndef delete_queue(name):\n\tconn = get_conn()\n\tqueue = conn.get_queue(name)\n\tif queue is None:\n resp = json.dumps(\"Queue not found\\n\")\n\telse:\n\t\tconn.delete_queue(queue)\n\t\tresp = json.dumps(\"Queue \" + name + \" deleted\\n\")\n return Response(response=resp,mimetype=\"application/json\")\n\[email protected](\"/queues/<name>/msgs/count\", methods=[\"GET\"])\ndef number_of_messages(name):\n\tconn = get_conn()\n\tqueue = conn.get_queue(name)\n\tif queue is None:\n resp = json.dumps(\"Queue not found\\n\")\n\telse:\n\t\tresp = json.dumps(\"Number of messages: \" + str(queue.count()))\n\treturn Response(response=resp,mimetype=\"application/json\")\n\[email protected](\"/queues/<name>/msgs\", methods=[\"POST\"])\ndef write_message(name):\n\tconn = get_conn()\n\tm = Message()\n\tbody = request.get_json(force=True)\n\tm.set_body(body[\"content\"])\n\tqueue = conn.get_queue(name)\n\tif queue is None:\n resp = json.dumps(\"Queue not found\\n\")\n\telse:\n\t\tqueue.write(m)\n\t\tresp = json.dumps(\"Message written\\n\")\n return Response(response=resp,mimetype=\"application/json\")\n\[email protected](\"/queues/<name>/msgs\", methods=[\"GET\"])\ndef read_message(name):\n\tconn = get_conn()\n\tqueue = conn.get_queue(name)\n\tif queue is None:\n resp = json.dumps(\"Queue not found\\n\")\n\telse:\n\t\tmessages = queue.get_messages()\n\t\tif queue.count() > 0:\n\t\t\tresp = json.dumps(\"Message: \" + messages[0].get_body())\n\t\telse:\n\t\t\tresp = json.dumps(\"No messages\")\n\treturn Response(response=resp,mimetype=\"application/json\")\n\[email protected](\"/queues/<name>/msgs\", methods=[\"DELETE\"])\ndef consume_message(name):\n\tconn = get_conn()\n\tqueue = conn.get_queue(name)\n\tif queue is None:\n resp = json.dumps(\"Queue not found\\n\")\n\telse:\n\t\tmessages = queue.get_messages()\n\t\tif len(messages) > 0:\n\t\t\tresp = json.dumps(\"Message: \" + messages[0].get_body())\n\t\t\tqueue.delete_message(messages[0])\n\t\telse:\n\t\t\tresp = json.dumps(\"No messages\")\n\treturn Response(response=resp,mimetype=\"application/json\")\n\t\n\nif __name__ == \"__main__\":\n app.run(host=\"0.0.0.0\", debug=True)\n"
}
] | 1 |
RafalSladek/programmer-competency-checklist | https://github.com/RafalSladek/programmer-competency-checklist | e5af8bb0bebb9428affbba5d1daba6dc887c6db1 | 8bd02556bd88960c94939cd70bfb0def9b71e8f2 | 7588cb290787bb9919aa426cf66aeffe15049610 | refs/heads/master | 2020-12-25T16:25:30.085226 | 2016-02-24T13:52:59 | 2016-02-24T13:52:59 | 52,440,854 | 1 | 1 | null | 2016-02-24T12:33:20 | 2016-02-24T12:33:20 | 2016-02-24T13:52:17 | Python | [
{
"alpha_fraction": 0.726457417011261,
"alphanum_fraction": 0.7466367483139038,
"avg_line_length": 30.785715103149414,
"blob_id": "0442047eba231fa76e2c569e1656d8cb78618931",
"content_id": "2fec84ac1b7be0d5684f3b55ad5d4d9b3af62cd8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 446,
"license_type": "no_license",
"max_line_length": 153,
"num_lines": 14,
"path": "/README.md",
"repo_name": "RafalSladek/programmer-competency-checklist",
"src_encoding": "UTF-8",
"text": "Programmer Competency Checklist\n===============================\n\n\nhttp://competency-checklist.appspot.com/\n\n\nInspired by http://www.indiangeek.net/wp-content/uploads/Programmer%20competency%20matrix.htm\n\nThe idea behind the project is to help people track theirs software skills studies.\n\n\n\n[](https://bitdeli.com/free \"Bitdeli Badge\")\n\n"
},
{
"alpha_fraction": 0.6101083159446716,
"alphanum_fraction": 0.6101083159446716,
"avg_line_length": 24.744186401367188,
"blob_id": "7ed2581021be547fbb250302c9b1f1bcf43bc4de",
"content_id": "037a4a9a7d11d7dd193527158d2632a93d7e5099",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 1108,
"license_type": "no_license",
"max_line_length": 47,
"num_lines": 43,
"path": "/js/all.js",
"repo_name": "RafalSladek/programmer-competency-checklist",
"src_encoding": "UTF-8",
"text": "var markAsKnown = function(skill, skillId) {\n localStorage.setItem(skillId, \"check\");\n skill.find(\"input\").prop(\"checked\", true);\n};\n\nvar markAsUnknown = function(skill, skillId) {\n localStorage.setItem(skillId, \"uncheck\");\n skill.find(\"input\").prop(\"checked\", false);\n};\n\nvar updateSkillsFromLocalStorage = function() {\n $(\".skill\").each(function(index, elem) {\n var skillId = $(elem).attr(\"id\");\n var value = localStorage.getItem(skillId);\n if (value === \"check\") {\n markAsKnown($(elem), skillId);\n }\n });\n};\n\nvar bindClicks = function() {\n $(\"input.check\").change(function() {\n var skill = $(this).parent().parent();\n var skillId = skill.attr(\"id\");\n if ($(this).prop(\"checked\")) {\n markAsKnown(skill, skillId);\n } else {\n markAsUnknown(skill, skillId);\n }\n });\n};\n\nvar emptyLocalStorage = function() {\n $(\".skill\").each(function(index, elem) {\n var skillId = $(elem).attr(\"id\");\n localStorage.setItem(skillId, \"uncheck\");\n });\n};\n\nvar useLocalStorage = function() {\n updateSkillsFromLocalStorage();\n bindClicks();\n};\n\n"
},
{
"alpha_fraction": 0.6365382075309753,
"alphanum_fraction": 0.6378411650657654,
"avg_line_length": 63.813331604003906,
"blob_id": "1c623c11d9f1271ed28dfbd923eebdf90cd68450",
"content_id": "f97bc214c1243a7bb790a11fd3ac5013e0e7fa53",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14582,
"license_type": "no_license",
"max_line_length": 374,
"num_lines": 225,
"path": "/skills.py",
"repo_name": "RafalSladek/programmer-competency-checklist",
"src_encoding": "UTF-8",
"text": "import re\nfrom hashlib import md5\n\nbig_areas = (\n (\"Computer Science\", [\n (\"data structures\", [\n \"\"\"Doesn't know the difference between Array and LinkedList\"\"\",\n \"\"\"Able to explain and use Arrays, LinkedLists, Dictionaries etc in practical programming tasks\"\"\",\n \"\"\"Knows space and time tradeoffs of the basic data structures, Arrays vs LinkedLists, Able to explain how hashtables can be implemented and can handle collisions, Priority queues and ways to implement them etc.\"\"\",\n \"\"\"Knowledge of advanced data structures like B-trees, binomial and fibonacci heaps, AVL/Red Black trees, Splay Trees, Skip Lists, tries etc.\"\"\",\n ]),\n (\"algorithms\", [\n \"\"\"Unable to find the average of numbers in an array (It's hard to believe but I've interviewed such candidates) \"\"\",\n \"\"\"Basic sorting, searching and data structure traversal and retrieval algorithms \"\"\",\n \"\"\"Tree, Graph, simple greedy and divide and conquer algorithms, is able to understand the relevance of the levels of this matrix. \"\"\",\n \"\"\"Able to recognize and code dynamic programming solutions, good knowledge of graph algorithms, good knowledge of numerical computation algorithms, able to identify NP problems etc. \"\"\",\n ]),\n (\"systems programming\", [\n \"\"\"Doesn't know what a compiler, linker or interpreter is\"\"\",\n \"\"\"Basic understanding of compilers, linker and interpreters. Understands what assembly code is and how things work at the hardware level. Some knowledge of virtual memory and paging.\"\"\",\n \"\"\"Understands kernel mode vs. user mode, multi-threading, synchronization primitives and how they're implemented, able to read assembly code. Understands how networks work, understanding of network protocols and socket level programming.\"\"\",\n \"\"\"Understands the entire programming stack, hardware (CPU + Memory + Cache + Interrupts + microcode), binary code, assembly, static and dynamic linking, compilation, interpretation, JIT compilation, garbage collection, heap, stack, memory addressing...\"\"\",\n ]),\n ]),\n\n\n (\"Software Engineering\", [\n (\"source code version control\", [\n \"\"\"Folder backups by date\"\"\",\n \"\"\"VSS and beginning CVS/SVN user\"\"\",\n \"\"\"Proficient in using CVS and SVN features. Knows how to branch and merge, use patches setup repository properties etc.\"\"\",\n \"\"\"Knowledge of distributed VCS systems. Has tried out Bzr/Mercurial/Darcs/Git\"\"\",\n ]),\n (\"build automation\", [\n \"\"\"Only knows how to build from IDE\"\"\",\n \"\"\"Knows how to build the system from the command line\"\"\",\n \"\"\"Can setup a script to build the basic system\"\"\",\n \"\"\"Can setup a script to build the system and also documentation, installers, generate release notes and tag the code in source control\"\"\",\n ]),\n (\"automated testing\", [\n \"\"\"Thinks that all testing is the job of the tester\"\"\",\n \"\"\"Has written automated unit tests and comes up with good unit test cases for the code that is being written\"\"\",\n \"\"\"Has written code in TDD manner\"\"\",\n \"\"\"Understands and is able to setup automated functional, load/performance and UI tests\"\"\",\n ])\n ]),\n\n (\"Programming\", [\n (\"problem decomposition\", [\n \"\"\"Only straight line code with copy paste for reuse\"\"\",\n \"\"\"Able to break up problem into multiple functions\"\"\",\n \"\"\"Able to come up with reusable functions/objects that solve the overall problem\"\"\",\n \"\"\"Use of appropriate data structures and algorithms and comes up with generic/object-oriented code that encapsulate aspects of the problem that are subject to change.\"\"\",\n ]),\n (\"systems decomposition\", [\n \"\"\"Not able to think above the level of a single file/class\"\"\",\n \"\"\"Able to break up problem space and design solution as long as it is within the same platform/technology\"\"\",\n \"\"\"Able to design systems that span multiple technologies/platforms.\"\"\",\n \"\"\"Able to visualize and design complex systems with multiple product lines and integrations with external systems. Also should be able to design operations support systems like monitoring, reporting, fail overs etc.\"\"\",\n ]),\n (\"communication\", [\n \"\"\"Cannot express thoughts/ideas to peers. Poor spelling and grammar.\"\"\",\n \"\"\"Peers can understand what is being said. Good spelling and grammar.\"\"\",\n \"\"\"Is able to effectively communicate with peers\"\"\",\n \"\"\"Able to understand and communicate thoughts/design/ideas/specs in a unambiguous manner and adjusts communication as per the context\"\"\",\n ]),\n (\"code organization within a file\", [\n \"\"\"no evidence of organization within a file\"\"\",\n \"\"\"Methods are grouped logically or by accessibility\"\"\",\n \"\"\"Code is grouped into regions and well commented with references to other source files\"\"\",\n \"\"\"File has license header, summary, well commented, consistent white space usage. The file should look beautiful.\"\"\",\n ]),\n (\"code organization across files\", [\n \"\"\"No thought given to organizing code across files\"\"\",\n \"\"\"Related files are grouped into a folder\"\"\",\n \"\"\"Each physical file has a unique purpose, for e.g. one class definition, one feature implementation etc.\"\"\",\n \"\"\"Code organization at a physical level closely matches design and looking at file names and folder distribution provides insights into design\"\"\",\n ]),\n (\"source tree organization\", [\n \"\"\"Everything in one folder\"\"\",\n \"\"\"Basic separation of code into logical folders.\"\"\",\n \"\"\"No circular dependencies, binaries, libs, docs, builds, third-party code all organized into appropriate folders\"\"\",\n \"\"\"Physical layout of source tree matches logical hierarchy and organization. The directory names and organization provide insights into the design of the system.\"\"\",\n ]),\n (\"code readability\", [\n \"\"\"Mono-syllable names\"\"\",\n \"\"\"Good names for files, variables classes, methods etc.\"\"\",\n \"\"\"No long functions, comments explaining unusual code, bug fixes, code assumptions\"\"\",\n \"\"\"Code assumptions are verified using asserts, code flows naturally - no deep nesting of conditionals or methods\"\"\",\n ]),\n (\"defensive coding\", [\n \"\"\"Doesn't understand the concept\"\"\",\n \"\"\"Checks all arguments and asserts critical assumptions in code\"\"\",\n \"\"\"Makes sure to check return values and check for exceptions around code that can fail.\"\"\",\n \"\"\"Has his own library to help with defensive coding, writes unit tests that simulate faults\"\"\",\n ]),\n (\"error handling\", [\n \"\"\"Only codes the happy case\"\"\",\n \"\"\"Basic error handling around code that can throw exceptions/generate errors\"\"\",\n \"\"\"Ensures that error/exceptions leave program in good state, resources, connections and memory is all cleaned up properly\"\"\",\n \"\"\"Codes to detect possible exception before, maintain consistent exception handling strategy in all layers of code, come up with guidelines on exception handling for entire system.\"\"\",\n ]),\n (\"IDE\", [\n \"\"\"Mostly uses IDE for text editing\"\"\",\n \"\"\"Knows their way around the interface, able to effectively use the IDE using menus.\"\"\",\n \"\"\"Knows keyboard shortcuts for most used operations.\"\"\",\n \"\"\"Has written custom macros\"\"\",\n ]),\n (\"API\", [\n \"\"\"Needs to look up the documentation frequently\"\"\",\n \"\"\"Has the most frequently used APIs in memory\"\"\",\n \"\"\"Vast and In-depth knowledge of the API\"\"\",\n \"\"\"Has written libraries that sit on top of the API to simplify frequently used tasks and to fill in gaps in the API\"\"\",\n ]),\n (\"frameworks\", [\n \"\"\"Has not used any framework outside of the core platform\"\"\",\n \"\"\"Has heard about but not used the popular frameworks available for the platform.\"\"\",\n \"\"\"Has used more than one framework in a professional capacity and is well-versed with the idioms of the frameworks.\"\"\",\n \"\"\"Author of framework\"\"\",\n ]),\n (\"requirements\", [\n \"\"\"Takes the given requirements and codes to spec\"\"\",\n \"\"\"Come up with questions regarding missed cases in the spec\"\"\",\n \"\"\"Understand complete picture and come up with entire areas that need to be speced\"\"\",\n \"\"\"Able to suggest better alternatives and flows to given requirements based on experience\"\"\",\n ]),\n (\"scripting\", [\n \"\"\"No knowledge of scripting tools\"\"\",\n \"\"\"Batch files/shell scripts\"\"\",\n \"\"\"Perl/Python/Ruby/VBScript/Powershell\"\"\",\n \"\"\"Has written and published reusable code\"\"\",\n ]),\n (\"database\", [\n \"\"\"Thinks that Excel is a database\"\"\",\n \"\"\"Knows basic database concepts, normalization, ACID, transactions and can write simple selects\"\"\",\n \"\"\"Able to design good and normalized database schemas keeping in mind the queries that'll have to be run, proficient in use of views, stored procedures, triggers and user defined types. Knows difference between clustered and non-clustered indexes. Proficient in use of ORM tools.\"\"\",\n \"\"\"Can do basic database administration, performance optimization, index optimization, write advanced select queries, able to replace cursor usage with relational sql, understands how data is stored internally, understands how indexes are stored internally, understands how databases can be mirrored, replicated etc. Understands how the two phase commit works.\"\"\",\n ]),\n\n ]),\n\n (\"Knowledge\", [\n (\"tool knowledge\", [\n \"\"\"Limited to primary IDE (VS.Net, Eclipse etc.)\"\"\",\n \"\"\"Knows about some alternatives to popular and standard tools.\"\"\",\n \"\"\"Good knowledge of editors, debuggers, IDEs, open source alternatives etc. etc. For e.g. someone who knows most of the tools from Scott Hanselman's power tools list. Has used ORM tools.\"\"\",\n \"\"\"Has actually written tools and scripts, added bonus if they've been published.\"\"\",\n ]),\n (\"languages exposed to\", [\n \"\"\"Imperative or Object Oriented\"\"\",\n \"\"\"Imperative, Object-Oriented and declarative (SQL), added bonus if they understand static vs dynamic typing, weak vs strong typing and static inferred types\"\"\",\n \"\"\"Functional, added bonus if they understand lazy evaluation, currying, continuations\"\"\",\n \"\"\"Concurrent (Erlang, Oz) and Logic (Prolog)\"\"\",\n ]),\n (\"codebase knowledge\", [\n \"\"\"Has never looked at the codebase\"\"\",\n \"\"\"Basic knowledge of the code layout and how to build the system\"\"\",\n \"\"\"Good working knowledge of code base, has implemented several bug fixes and maybe some small features.\"\"\",\n \"\"\"Has implemented multiple big features in the codebase and can easily visualize the changes required for most features or bug fixes.\"\"\",\n ]),\n (\"knowledge of upcoming technologies\", [\n \"\"\"Has not heard of the upcoming technologies\"\"\",\n \"\"\"Has heard of upcoming technologies in the field\"\"\",\n \"\"\"Has downloaded the alpha preview/CTP/beta and read some articles/manuals\"\"\",\n \"\"\"Has played with the previews and has actually built something with it and as a bonus shared that with everyone else\"\"\",\n ]),\n (\"platform internals\", [\n \"\"\"Zero knowledge of platform internals\"\"\",\n \"\"\"Has basic knowledge of how the platform works internally\"\"\",\n \"\"\"Deep knowledge of platform internals and can visualize how the platform takes the program and converts it into executable code.\"\"\",\n \"\"\"Has written tools to enhance or provide information on platform internals. For e.g. disassemblers, decompilers, debuggers etc.\"\"\",\n ]),\n (\"books\", [\n \"\"\"Unleashed series, 21 days series, 24 hour series, dummies series...\"\"\",\n \"\"\"Code Complete, Don't Make me Think, Mastering Regular Expressions\"\"\",\n \"\"\"Design Patterns, Peopleware, Programming Pearls, Algorithm Design Manual, Pragmatic Programmer, Mythical Man month\"\"\",\n \"\"\"Structure and Interpretation of Computer Programs, Concepts Techniques, Models of Computer Programming, Art of Computer Programming, Database systems , by C. J Date, Thinking Forth, Little Schemer\"\"\",\n ]),\n (\"blogs\", [\n \"\"\"Has heard of them but never got the time.\"\"\",\n \"\"\"Reads tech/programming/software engineering blogs and listens to podcasts regularly.\"\"\",\n \"\"\"Maintains a link blog with some collection of useful articles and tools that he/she has collected\"\"\",\n \"\"\"Maintains a blog in which personal insights and thoughts on programming are shared\"\"\",\n ]),\n ]),\n\n (\"Experience\", [\n (\"languages with professional experience\", [\n \"\"\"Imperative or Object Oriented\"\"\",\n \"\"\"Imperative, Object-Oriented and declarative (SQL), added bonus if they understand static vs dynamic typing, weak vs strong typing and static inferred types\"\"\",\n \"\"\"Functional, added bonus if they understand lazy evaluation, currying, continuations\"\"\",\n \"\"\"Concurrent (Erlang, Oz) and Logic (Prolog)\"\"\",\n ]),\n\n (\"platforms with professional experience\", [\n \"\"\"1\"\"\",\n \"\"\"2-3\"\"\",\n \"\"\"4-5\"\"\",\n \"\"\"6+\"\"\",\n ]),\n\n (\"years of professional experience\", [\n \"\"\"1\"\"\",\n \"\"\"2-5\"\"\",\n \"\"\"6-9\"\"\",\n \"\"\"10+\"\"\",\n ]),\n\n (\"domain knowledge\", [\n \"\"\"No knowledge of the domain\"\"\",\n \"\"\"Has worked on at least one product in the domain.\"\"\",\n \"\"\"Has worked on multiple products in the same domain.\"\"\",\n \"\"\"Domain expert. Has designed and implemented several products/solutions in the domain. Well versed with standard terms, protocols used in the domain.\"\"\",\n ]),\n ]),\n)\n\ndef skill_hash_function(skill):\n return md5(skill).hexdigest()\n\ndef slugify(text):\n return re.sub(r\"\\W\", \"_\", text.lower())\n\ndef reverse(coll):\n return list(reversed(coll))"
},
{
"alpha_fraction": 0.5535622835159302,
"alphanum_fraction": 0.5592004060745239,
"avg_line_length": 28.134328842163086,
"blob_id": "ba24c562c54c3ea538189c52e873bd2af28160b0",
"content_id": "8bc246b736f22c286c4b5fa5228aeacaacccfec1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1951,
"license_type": "no_license",
"max_line_length": 100,
"num_lines": 67,
"path": "/loggedin.py",
"repo_name": "RafalSladek/programmer-competency-checklist",
"src_encoding": "UTF-8",
"text": "import webapp2\nimport jinja2\nimport os.path\nfrom google.appengine.api import users\nfrom google.appengine.ext import db\nfrom skills import big_areas, skill_hash_function, slugify, reverse\n\n\njinja2_env = jinja2.Environment(loader=jinja2.FileSystemLoader(os.path.dirname(__file__)))\n\n\nclass Home(webapp2.RequestHandler):\n\n def get(self):\n user = users.get_current_user()\n template = jinja2_env.get_template('index.html')\n values = {\n \"user_is_loggedin\": False,\n \"enumerate\": enumerate,\n \"reverse\": reverse,\n \"len\": len,\n \"slugify\": slugify,\n \"big_areas\": big_areas,\n \"logout_url\": users.create_logout_url(\"/\"),\n \"login_url\": users.create_login_url(self.request.uri),\n }\n if user:\n values.update({\n \"user_is_loggedin\": True,\n \"name\": user.nickname(),\n \"user_skills\": self.get_skills(user),\n })\n self.response.out.write(template.render(values))\n\n def get_skills(self, user):\n q = db.GqlQuery(\"SELECT * FROM User WHERE userid = :1\", user.user_id())\n u = q.get()\n if u:\n return u.skills\n else:\n return []\n\n\nclass Save(webapp2.RequestHandler):\n\n def post(self):\n current_user = users.get_current_user()\n if current_user:\n q = db.GqlQuery(\"SELECT * FROM User WHERE userid = :1\", current_user.user_id())\n user = q.get()\n if not user:\n user = User(userid=current_user.user_id())\n user.put()\n user.skills = [arg for arg in self.request.arguments() if self.request.get(arg) == \"on\"]\n user.save()\n self.redirect(\"/\")\n\n\nclass User(db.Model):\n\n userid = db.StringProperty()\n skills = db.StringListProperty()\n\napp = webapp2.WSGIApplication([\n (\"/\", Home),\n (\"/save\", Save)],\n debug=True)"
},
{
"alpha_fraction": 0.5806451439857483,
"alphanum_fraction": 0.6774193644523621,
"avg_line_length": 30,
"blob_id": "6855c1c75e622c7cf10b6d31121dae2d808fb315",
"content_id": "75131bc3a467615cf7b6547c76584c25282c640c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 62,
"license_type": "no_license",
"max_line_length": 49,
"num_lines": 2,
"path": "/run.sh",
"repo_name": "RafalSladek/programmer-competency-checklist",
"src_encoding": "UTF-8",
"text": "#!/bin/bash\npython2.7 $(which dev_appserver.py) --port 8080 .\n"
}
] | 5 |
AlekseyKovy/mikran | https://github.com/AlekseyKovy/mikran | b28a46a5d85bdc97c79a9866562992ea881edb2b | fad480261a82cf8b504ff2e6f507a4a0f2ef236e | 1b8904c6d1adda1d20af936ce6f41e1dfef232ab | refs/heads/master | 2022-04-19T14:58:11.703585 | 2020-04-18T09:06:27 | 2020-04-18T09:06:27 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7226053476333618,
"alphanum_fraction": 0.7226053476333618,
"avg_line_length": 32.46154022216797,
"blob_id": "cd14d7c7b48e9db7aa1f19b48483230642699304",
"content_id": "14bd27e8ce2277272c94cda4a1a3d6733acf31f2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1321,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 39,
"path": "/server/cabinet/views.py",
"repo_name": "AlekseyKovy/mikran",
"src_encoding": "UTF-8",
"text": "from django.shortcuts import render, redirect\nfrom django.http import HttpResponse\nfrom django.contrib.auth import authenticate, login, logout\nfrom django.views.decorators.csrf import csrf_exempt\nfrom django.middleware.csrf import get_token\nfrom json import dumps\nfrom django.contrib.auth.decorators import login_required\nfrom .models import Profile\nfrom django.contrib.auth.models import User\n\n@csrf_exempt\ndef authentication(request):\n username = request.POST['username']\n password = request.POST['password']\n csrf_token = get_token(request)\n user = authenticate(username=username, password=password)\n if user is not None:\n login(request, user)\n return HttpResponse({'first_name': user.username, ' last_name': user.last_name, 'email': user.email})\n else:\n return HttpResponse('fail')\n\n@csrf_exempt\ndef cabinet(request):\n if request.user.is_authenticated:\n profile = Profile.objects.filter(user=request.user)\n fields = 'group' #Вводим нужные поля\n return HttpResponse(profile.values(fields))\n else:\n return HttpResponse(\"Fail\")\n\n\n@csrf_exempt\ndef logout_view(request):\n if request.user.is_authenticated:\n logout(request)\n return HttpResponse(\"Succes\")\n else:\n return HttpResponse(\"Already logged out\")\n"
},
{
"alpha_fraction": 0.49059560894966125,
"alphanum_fraction": 0.5391849279403687,
"avg_line_length": 13.199999809265137,
"blob_id": "7c0bb26bd3b0204eb2662c270e427dddde4e0984",
"content_id": "9a5b2007e5af7535defd1a6b7aa837eb49ef8879",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "YAML",
"length_bytes": 638,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 45,
"path": "/docker-compose.yaml",
"repo_name": "AlekseyKovy/mikran",
"src_encoding": "UTF-8",
"text": "version: '3'\n\nservices:\n db2:\n build: ./db\n tty: true\n \n volumes: \n - C:/python/micran2/db/data:/var/lib/postgresql\n ports:\n - \"5432:5432\"\n\n\n \n server:\n build: ./server\n tty: true\n volumes:\n - C:/python/micran2/server:/usr/src/server/\n ports:\n - \"8000:8000\"\n depends_on:\n - db2\n# command: ls \n command: sh /usr/src/server/run.sh\n\n\n\n\n client:\n build: ./client\n tty: true\n volumes:\n - C:/python/micran2/client:/usr/src/project/\n ports:\n - \"5000:5000\"\n depends_on:\n - db2\n command: sh /usr/src/project/run.sh \n\n\n\n \n\n#docker-compose up -d"
},
{
"alpha_fraction": 0.75,
"alphanum_fraction": 0.75,
"avg_line_length": 16,
"blob_id": "8cef7830fe58cfc955842095ba5bc8ea2dee0054",
"content_id": "ef4a4df7b301c0aaba155ec9ba0df5b22a999cb8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 16,
"license_type": "no_license",
"max_line_length": 16,
"num_lines": 1,
"path": "/client/run.sh",
"repo_name": "AlekseyKovy/mikran",
"src_encoding": "UTF-8",
"text": "echo \"well done\""
},
{
"alpha_fraction": 0.5953307151794434,
"alphanum_fraction": 0.5953307151794434,
"avg_line_length": 16.64285659790039,
"blob_id": "6650eb3ae0a838a5883835f924b14ba28b5c3abd",
"content_id": "872deaedb5f8568c1224d9f91d1b292daadba246",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 257,
"license_type": "no_license",
"max_line_length": 42,
"num_lines": 14,
"path": "/prepare.py",
"repo_name": "AlekseyKovy/mikran",
"src_encoding": "UTF-8",
"text": "import os\n\n\npath = os.getcwd().replace(\"\\\\\",\"/\")\n\nhandle = open(\"docker-compose.yamlx\", \"r\")\ndata = handle.readlines() \nhandle.close()\n\n\nhandle = open(\"docker-compose.yaml\", \"w\")\nfor i in data:\n i = i.replace(\"{PATH}\",path)\n handle.write(i) \n \n\n\n\n\n"
},
{
"alpha_fraction": 0.7938144207000732,
"alphanum_fraction": 0.8350515365600586,
"avg_line_length": 23.25,
"blob_id": "5a4641cb867d411a1d2469fd1df26a4bc6034ef1",
"content_id": "77680e29c240ed3df5fd8952bf33a76c09429a57",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 97,
"license_type": "no_license",
"max_line_length": 32,
"num_lines": 4,
"path": "/server/run.sh",
"repo_name": "AlekseyKovy/mikran",
"src_encoding": "UTF-8",
"text": "sleep 5\npython3 manage.py makemigrations\npython3 manage.py migrate\n# python3 manage.py runserver\n"
},
{
"alpha_fraction": 0.6820513010025024,
"alphanum_fraction": 0.6820513010025024,
"avg_line_length": 20.77777862548828,
"blob_id": "97f298b5236cdf89127b55317b04d8d132fd8105",
"content_id": "d58afc9a321334cbce68023fce5e00a213ac305a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 195,
"license_type": "no_license",
"max_line_length": 41,
"num_lines": 9,
"path": "/server/cabinet/urls.py",
"repo_name": "AlekseyKovy/mikran",
"src_encoding": "UTF-8",
"text": "from django.urls import path, include\n\nfrom . import views\n\nurlpatterns = [\n path('login/', views.authentication),\n path('cabinet/', views.cabinet),\n path('logout/', views.logout_view)\n]"
},
{
"alpha_fraction": 0.71875,
"alphanum_fraction": 0.7400568127632141,
"avg_line_length": 46,
"blob_id": "e860c50b551b2b57b496351a849b3a41933b8ee8",
"content_id": "71c2c765b915961aca4cc8beec37930797802e04",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 704,
"license_type": "no_license",
"max_line_length": 64,
"num_lines": 15,
"path": "/server/cabinet/models.py",
"repo_name": "AlekseyKovy/mikran",
"src_encoding": "UTF-8",
"text": "from django.db import models\nfrom django.contrib.auth.models import User\n\n\nclass Profile(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE)\n sex = models.CharField(max_length=5, blank=False)\n subdivision = models.CharField(max_length=30, blank=False)\n birth_date = models.DateField(null=True, blank=False)\n position = models.CharField(max_length=30, blank=False)\n experience = models.FloatField(blank=False, default='0.0')\n shift = models.CharField(max_length=30, blank=False)\n part_time_job = models.CharField(max_length=30, blank=False)\n group = models.CharField(max_length=30, blank=False)\n lateness = models.TimeField(max_length=30, blank=False)"
}
] | 7 |
winston19851212/guess-number | https://github.com/winston19851212/guess-number | 4f857abcc503ece3eeca10e3dab5f63ef90dc922 | 23193b97743230d3b720a37eee31fbde4c7f8214 | bfc08a6c8258f723959237d42cfe0b33e7068b92 | refs/heads/main | 2023-06-08T16:29:08.821552 | 2021-07-03T07:10:27 | 2021-07-03T07:10:27 | 382,548,270 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6240310072898865,
"alphanum_fraction": 0.6395348906517029,
"avg_line_length": 20.25,
"blob_id": "921c0bee22716204fdd6497c08298feb8369051e",
"content_id": "1d09f4ad94fc0780e1846f17e701b1f14dfbafc7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 258,
"license_type": "no_license",
"max_line_length": 35,
"num_lines": 12,
"path": "/r.py",
"repo_name": "winston19851212/guess-number",
"src_encoding": "UTF-8",
"text": "import random\nr = random.randint(1, 100)\nwhile True:\n\tnum = input('give it a nuumber')\n\tnum = int(num)\n\tif num == r:\n\t\tprint('yes you got it! YAYAYAYA')\n\t\tbreak\n\telif num > r:\n\t\tprint('more than the answer')\n\telif num < r:\n\t\tprint('less than the answer')\n\t\t\n"
}
] | 1 |
silveiravh/word_array | https://github.com/silveiravh/word_array | b7c584b04132a1860f4ba117634e3b38eba6902f | 5c81b0f667496a65e623680773a68509190f99fc | 504956fb11588e33544c898ee686d6f484635dc1 | refs/heads/master | 2023-01-31T22:44:07.429039 | 2020-12-14T20:27:09 | 2020-12-14T20:27:09 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7155448794364929,
"alphanum_fraction": 0.7528044581413269,
"avg_line_length": 31,
"blob_id": "a35ffe9e42198b53abe069729ae4656d96823344",
"content_id": "24559a56330b7704d1647380f4faf88b7a0e977b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2589,
"license_type": "no_license",
"max_line_length": 376,
"num_lines": 78,
"path": "/readme.md",
"repo_name": "silveiravh/word_array",
"src_encoding": "UTF-8",
"text": "**Linguagem de Programação Utilizada**\n- Python 3.9.0 (necessário instalar biblioteca Flask-RESTful através do comando 'pip install Flask-RESTful')\n\n**A Postman Collection presente no repositório permite testar a API**\n\nEsta API REST permite ao usuário enviar textos de entrada e gera como resultado o vucabulário formado pelas palavras dos textos (ignorando repetições, case, pontuação e palavras que não agragam valor ao vacabulário do texto chamadas *stopwords*) e um vetor de repetição que conta quantas vezes cada termo daquele vocabulário aparece no texto. Considera os seguintes cenários:\\\n\n**1. o vocabulário é composto de palavras isoladas;**\\\nExemplo:\\\ntexto1: “Falar é fácil. Mostre-me o código.”\\\ntexto2: “É fácil escrever código. Difícil é escrever código que funcione.”\\\nVocabulário:\n1. falar\n2. é\n3. fácil\n4. mostre\n5. me\n6. o\n7. código\n8. escrever\n9. difícil\n10. que\n11. funcione\n\nVetor de repetição:\\\ntexto1: [1,1,1,1,1,1,1,0,0,0,0]\\\ntexto2: [0,2,1,0,0,0,2,2,1,1,1]\n\n**2. o vocabulário é composto de grupos de duas palavras em sequência (2-gram);**\nExemplo:\\\nConsiderando os mesmos textos 1 e 2, o vocabulário seria:\n1. falar é\n2. é fácil\n3. fácil mostre\n4. mostre me\n5. me o\n6. o código\n7. fácil escrever\n8. escrever código\n9. código difícil\n10. difícil é\n11. é escrever\n12. código que\n13. que funcione\n\nVetor de repetição:\\\ntexto1: [1,1,1,1,1,1,0,0,0,0,0,0,0]\\\ntexto2: [0,1,0,0,0,0,1,2,1,1,1,1,1]\n\ne assim por diante (podendo trabalhar com sequências n-gram sendo n um número natural inteiro diferente de zero).\n\n**Envio de textos**\n- Para testar a API nessa versão inicial o envio de textos deve ser feito no formato JSON:\n```json\n{\n \"id\": 1,\n \"content\": \"Falar é fácil. Mostre-me o código.\"\n}\n```\nsendo 'id' o identificador único do texto e 'content' seu conteúdo. O texto será enviado utilizando o seguinte método:\n- POST host:port/text\n\ncom o body da requisição sendo como descrito acima.\n\n\n**Vocabulário n-gram**\n\nO usuário poderá solicitar o vocabulário n-gram através do seguinte método:\n- GET host:port/vocabulary/\\<int:gram\\>\n\nsendo gram um inteiro positivo diferente de zero que define como as palavras serão agregadas no vocabulário.\n\n**Vetores de repetições para os textos**\n\nO usuário poderá solicitar os vetores de repetições para os textos considerando um vocabulário n-gram através do seguinte método:\n- GET host:port/wordfrequency/\\<int:gram\\>\n\nsendo gram um inteiro positivo diferente de zero que define como as palavras serão agregadas no vocabulário.\n"
},
{
"alpha_fraction": 0.6243478059768677,
"alphanum_fraction": 0.6273912787437439,
"avg_line_length": 38,
"blob_id": "3ae78b2a7496beca6ddd1ae1d8dfc5a202a5a67b",
"content_id": "fe8e01bf398333d610ee18a4781c2deeb5303ab1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2307,
"license_type": "no_license",
"max_line_length": 165,
"num_lines": 59,
"path": "/code/app.py",
"repo_name": "silveiravh/word_array",
"src_encoding": "UTF-8",
"text": "from flask import Flask, request\nfrom flask_restful import Resource, Api\nimport nltk\nimport string\nfrom nltk import ngrams\nfrom typing import List\n\nnltk.download('stopwords')\nstopwords = nltk.corpus.stopwords.words('portuguese')\n\napp = Flask(__name__)\napi = Api(app)\n\ntexts = []\n\nclass Text(Resource):\n def post(self):\n data = request.get_json()\n new_text = {'id': data['id'], 'content': data['content']}\n texts.append(new_text)\n return new_text, 201\n\nclass Vocabulary(Resource):\n @classmethod\n def build_vocabulary(cls, gram: int) -> List:\n word_list = []\n for text in texts:\n word_list.extend(ngrams(text['content']\n .lower() # transforma tudo em lowercase para desconsiderar o case\n .replace('-', ' ') # substitui '-' por ' ' para considerar duas palavras no caso de palavras compostas (ex. mostre-me será 'mostre' e 'me' separadamente)\n .split(), gram)) # aplica o n-gram conforme o valor de gram passado na request\n word_list = [' '.join(word) for word in word_list] # transforma de tuple para list\n word_list = [word.translate(str.maketrans('', '', string.punctuation)) for word in word_list if word not in stopwords] # remove pontuação e stopwords\n word_list = list(dict.fromkeys(word_list)) # remove duplicatas\n return word_list\n \n def get(self, gram):\n return ({'vocabulary': Vocabulary.build_vocabulary(gram)})\n\nclass WordFrequencyList(Resource):\n def get(self, gram):\n word_list = Vocabulary.build_vocabulary(gram)\n list_word_frequency = []\n for text in texts:\n word_frequency = []\n for word in word_list:\n word_frequency.append(text['content']\n .lower()\n .replace('-', ' ') # substitui '-' por ' '\n .translate(str.maketrans('', '', string.punctuation)) # remove pontuação\n .count(word)) #conta a repetição da palavra no texto\n list_word_frequency.append(word_frequency)\n return ({'list_word_frequency': list_word_frequency})\n \napi.add_resource(Text, '/text')\napi.add_resource(Vocabulary, '/vocabulary/<int:gram>')\napi.add_resource(WordFrequencyList, '/wordfrequency/<int:gram>')\n\napp.run(port=5000)"
}
] | 2 |
nwhobart/pricecheck | https://github.com/nwhobart/pricecheck | 620453566af0c5cc1c6fa9ef6a2e03046e6bce33 | a14c0a7decfa4b0f268df4a530abd10598a3e2dc | eeca2c4539a6a67c21eb8ffe18a37f3a22178001 | refs/heads/master | 2022-12-14T23:30:16.968927 | 2022-04-12T17:01:16 | 2022-04-12T17:01:16 | 204,819,244 | 1 | 0 | MIT | 2019-08-28T01:10:05 | 2022-04-22T17:57:15 | 2022-12-08T08:58:57 | Python | [
{
"alpha_fraction": 0.669910192489624,
"alphanum_fraction": 0.6893712282180786,
"avg_line_length": 26.83333396911621,
"blob_id": "8201995c7fb645cd12a29ef0c19ec5e60aa5dce5",
"content_id": "d4bb6accf17074d0603579adfc7458d8bcd02a20",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1337,
"license_type": "permissive",
"max_line_length": 102,
"num_lines": 48,
"path": "/comedhourly.py",
"repo_name": "nwhobart/pricecheck",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python3\nfrom bs4 import BeautifulSoup\nimport argparse\nimport arrow\nimport csv\nimport pprint\nimport re\nimport requests\nimport sys\n\nparser = argparse.ArgumentParser(description='hurrr-durrr.')\nparser.add_argument('--sort', nargs='?',choices=['low', 'high'])\n\nargs = parser.parse_args()\n\nr = requests.get('https://hourlypricing.comed.com/rrtp/ServletFeed?type=pricingtabledaynexttomorrow')\nsoup = BeautifulSoup(r.text, 'html.parser')\npp = pprint.PrettyPrinter(indent=2)\nprices = list(re.findall(r\"(...¢)\",soup.text))\ntimes = list(range(0,24))\nzipped = zip(times, prices)\nzipped2 = zip(times, prices)\ntable = list(zip(times, prices))\nlow = sorted(zipped, key=lambda x: x[1])\nhigh = sorted(zipped2, key=lambda x: x[1],reverse=True)\n\ndef safety_checks():\n sys.tracebacklimit = 0\n right_now = arrow.now().format('HH:mm:ss')\n if right_now <= \"16:30:00\":\n raise RuntimeError(\"ComEd publishes rates at 16:30. The time is currently: {}\" .format(right_now))\n exit(1)\n if r.status_code is not 200:\n raise RuntimeError(\"ComEd servers are acting up. The return code is: {}\" .format(r.status_code))\n exit (1)\n return safety_checks\n\ndef main():\n safety_checks()\n if args.sort == \"low\":\n pp.pprint(low)\n elif args.sort == \"high\":\n pp.pprint(high)\n else:\n pp.pprint(table)\n\nif __name__ == \"__main__\":\n main()\n"
},
{
"alpha_fraction": 0.7821229100227356,
"alphanum_fraction": 0.7821229100227356,
"avg_line_length": 43.75,
"blob_id": "07baaee31d4ed55698b4bc585e7bfe0e9a99543b",
"content_id": "09d9bf0e2548c595f702214b18a1615b15c904b2",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 179,
"license_type": "permissive",
"max_line_length": 121,
"num_lines": 4,
"path": "/README.md",
"repo_name": "nwhobart/pricecheck",
"src_encoding": "UTF-8",
"text": "# pricecheck\n[](https://travis-ci.org/hobakill/pricecheck)\n\nGetting next-day hourly pricing from ComEd\n"
},
{
"alpha_fraction": 0.4922279715538025,
"alphanum_fraction": 0.6943005323410034,
"avg_line_length": 16.545454025268555,
"blob_id": "3d62302845e5b03bc321b6a1d7e661579f8f477e",
"content_id": "98f04ce75da93856b03048fcb711b80f20fc2965",
"detected_licenses": [
"MIT"
],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 193,
"license_type": "permissive",
"max_line_length": 27,
"num_lines": 11,
"path": "/requirements.txt",
"repo_name": "nwhobart/pricecheck",
"src_encoding": "UTF-8",
"text": "-i https://pypi.org/simple/\narrow==0.14.6\nbeautifulsoup4==4.8.0\ncertifi==2020.12.5\nchardet==3.0.4\nidna==2.8\npython-dateutil==2.8.1\nrequests==2.22.0\nsix==1.15.0\nsoupsieve==2.2.1\nurllib3==1.26.5\n"
}
] | 3 |
ChittojiMuraliSreeKrishna/PythonCodes | https://github.com/ChittojiMuraliSreeKrishna/PythonCodes | e0e8721f598eec468d1315a4f075818e0788e738 | bcf499b1fb346d1153a8181a7934368ab5832a70 | eb0251349f6fb755b9ff85267091effb2ce316af | refs/heads/main | 2023-06-17T19:32:21.541983 | 2021-07-22T14:22:22 | 2021-07-22T14:22:22 | 361,216,443 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6245733499526978,
"alphanum_fraction": 0.6245733499526978,
"avg_line_length": 31.55555534362793,
"blob_id": "85ae6933d15be1338837cb1852b9799c882067f4",
"content_id": "df2b38f3a264dac2a70f144a420e42d5b9945fd7",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 293,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 9,
"path": "/Bulkfile_rename.py",
"repo_name": "ChittojiMuraliSreeKrishna/PythonCodes",
"src_encoding": "UTF-8",
"text": "import os\nos.chdir('/home/wargun/Documents/')\nfor f in os.listdir():\n file_name, file_ext = os.path.splitext(f)\n file_title, file_num = file_name\n f_title = file_title.strip()\n f_num = file_num.strip()\n Rename = '{}-{}'.format(f_num, f_title, file_ext)\n os.rename(f, Rename)\n"
},
{
"alpha_fraction": 0.4482758641242981,
"alphanum_fraction": 0.4482758641242981,
"avg_line_length": 11.428571701049805,
"blob_id": "985de27291c4110f2fc479ac0495a4de7a679a0a",
"content_id": "93912f4da41e9ac78e52abc4d04ccdc2471a86d5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 87,
"license_type": "no_license",
"max_line_length": 14,
"num_lines": 7,
"path": "/word.py",
"repo_name": "ChittojiMuraliSreeKrishna/PythonCodes",
"src_encoding": "UTF-8",
"text": "word_list = [\n 'warlord',\n 'wargun',\n 'nissan',\n 'honda',\n 'luciale',\n]\n"
},
{
"alpha_fraction": 0.6192660331726074,
"alphanum_fraction": 0.6247706413269043,
"avg_line_length": 44.41666793823242,
"blob_id": "0403c422720a5d29d3b0b9135fb9719ce208ce25",
"content_id": "01ea794201c902891cb293162cb990286f28b960",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1090,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 24,
"path": "/File_sorter.py",
"repo_name": "ChittojiMuraliSreeKrishna/PythonCodes",
"src_encoding": "UTF-8",
"text": "import os\nimport shutil\n\npath = '/home/wargun/Videos/'\nnames = os.listdir(path)\nfolder_name = ['mkv', 'mp4', 'py', 'txt', 'js', 'html', 'css']\nfor x in range(0, 2):\n if not os.path.exists(path+folder_name[x]):\n os.makedirs(path+folder_name[x])\nfor files in names:\n if '.mkv' in files and not os.path.exists(path+'mkv/'+files):\n shutil.move(path+files, path+'mkv/'+files)\n if '.mp4' in files and not os.path.exists(path+'mp4/'+files):\n shutil.move(path+files, path+'mp4/'+files)\n if '.py' in files and not os.path.exists(path+'py/'+files):\n shutil.move(path+files, path+'py/'+files)\n if '.html' in files and not os.path.exists(path+'html/'+files):\n shutil.move(path+files, path+'html/'+files)\n if '.txt' in files and not os.path.exists(path+'txt/'+files):\n shutil.move(path+files, path+'txt/'+files)\n if '.js' in files and not os.path.exists(path+'js/'+files):\n shutil.move(path+files, path+'js/'+files)\n if '.css' in files and not os.path.exists(path+'css/'+files):\n shutil.move(path+files, path+'css/'+files)\n"
},
{
"alpha_fraction": 0.4516916573047638,
"alphanum_fraction": 0.4791199862957001,
"avg_line_length": 26.87670135498047,
"blob_id": "927fad080c479966c597aed1e340667ddafb458b",
"content_id": "29b547d1a275f5cccd673cab2242377e3457f87d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 34818,
"license_type": "no_license",
"max_line_length": 264,
"num_lines": 1249,
"path": "/Calculator.py",
"repo_name": "ChittojiMuraliSreeKrishna/PythonCodes",
"src_encoding": "UTF-8",
"text": "# importing math module as m\nimport math as m\n# importing sys\nimport sys\n# importing the required functions from module\nfrom termcolor import colored, cprint\n# importing time functions\nimport time\n# importing random functions\nfrom tqdm import tqdm, trange\n# this for windows to show colors\nimport os\n\n\n# defining colors , so that we can use again\ndef print_blue(x): return cprint(x, 'cyan', attrs=['bold'])\n\n# class for basic rules so that we can call again with out entering codes again\n\n\nclass calculator:\n def __init__(self, name):\n self.name = name # taking the name of the user\n\n # list of options for the calculator\n options = '0.prime-number', '1.addition', '2.sutraction', '3.multiply', '4.division', '5.even-odd', '6.range_of_numbers', '7.exponential-power', '8.fibonacci-series', '9.fibonacci_or_not', '10.constatns', '11.trignometry', '12.squareroot', '13.degrees&radians'\n # trignometric list\n subs = '1.cos', '2.sin', '3.tan', '4.cosh', '5.sinh', '6.tanh', '7.acosh', '8.asinh', '9.atanh'\n # degrees & radians\n degs = '1.Degrees to radians', '2.Radians to degrees'\n # it will be automatically called when ever a new object is called\n\n def rules(self): # type of rules\n print(\"\\u001b[34;1m hey\", self.name,\n \"enter only the number aka integers\")\n\n def error(self): # String or charector insert instead of number\n print(\"\\u001b[31;1m hey\", self.name, \"it is not a number, try again\")\n\n def error1(self): # if the option is not available\n print(\n \"\\u001b[31m hey\", self.name, \"this not a correct option, choose the proper one next time\")\n\n def zeroerror(self):\n print(\"\\u001b[34;1m hey\", self.name,\n \"values connot be divided with zero\")\n\n # num values start from here aka the values which you wanna print out and take in\n\n def inum(self): # for int type input\n return int(input(\"\\u001b[35m enter the value: \"))\n\n def fnum1(self): # for float type first input\n return float(input(\"\\u001b[35m enter your first value: \"))\n\n def fnum2(self): # for float type second input\n return float(input(\"\\u001b[35m enter your second value: \"))\n\n def fnum(self): # for float type only those need single input\n return float(input(\"\\u001b[35m enter the value: \"))\n\n def inum1(self): # for int type used for options\n return int(input(\"\\u001b[33;1m enter the option: \"))\n\n def fnum3(self):\n return float(input(\"\\u001b[35m enter your third value: \"))\n\n def fnum4(self):\n return float(input(\"\\u001b[35m enter your forth value: \"))\n\n def fnum5(self):\n return float(input(\"\\u001b[35m enter your fifth value: \"))\n\n def fnum6(self):\n return float(input(\"\\u001b[35m enter your sixth value: \"))\n\n @classmethod\n def Options(cls): # for options\n for option in cls.options:\n print(\"\\u001b[32m\", option)\n\n @classmethod\n def Subs(cls): # for trignometry options\n for sub in cls.subs:\n print(\"\\u001b[32m\", sub)\n\n @classmethod\n def Deg(cls): # for degrees and radians options\n for deg in cls.degs:\n print(\"\\u001b[32m\", deg)\n\n\nclass add_values:\n add = '1.add two-num', '2.add three-num', '3.add four-num', '4.add five-num', '5.add six-num', '6.more than six'\n\n @classmethod\n def adds(cls):\n for ad in cls.add:\n print(\"\\u001b[32m\", ad)\n\n @classmethod\n def Add(cls): # for sum(2)\n return num1+num2\n\n @classmethod\n def Add1(cls): # for sum(3)\n return (num1+num2)+num3\n\n @classmethod\n def Add2(cls): # for sum(4)\n return ((num1+num2)+num3)+num4\n\n @classmethod\n def Add3(cls): # for sum(5)\n return (((num1+num2)+num3)+num4)+num5\n\n @classmethod\n def Add4(cls): # for sum(5)\n return ((((num1+num2)+num3)+num4)+num5)+num6\n\n\nclass sub_values:\n sub = '1.sub two-num', '2.sub three-num', '3.sub four-num', '4.sub five-num', '5.sub six-num', '6.more than six'\n\n @classmethod\n def subt(cls):\n for su in cls.sub:\n print(\"\\u001b[32m\", su)\n\n @classmethod\n def Subt(cls): # for sub(2)\n return num1-num2\n\n @classmethod\n def Subt1(cls): # for sub(3)\n return (num1-num2)-num3\n\n @classmethod\n def Subt2(cls): # for sub(4)\n return ((num1-num2)-num3)-num4\n\n @classmethod\n def Subt3(cls): # for sub(5)\n return (((num1-num2)-num3)-num4)-num5\n\n @classmethod\n def Subt4(cls): # for sub(6)\n return ((((num1-num2)-num3)-num4)-num5)-num6\n\n\nclass mul_values:\n mul = '1.mul two-num', '2.mul three-num', '3.mul four-num', '4.mul five-num', '5.mul six-num', '6.more than six'\n\n @classmethod\n def mult(cls):\n for mu in cls.mul:\n print(\"\\u001b[32m\", mu)\n\n @classmethod\n def Mult(cls): # for sub(2)\n return num1*num2\n\n @classmethod\n def Mult1(cls): # for sub(3)\n return (num1*num2)*num3\n\n @classmethod\n def Mult2(cls): # for sub(4)\n return ((num1*num2)*num3)*num4\n\n @classmethod\n def Mult3(cls): # for sub(5)\n return (((num1*num2)*num3)*num4)*num5\n\n @classmethod\n def Mult4(cls): # for sub(6)\n return ((((num1*num2)*num3)*num4)*num5)*num6\n\n\nclass div_values:\n div = '1.div two-num', '2.div three-num', '3.div four-num', '4.div five-num', '5.div six-num', '6.more than six'\n\n @classmethod\n def divs(cls):\n for di in cls.div:\n print(\"\\u001b[32m\", di)\n\n @classmethod\n def Div(cls): # for sub(2)\n return num1/num2\n\n @classmethod\n def Div1(cls): # for sub(3)\n return (num1/num2)/num3\n\n @classmethod\n def Div2(cls): # for sub(4)\n return ((num1/num2)/num3)/num4\n\n @classmethod\n def Div3(cls): # for sub(5)\n return (((num1/num2)/num3)/num4)/num5\n\n @classmethod\n def Mult4(cls): # for sub(6)\n return ((((num1/num2)/num3)/num4)/num5)/num6\n\n\n# private class\n\n# for loading bar\n\n\ndef loading():\n for i in trange(10):\n time.sleep(0.1) # if your system is slow increase the sleep time\n print()\n\n\n# this is object for the class which is used to call the attributes of it\nbase = calculator(input(\"\\u001b[37;1m your name: \"))\nfun = add_values()\n# just for fun\nloading()\n# from here the actual part starts\nprint_blue(\" %% some basic math functions %%\")\n# now we are calling the object here\ncalculator.rules(base)\n# setting localtime\nlocaltime = time.asctime(time.localtime(time.time()))\n# this will print the time\nprint(\"\\u001b[37;1m time :\", localtime)\n# just using it for gap\nprint(\" \")\n# list of options\ncalculator.Options()\n# juat using this for gap\nprint(\" \")\n\n\n# catching the value errors\nwhile True:\n try:\n option = calculator.inum1(base)\n break\n except ValueError:\n calculator.error(base)\n\n# prime-number\nif option == 0:\n print_blue(\"prime-number\")\n while True:\n try:\n num = calculator.inum(base)\n break\n except ValueError:\n calculator.error(base)\n # num must be grater than 1 ,because when we try to run with 1 all the numbers get divided\n if num > 1:\n # taking i with range from 2 to given value , so that it keeps incrimenting from 2 - number which we have provided\n for i in range(2, num):\n # checking for the given number % i returns 0 or not\n if (num % i) == 0:\n # loading()\n print(\"\\u001b[37;1m\", num, \" is not a prime number\")\n break\n else:\n # loading()\n print(\"\\u001b[37;1m\", num, \" is a prime number\")\n else:\n # loading()\n print(\"\\u001b[37;1m\", num, \" is a prime number\")\n\n# addition\nelif option == 1:\n print_blue(\"addition\")\n print(\"\")\n add_values.adds()\n print(\"\")\n\n while True:\n try:\n adds = calculator.inum1(base)\n break\n except ValueError:\n calculator.error(base)\n\n if adds == 1:\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n print(\" \\u001b[37;1m \", num1, \"+\", num2, \"=\", add_values.Add())\n\n elif adds == 2:\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num3 = calculator.fnum3(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n print(\" \\u001b[37;1m \", num1, \"+\", num2,\n \"+\", num3, \"=\", add_values.Add1())\n\n elif adds == 3:\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num3 = calculator.fnum3(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num4 = calculator.fnum4(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n print(\" \\u001b[37;1m \", num1, \"+\", num2,\n \"+\", num3, \"+\", num4, \"=\", add_values.Add2())\n\n elif adds == 4:\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num3 = calculator.fnum3(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num4 = calculator.fnum4(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num5 = calculator.fnum5(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n print(\" \\u001b[37;1m \", num1, \"+\", num2,\n \"+\", num3, \"+\", num4, \"+\", num5, \"=\", add_values.Add3())\n\n elif adds == 5:\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num3 = calculator.fnum3(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num4 = calculator.fnum4(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num5 = calculator.fnum5(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num6 = calculator.fnum6(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n print(\" \\u001b[37;1m \", num1, \"+\", num2,\n \"+\", num3, \"+\", num4, \"+\", num5, \"+\", num6, \"=\", add_values.Add4())\n\n elif adds == 6:\n while True:\n try:\n num = calculator.fnum(base)\n break\n except ValueError:\n calculator.error(base)\n result = 0\n while num > 0:\n digit = num % 10\n result = result + digit\n num = num // 10\n print(result)\n\n else:\n calculator.error1(base)\n\n# subtraction\nelif option == 2:\n print_blue(\"subtraction\")\n print(\"\")\n sub_values.subt()\n print(\"\")\n\n while True:\n try:\n subt = calculator.inum1(base)\n break\n except ValueError:\n calculator.error(base)\n\n if subt == 1:\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n print(\" \\u001b[37;1m \", num1, \"-\", num2, \"=\", sub_values.Subt())\n\n elif subt == 2:\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num3 = calculator.fnum3(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n print(\" \\u001b[37;1m \", num1, \"+\", num2,\n \"+\", num3, \"=\", sub_values.Subt1())\n\n elif subt == 3:\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num3 = calculator.fnum3(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num4 = calculator.fnum4(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n print(\" \\u001b[37;1m \", num1, \"-\", num2,\n \"-\", num3, \"-\", num4, \"=\", sub_values.Subt2())\n\n elif subt == 4:\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num3 = calculator.fnum3(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num4 = calculator.fnum4(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num5 = calculator.fnum5(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n print(\" \\u001b[37;1m \", num1, \"-\", num2,\n \"-\", num3, \"-\", num4, \"-\", num5, \"=\", sub_values.Subt3())\n\n elif subt == 5:\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num3 = calculator.fnum3(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num4 = calculator.fnum4(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num5 = calculator.fnum5(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num6 = calculator.fnum6(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n print(\" \\u001b[37;1m \", num1, \"-\", num2,\n \"-\", num3, \"-\", num4, \"-\", num5, \"-\", num6, \"=\", sub_values.Subt4())\n\n elif subt == 6:\n while True:\n try:\n num = calculator.fnum(base)\n break\n except ValueError:\n calculator.error(base)\n result = 0\n while num > 0:\n digit = num % 10\n result = result - digit\n num = num // 10\n print(result)\n\n else:\n calculator.error1(base)\n\n# multiplication\nelif option == 3:\n print_blue(\"multiply\")\n print(\"\")\n mul_values.mult()\n print(\"\")\n\n while True:\n try:\n mult = calculator.inum1(base)\n break\n except ValueError:\n calculator.error(base)\n\n if mult == 1:\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n print(\" \\u001b[37;1m \", num1, \"x\", num2, \"=\", mul_values.Mult())\n\n elif mult == 2:\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num3 = calculator.fnum3(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n print(\" \\u001b[37;1m \", num1, \"x\", num2,\n \"x\", num3, \"=\", add_values.Add1())\n\n elif mult == 3:\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num3 = calculator.fnum3(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num4 = calculator.fnum4(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n print(\" \\u001b[37;1m \", num1, \"x\", num2,\n \"x\", num3, \"x\", num4, \"=\", mul_values.Mult2())\n\n elif mult == 4:\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num3 = calculator.fnum3(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num4 = calculator.fnum4(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num5 = calculator.fnum5(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n print(\" \\u001b[37;1m \", num1, \"x\", num2,\n \"x\", num3, \"x\", num4, \"x\", num5, \"=\", mul_values.Mult3())\n\n elif mult == 5:\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num3 = calculator.fnum3(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num4 = calculator.fnum4(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num5 = calculator.fnum5(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num6 = calculator.fnum6(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n print(\" \\u001b[37;1m \", num1, \"x\", num2,\n \"x\", num3, \"x\", num4, \"x\", num5, \"x\", num6, \"=\", mul_values.Mult4())\n\n elif mult == 6:\n while True:\n try:\n num = calculator.fnum(base)\n break\n except ValueError:\n calculator.error(base)\n result = 1\n while num > 0:\n digit = num % 10\n result = result * digit\n num = num // 10\n print(result)\n\n else:\n calculator.error1(base)\n\n# division\nelif option == 4:\n print_blue(\"division\")\n print(\"\")\n div_values.divs()\n print(\"\")\n\n while True:\n try:\n divs = calculator.inum1(base)\n break\n except ValueError:\n calculator.error(base)\n\n if divs == 1:\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n while True:\n try:\n print(\" \\u001b[37;1m \", num1, \"/\", num2, \"=\", div_values.Div())\n break\n except ZeroDivisionError:\n calculator.zeroerror(base)\n break\n\n elif divs == 2:\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num3 = calculator.fnum3(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n while True:\n try:\n print(\" \\u001b[37;1m \", num1, \"/\", num2,\n \"/\", num3, \"=\", div_values.Div1())\n break\n except ZeroDivisionError:\n calculator.zeroerror(base)\n break\n\n elif divs == 3:\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num3 = calculator.fnum3(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num4 = calculator.fnum4(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n while True:\n try:\n print(\" \\u001b[37;1m \", num1, \"/\", num2,\n \"/\", num3, \"/\", num4, \"=\", div_values.Div2())\n break\n except ZeroDivisionError:\n calculator.zeroerror(base)\n break\n\n elif divs == 4:\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num3 = calculator.fnum3(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num4 = calculator.fnum4(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num5 = calculator.fnum5(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n while True:\n try:\n print(\" \\u001b[37;1m \", num1, \"/\", num2,\n \"/\", num3, \"/\", num4, \"/\", num5, \"=\", div_values.Div3())\n break\n except ZeroDivisionError:\n calculator.zeroerror(base)\n break\n\n elif divs == 5:\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num3 = calculator.fnum3(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num4 = calculator.fnum4(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num5 = calculator.fnum5(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num6 = calculator.fnum6(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n while True:\n try:\n print(\" \\u001b[37;1m \", num1, \"/\", num2,\n \"/\", num3, \"/\", num4, \"/\", num5, \"/\", num6, \"=\", add_values.Add4())\n break\n except ZeroDivisionError:\n calculator.zeroerror(base)\n\n elif adds == 6:\n while True:\n try:\n num = calculator.fnum(base)\n break\n except ValueError:\n calculator.error(base)\n result = 0\n while num > 0:\n digit = num % 10\n result = result / digit\n num = num // 10\n print(result)\n\n else:\n calculator.error(base)\n # even-odd\n\n# even-odd\nelif option == 5:\n print_blue(\"even-odd\")\n while True:\n try:\n num = calculator.fnum(base)\n break\n except ValueError:\n calculator.error(base)\n if num % 2 == 0:\n # loading()\n print(\"\\u001b[37;1m\", num, \" is a even number\")\n else:\n # loading()\n print(\"\\u001b[37;1m\", num, \" is a odd number\")\n\n# range_of_numbers\nelif option == 6:\n print_blue(\"range_of_numbers\")\n while True:\n try:\n num = calculator.inum(base)\n break\n except ValueError:\n calculator.error(base)\n for i in range(-1, num):\n if i != num:\n print(\"\\u001b[37m\", i+1)\n else:\n print(\"this is end\")\n\n# exponential power\nelif option == 7:\n print_blue(\"exponential-power\")\n while True:\n try:\n num1 = calculator.fnum1(base)\n break\n except ValueError:\n calculator.error(base)\n while True:\n try:\n num2 = calculator.fnum2(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n print(\"\\u001b[37;1m exponent: \", num1, \"^\", num2, \"=\", m.pow(num1, num2))\n\n# fibonacci-series\nelif option == 8:\n print_blue(\"fibonacci-series\")\n while True:\n try:\n num = calculator.inum(base)\n break\n except ValueError:\n calculator.error(base)\n var1 = 0\n var2 = 1\n for i in range(num):\n var3 = var1\n var1 = var2\n var2 = var3+var2\n print(\"\\u001b[37;1m\", var3)\n\n# fibonacci or not\nelif option == 9:\n print_blue(\"fibonacci-or-not\")\n\n def perfectsquare(value):\n var = int(m.sqrt(value))\n return var*var == value\n while True:\n try:\n num = calculator.inum(base)\n break\n except ValueError:\n calculator.error(base)\n var1 = 5*(num*num)+4\n var2 = 5*(num*num)-4\n if perfectsquare(var1) or perfectsquare(var2):\n # loading()\n print(num, \"\\u001b[37;1m is a fibonacci number\")\n else:\n # loading()\n print(num, \"\\u001b[37;1m is not a fibonacci number\")\n\n# constants\nelif option == 10:\n # loading()\n print_blue(\"constants\")\n print(\"\\u001b[37;1m 1.the value of pi: \", m.pi)\n print(\"\\u001b[37;1m 2.the value of eplison: \", m.e)\n print(\"\\u001b[37;1m 3.the value of tau: \", m.tau)\n\n# trignometry\nelif option == 11:\n calculator.rules(base)\n print_blue(\" trignometry\")\n print('')\n calculator.Subs()\n print('')\n while True:\n try:\n sub = calculator.inum1(base)\n break\n except ValueError:\n calculator.error(base)\n if sub == 1:\n print_blue(\"cos()\")\n while True:\n try:\n num = calculator.fnum(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n print(\"\\u001b[37;1m cos( \", num, \")=\", m.cos(num))\n elif sub == 2:\n print_blue(\"sin()\")\n while True:\n try:\n num = calculator.fnum(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n print(\"\\u001b[37;1m sin( \", num, \")=\", m.sin(num))\n elif sub == 3:\n print_blue(\"tan()\")\n while True:\n try:\n num = calculator.fnum(base)\n break\n except ValueError:\n calculator.error(base)\n print(\"\\u001b[37;1m tan( \", num, \")=\", m.tan(num))\n # loading()\n elif sub == 4:\n print_blue(\"cosh()\")\n while True:\n try:\n num = calculator.fnum(base)\n break\n except ValueError:\n calculator.error(base)\n print(\"\\u001b[37;1m cosh( \", num, \")=\", m.cosh(num))\n elif sub == 5:\n print_blue(\"sinh()\")\n while True:\n try:\n num = calculator.fnum(base)\n break\n except ValueError:\n calculator.error(base)\n print(\"\\u001b[37;1m sinh( \", num, \")=\", m.sinh(num))\n elif sub == 6:\n print_blue(\"tanh()\")\n while True:\n try:\n num = calculator.fnum(base)\n break\n except ValueError:\n calculator.error(base)\n print(\"\\u001b[37;1m tanh( \", num, \")=\", m.tanh(num))\n elif sub == 7:\n print_blue(\"acosh()\")\n while True:\n try:\n num = calculator.fnum(base)\n break\n except ValueError:\n calculator.error(base)\n print(\"\\u001b[37;1m acosh( \", num, \")=\", m.acosh(num))\n elif sub == 8:\n print_blue(\"asinh()\")\n while True:\n try:\n num = calculator.fnum(base)\n break\n except ValueError:\n calculator.error(base)\n print(\"\\u001b[37;1m asinh( \", num, \")=\", m.asinh(num))\n elif sub == 9:\n print_blue(\"atanh()\")\n while True:\n try:\n num = calculator.fnum(base)\n break\n except ValueError:\n calculator.error(base)\n print(\"\\u001b[37;1m atanh( \", num, \")=\", m.atanh(num))\n else:\n calculator.error1(base)\n\n# square-root\nelif option == 12:\n print_blue(\"square-root\")\n while True:\n try:\n num = calculator.fnum(base)\n break\n except ValueError:\n calculator.error(base)\n # loading()\n print(\"\\u001b[37;1m the squareroot of\", num, \"=\", m.sqrt(num))\n\n# degrees and radians\nelif option == 13:\n print_blue(\"degrees to radians\")\n calculator.rules(base)\n print(\"\")\n calculator.Deg()\n print(\"\")\n while True:\n try:\n deg = calculator.fnum(base)\n break\n except ValueError:\n calculator.error(base)\n if deg == 1:\n print_blue(\"radians to degrees\")\n while True:\n try:\n num = calculator.num3(base)\n break\n except ValueError:\n calculator.error(base)\n print(\"\\u001b[37;1m the degrees(\", num,\n \")\" \"radians =\", m.degrees(num))\n elif deg == 2:\n while True:\n try:\n num = calculator.fnum(base)\n break\n except ValueError:\n calculator.error(base)\n print(\"\\u001b[37;1m the radians(\", num,\n \")\" \"degrees =\", m.radians(num))\n else:\n calculator.error1(base)\n\n# if option is out of bound\nelse:\n calculator.error1(base)\n"
}
] | 4 |
zhengwei6/Intro.-to-Artificial-Intelligence-Spring-Semester-2019 | https://github.com/zhengwei6/Intro.-to-Artificial-Intelligence-Spring-Semester-2019 | 203ff56e3dbb53233c133db26fb7456747a505c6 | 9fe004416a7004dac0e8efc90debebbb3f3fdeaa | fb93a6540c4ef7692bfd1d12ed5bf521d07b272a | refs/heads/master | 2020-05-04T15:00:23.651507 | 2019-04-30T04:20:37 | 2019-04-30T04:20:37 | 179,219,787 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4815463125705719,
"alphanum_fraction": 0.5122207403182983,
"avg_line_length": 39.14985656738281,
"blob_id": "e7dd4075fd074de2b40630dfffd73067dd0dd075",
"content_id": "7097b94a298d73153d6f6ae8f056a731ca1954fb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14291,
"license_type": "no_license",
"max_line_length": 140,
"num_lines": 347,
"path": "/HW1/main.py",
"repo_name": "zhengwei6/Intro.-to-Artificial-Intelligence-Spring-Semester-2019",
"src_encoding": "UTF-8",
"text": "import pandas as pd\r\nimport numpy as np \r\nimport copy\r\nimport functools\r\nimport random\r\nimport csv\r\n\r\nclass puzzleInfo():\r\n def __init__(self,puzzleIndex,wordGroup):\r\n if puzzleIndex == 0:\r\n self.constraintMap = [[-1,0,0,-1,-1],[0,-1,-1,-1,0],[2,-1,-1,0,2],[-1,-1,2,-1,-1],[-1,3,3,-1,-1]]\r\n self.variableLen = [4,5,4,2,3]\r\n elif puzzleIndex == 1:\r\n self.constraintMap = [[-1,1,2,-1,-1,-1],[1,-1,-1,0,-1,-1],[3,-1,-1,2,0,-1],[-1,3,4,-1,-1,0],[-1,-1,6,-1,-1,2],[-1,-1,-1,4,2,-1]]\r\n self.variableLen = [5,5,7,5,4,3]\r\n elif puzzleIndex == 2:\r\n self.constraintMap = [[-1,0,0,-1,-1,-1],[0,-1,-1,-1,2,0],[3,-1,-1,-1,5,3],[-1,-1,-1,-1,0,-1],[-1,2,2,1,-1,-1],[-1,4,4,-1,-1,-1]]\r\n self.variableLen = [4,5,5,3,6,4]\r\n else:\r\n self.constraintMap = [[-1,0 ,-1,-1,0 ,-1,-1,-1,-1,-1,-1,-1],\r\n [0 ,-1,-1,-1,-1,-1,0 ,0 ,-1,-1,-1,-1],\r\n [-1,-1,-1,1 ,1 ,0 ,-1,-1,-1,-1,-1,-1],\r\n [-1,-1,2 ,-1,-1,-1,-1,-1,-1,-1,-1,-1],\r\n [4 ,-1,0 ,-1,-1,-1,4 ,4 ,3 ,-1,-1,-1],\r\n [-1,-1,3 ,-1,-1,-1,7 ,-1,-1,-1,-1,-1],\r\n [-1,3 ,-1,-1,3 ,2 ,-1,-1,-1,0 ,-1,-1],\r\n [-1,5 ,-1,-1,5 ,-1,-1,-1,-1,2 ,0 ,-1],\r\n [-1,-1,-1,-1,7 ,-1,-1,-1,-1,4 ,-1,-1],\r\n [-1,-1,-1,-1,-1,-1,2 ,2 ,1 ,-1,-1,-1],\r\n [-1,-1,-1,-1,-1,-1,-1,6 ,-1,-1,-1,0 ],\r\n [-1,-1,-1,-1,-1,-1,-1,-1,-1,-1,1 ,-1]]\r\n self.variableLen = [5,7,4,2,8,4,8,7,4,5,2,2]\r\n \r\n\r\nclass puzzleNode():\r\n def __init__(self):\r\n self.assignVarIndex = None\r\n self.assignWrdIndex = None \r\n self.domain = []\r\n\r\n def init_domain(self,var_len,wordGroup):\r\n self.alreadyAssign = np.empty(len(var_len))\r\n self.alreadyAssign.fill(-1)\r\n print(\"First domain example:\")\r\n for length in var_len:\r\n self.domain.append(wordGroup[length].values)\r\n print(length,wordDataFrame.at[wordGroup[length].values[0],'words'])\r\n\r\n print(\"First node domain len:\",len(self.domain))\r\n \r\n def print_domain(self):\r\n print(self.domain)\r\n\r\n def set_domain(self):\r\n # set assignVarIndex = 0 , assignWrdIndex = 500\r\n if self.assignVarIndex is not None :\r\n self.domain[self.assignVarIndex] = np.array([self.assignWrdIndex])\r\n\r\n def update_domain(self,constraintMap):\r\n varIndex = self.assignVarIndex\r\n wrdIndex = self.assignWrdIndex\r\n self.alreadyAssign[varIndex] = wrdIndex \r\n assignWord = wordDataFrame.at[wrdIndex,'words']\r\n for index,element in enumerate(self.alreadyAssign):\r\n if element == -1 :\r\n prohibitIndex = constraintMap[varIndex][index]\r\n if prohibitIndex == -1:\r\n continue\r\n doProhitbitWord = assignWord[constraintMap[index][varIndex]]\r\n delete_list = []\r\n for index2,element2 in enumerate(self.domain[index]):\r\n if wordDataFrame.at[element2,'words'][prohibitIndex] != doProhitbitWord:\r\n delete_list.append(index2)\r\n \r\n self.domain[index] = np.delete(self.domain[index],delete_list)\r\n else:\r\n continue\r\n\r\n def checkConsistency(self):\r\n for element in self.domain:\r\n if element.size == 0:\r\n return False\r\n solution = 1\r\n for index,element in enumerate(self.alreadyAssign):\r\n if element == -1:\r\n solution = 0\r\n \r\n if solution == 1:\r\n #print(\"Following is solution dictionary index:\")\r\n ans = []\r\n for e in self.alreadyAssign:\r\n ans.append(wordDataFrame.at[int(e),'words'])\r\n check = 0\r\n for element in answer:\r\n check = 1\r\n for index2,element2 in enumerate(element):\r\n if element2 != ans[index2]:\r\n check = 0\r\n if check == 1:\r\n break\r\n if check != 1:\r\n answer.append(ans)\r\n return False\r\n else:\r\n return True\r\ndef compareDomain(Node1, Node2):\r\n firstLen = len(Node1.domain[Node1.assignVarIndex])\r\n secondLen = len(Node2.domain[Node2.assignVarIndex])\r\n if firstLen < secondLen :\r\n return 1\r\n elif firstLen > secondLen:\r\n return -1\r\n elif firstLen == secondLen and mode > 0:\r\n firstconstrainNum = 0\r\n secondconstrainNum = 0\r\n for index,element in enumerate(Node1.alreadyAssign):\r\n if element == -1 and puzzleBoard.constraintMap[Node1.assignVarIndex][index] != -1 :\r\n firstconstrainNum = firstconstrainNum + 1\r\n for index2,element2 in enumerate(Node2.alreadyAssign):\r\n if element2 == -1 and puzzleBoard.constraintMap[Node2.assignVarIndex][index2] != -1 :\r\n secondconstrainNum = secondconstrainNum + 1\r\n \r\n if firstconstrainNum < secondconstrainNum:\r\n return -1\r\n elif firstconstrainNum > secondconstrainNum:\r\n return 1\r\n elif mode > 1:\r\n domain1 = copy.copy(Node1.domain)\r\n domain2 = copy.copy(Node2.domain)\r\n count1 = 0\r\n count2 = 0\r\n varIndex = Node1.assignVarIndex\r\n wrdIndex = Node1.assignWrdIndex\r\n assignWord = wordDataFrame.at[wrdIndex,'words']\r\n\r\n varIndex2 = Node2.assignVarIndex\r\n wrdIndex2 = Node2.assignWrdIndex\r\n assignWord2 = wordDataFrame.at[wrdIndex2,'words']\r\n\r\n delete_list = []\r\n for index,element in enumerate(Node1.alreadyAssign):\r\n if element == -1 and index != Node1.assignVarIndex:\r\n prohibitIndex = puzzleBoard.constraintMap[varIndex][index]\r\n if prohibitIndex == -1:\r\n continue\r\n doProhitbitWord = assignWord[puzzleBoard.constraintMap[index][varIndex]]\r\n for index2,element2 in enumerate(domain1[index]):\r\n if wordDataFrame.at[element2,'words'][prohibitIndex] != doProhitbitWord:\r\n delete_list.append(index2)\r\n domain1[index] = np.delete(domain1[index],delete_list)\r\n count1 = count1 + len(domain1[index])\r\n delete_list = []\r\n for index,element in enumerate(Node2.alreadyAssign):\r\n if element == -1 and index != Node2.assignVarIndex:\r\n prohibitIndex = puzzleBoard.constraintMap[varIndex2][index]\r\n if prohibitIndex == -1:\r\n continue\r\n doProhitbitWord = assignWord2[puzzleBoard.constraintMap[index][varIndex2]]\r\n for index2,element2 in enumerate(domain2[index]):\r\n if wordDataFrame.at[element2,'words'][prohibitIndex] != doProhitbitWord:\r\n delete_list.append(index2)\r\n domain2[index] = np.delete(domain2[index],delete_list)\r\n count2 = count2 + len(domain2[index])\r\n if count1 < count2:\r\n return -1\r\n elif count1 > count2:\r\n return 1 \r\n return 0\r\n\r\ndef genChild(parent):\r\n childNode = []\r\n for index,element in enumerate(parent.alreadyAssign):\r\n if element == -1:\r\n for index2,element2 in enumerate(parent.domain[index]):\r\n newNode = puzzleNode()\r\n newNode.assignVarIndex = index\r\n newNode.assignWrdIndex = element2\r\n newNode.domain = copy.copy(parent.domain)\r\n newNode.alreadyAssign = copy.copy(parent.alreadyAssign)\r\n childNode.append(newNode)\r\n #random.shuffle(childNode)\r\n if mode != 3 :\r\n childNode = sorted(childNode,key=functools.cmp_to_key(compareDomain))\r\n #print(childNode[-1].assignVarIndex)\r\n return childNode\r\n\r\ndef genWordGroup(wordDataFrame): \r\n wordDataFrame['wordLength'] = 0\r\n for index, row in wordDataFrame.iterrows():\r\n wordDataFrame.at[index,'wordLength'] = len(row['words'])\r\n \r\n re = wordDataFrame.groupby('wordLength').groups\r\n return re\r\n\r\n# starTest is for testing many kind of mode with heuristic\r\ndef starTest(wordGroup):\r\n expandNodeNum = 0\r\n puzzleStack = []\r\n if mode == 0:\r\n print(\"Heuristic: MRV\")\r\n firstNode = puzzleNode()\r\n firstNode.init_domain(puzzleBoard.variableLen,wordGroup)\r\n puzzleStack.append(firstNode)\r\n print(\"Start to expand nodes\")\r\n i = 0\r\n while puzzleStack:\r\n expandNode = puzzleStack[-1]\r\n puzzleStack.pop()\r\n expandNodeNum = expandNodeNum + 1\r\n if expandNode.assignVarIndex is not None:\r\n expandNode.set_domain()\r\n expandNode.update_domain(puzzleBoard.constraintMap)\r\n \r\n \r\n if expandNode.checkConsistency() == True:\r\n child = genChild(expandNode)\r\n else:\r\n if len(answer) == anserLimit:\r\n print(\"answer equal the limit: \",anserLimit)\r\n break\r\n continue\r\n for index,element in enumerate(child):\r\n puzzleStack.append(element)\r\n print(\"End of the expansion\")\r\n print(\"Number of expand node: \",expandNodeNum)\r\n print(\"-----------------------\")\r\n elif mode == 1:\r\n print(\"Heuristic: MRV、Degree\")\r\n firstNode = puzzleNode()\r\n firstNode.init_domain(puzzleBoard.variableLen,wordGroup)\r\n puzzleStack.append(firstNode)\r\n print(\"Start to expand nodes\")\r\n i = 0\r\n while puzzleStack:\r\n expandNode = puzzleStack[-1]\r\n puzzleStack.pop()\r\n expandNodeNum = expandNodeNum + 1\r\n if expandNode.assignVarIndex is not None:\r\n expandNode.set_domain()\r\n expandNode.update_domain(puzzleBoard.constraintMap)\r\n\r\n \r\n if expandNode.checkConsistency() == True:\r\n #print(456)\r\n child = genChild(expandNode)\r\n else:\r\n #print(123)\r\n if len(answer) == anserLimit:\r\n break\r\n continue\r\n for index,element in enumerate(child):\r\n puzzleStack.append(element)\r\n print(\"End of the expansion\")\r\n print(\"Number of expand node: \",expandNodeNum)\r\n print(\"-----------------------\")\r\n elif mode == 2:\r\n print(\"Heuristic: MRV、Degree、LCV\")\r\n firstNode = puzzleNode()\r\n firstNode.init_domain(puzzleBoard.variableLen,wordGroup)\r\n puzzleStack.append(firstNode)\r\n print(\"Start to expand nodes\")\r\n i = 0\r\n while puzzleStack:\r\n expandNode = puzzleStack[-1]\r\n puzzleStack.pop()\r\n expandNodeNum = expandNodeNum + 1\r\n if expandNode.assignVarIndex is not None:\r\n expandNode.set_domain()\r\n expandNode.update_domain(puzzleBoard.constraintMap)\r\n \r\n if expandNode.checkConsistency() == True:\r\n child = genChild(expandNode)\r\n else:\r\n if len(answer) == anserLimit:\r\n break\r\n continue\r\n \r\n for index,element in enumerate(child):\r\n puzzleStack.append(element)\r\n print(\"End of the expansion\")\r\n print(\"Number of expand node: \",expandNodeNum)\r\n print(\"-----------------------\")\r\n else:\r\n print(\"Heuristic: \")\r\n firstNode = puzzleNode()\r\n firstNode.init_domain(puzzleBoard.variableLen,wordGroup)\r\n puzzleStack.append(firstNode)\r\n print(\"Start to expand nodes\")\r\n i = 0\r\n while puzzleStack:\r\n expandNode = puzzleStack[-1]\r\n puzzleStack.pop()\r\n expandNodeNum = expandNodeNum + 1\r\n if expandNodeNum % 10000 == 0:\r\n print(expandNodeNum)\r\n if expandNode.assignVarIndex is not None:\r\n expandNode.set_domain()\r\n expandNode.update_domain(puzzleBoard.constraintMap)\r\n \r\n if expandNode.checkConsistency() == True:\r\n child = genChild(expandNode)\r\n else:\r\n if len(answer) == anserLimit:\r\n break\r\n continue\r\n \r\n for index,element in enumerate(child):\r\n puzzleStack.append(element)\r\n print(\"End of the expansion\")\r\n print(\"Number of expand node: \",expandNodeNum)\r\n print(\"-----------------------\")\r\n return expandNodeNum\r\n \r\n\r\ndef main():\r\n global mode\r\n global puzzleBoard \r\n global anserLimit\r\n global answer\r\n global wordDataFrame\r\n # init constraints map\r\n # setup mode、 answer 、 answerLimit 、 puzzleBoard\r\n \r\n testingSet = []\r\n for step in range(0,10):\r\n answer = []\r\n anserLimit = 1\r\n wordDataFrame = pd.read_csv('./English-words-3000.txt',sep = \"\\n\",names = ['words'])\r\n wordDataFrame = wordDataFrame.sample(frac=1).reset_index(drop=True) \r\n wordGroup = genWordGroup(wordDataFrame) \r\n puzzleBoard = puzzleInfo(0,wordGroup)\r\n tmpList = []\r\n for i in range(0,3):\r\n answer = []\r\n mode = i\r\n print(\"mode: \",mode)\r\n path = './ans' + str(i) + '.csv'\r\n expandNodeNum = starTest(wordGroup)\r\n tmpList.append(expandNodeNum)\r\n df = pd.DataFrame(answer,columns=['0','1','2','3','4'])\r\n df.to_csv(path,sep = ',')\r\n testingSet.append(tmpList)\r\n df = pd.DataFrame(testingSet,columns=['0','1','2','3','4'])\r\n df.to_csv('output.csv',sep=',')\r\n print(testingSet) \r\nif __name__ == '__main__':\r\n main()\r\n"
},
{
"alpha_fraction": 0.6921659111976624,
"alphanum_fraction": 0.7170506715774536,
"avg_line_length": 49.761905670166016,
"blob_id": "a5b1f8f95cac3d66b63eebda49453459261fe5a3",
"content_id": "a2d40a2b90d1c6a1ebe3f495880ab5063d6198e9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1085,
"license_type": "no_license",
"max_line_length": 124,
"num_lines": 21,
"path": "/PR2/VISUAL.py",
"repo_name": "zhengwei6/Intro.-to-Artificial-Intelligence-Spring-Semester-2019",
"src_encoding": "UTF-8",
"text": "import pandas as pd\r\nimport matplotlib.pyplot as plt\r\ntrainDataframe = pd.read_csv('training.csv')\r\nvalidationDataframe = pd.read_csv('validation.csv')\r\ntrain_mean = trainDataframe.loc[:,'mean_score']/100\r\ntrain_std = trainDataframe.loc[:,'std_score']/100\r\nvalidation_mean = validationDataframe.loc[:,'mean_score']/100\r\nvalidation_std = validationDataframe.loc[:,'std_score']/100\r\ntrain_size = trainDataframe.loc[:,'sample_num']\r\nplt.figure(figsize=(15,10))\r\nplt.plot(train_size, train_mean,color='blue',marker='o',markersize=5,label='training accuracy')\r\nplt.fill_between(train_size,train_mean+train_std,train_mean - train_std,alpha = 0.15)\r\nplt.plot(train_size, validation_mean, color='green', linestyle='--', marker='s', markersize=5, label='validation accuracy')\r\nplt.fill_between(train_size, validation_mean + validation_std, validation_mean - validation_std,alpha = 0.15,color ='green')\r\nplt.grid()\r\nplt.title(\"Change tree number of breast\")\r\nplt.xlabel('Depth of tree')\r\nplt.ylabel('Accuracy')\r\nplt.legend(loc='lower left')\r\nplt.ylim([0,1.0])\r\nplt.show()"
}
] | 2 |
algoding/xam | https://github.com/algoding/xam | f3f53839ab22ce9d3a60728c95858fe76051b0c2 | 43e788b2b9fd9ae2ce1fd57c07fc876babf34f2b | b1d3a6312f48f67738521288c3fa6f6d09008d66 | refs/heads/master | 2021-04-03T08:20:34.406913 | 2018-02-06T16:50:48 | 2018-02-06T16:50:48 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7799174785614014,
"alphanum_fraction": 0.7799174785614014,
"avg_line_length": 24.068965911865234,
"blob_id": "c310e2207335bb412e861f17bff385360c082167",
"content_id": "9a77ee7c23d6a84d81c818ba34b2566d84bb0c16",
"detected_licenses": [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 727,
"license_type": "permissive",
"max_line_length": 74,
"num_lines": 29,
"path": "/tests/test_check_estimator.py",
"repo_name": "algoding/xam",
"src_encoding": "UTF-8",
"text": "from sklearn.utils.estimator_checks import check_estimator\n\nimport xam\n\n\n# Preprocessing\n\ndef test_cycle_transformer():\n assert check_estimator(xam.preprocessing.CycleTransformer) is None\n\n## Binning\n\ndef test_bayesian_blocks_binner():\n assert check_estimator(xam.preprocessing.BayesianBlocksBinner) is None\n\ndef test_equal_frequency_binner():\n assert check_estimator(xam.preprocessing.EqualFrequencyBinner) is None\n\ndef test_equal_width_binner():\n assert check_estimator(xam.preprocessing.EqualWidthBinner) is None\n\ndef test_mdlp_binner():\n assert check_estimator(xam.preprocessing.MDLPBinner) is None\n\n\n# NLP\n\n# def test_top_terms_classifier():\n# assert check_estimator(xam.nlp.TopTermsClassifier) is None\n"
},
{
"alpha_fraction": 0.6934306621551514,
"alphanum_fraction": 0.7141119241714478,
"avg_line_length": 29.44444465637207,
"blob_id": "6f15fb5133a5cee2349cf1b367f4e77cb469c29b",
"content_id": "4f14e3263506bb7e3f86b5f543c9eac246a7909c",
"detected_licenses": [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 822,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 27,
"path": "/docs/nlp.md",
"repo_name": "algoding/xam",
"src_encoding": "UTF-8",
"text": "# Natural Language Processing (NLP)\n\n## Top-terms classifier\n\n```python\n>>> from sklearn.datasets import fetch_20newsgroups\n>>> from sklearn.feature_extraction.text import CountVectorizer\n>>> import xam\n\n>>> cats = ['alt.atheism', 'comp.windows.x']\n>>> newsgroups_train = fetch_20newsgroups(subset='train', categories=cats)\n>>> newsgroups_test = fetch_20newsgroups(subset='test', categories=cats)\n\n>>> vectorizer = CountVectorizer(stop_words='english', max_df=0.2)\n\n>>> X_train = vectorizer.fit_transform(newsgroups_train.data)\n>>> y_train = newsgroups_train.target\n\n>>> X_test = vectorizer.transform(newsgroups_test.data)\n>>> y_test = newsgroups_test.target\n\n>>> clf = xam.nlp.TopTermsClassifier(n_terms=50)\n>>> score = clf.fit(X_train.toarray(), y_train).score(X_test.toarray(), y_test)\n>>> round(score, 5)\n0.95238\n\n```\n"
},
{
"alpha_fraction": 0.45078298449516296,
"alphanum_fraction": 0.5592840909957886,
"avg_line_length": 22.704545974731445,
"blob_id": "af357133b7f705ac97a26f64cb35752d0eee1390",
"content_id": "191141ac0c77db451e3c4c2987f05cf4d5979838",
"detected_licenses": [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 6262,
"license_type": "permissive",
"max_line_length": 440,
"num_lines": 264,
"path": "/docs/preprocessing.md",
"repo_name": "algoding/xam",
"src_encoding": "UTF-8",
"text": "# Preprocessing\n\n## Binning\n\n### Bayesian blocks binning\n\nHeuristically determines the number of bins to use for continuous variables, see this [blog post](https://jakevdp.github.io/blog/2012/09/12/dynamic-programming-in-python/) for details.\n\n```python\n>>> import numpy as np\n>>> from scipy import stats\n>>> import xam\n\n>>> np.random.seed(0)\n>>> x = np.concatenate([\n... stats.cauchy(-5, 1.8).rvs(500),\n... stats.cauchy(-4, 0.8).rvs(2000),\n... stats.cauchy(-1, 0.3).rvs(500),\n... stats.cauchy(2, 0.8).rvs(1000),\n... stats.cauchy(4, 1.5).rvs(500)\n... ])\n>>> x = x[(x > -15) & (x < 15)].reshape(-1, 1)\n>>> binner = xam.preprocessing.BayesianBlocksBinner()\n>>> binner.fit_transform(X=x)[:10]\narray([[ 6],\n [ 8],\n [ 7],\n [ 6],\n [ 5],\n [ 7],\n [ 5],\n [13],\n [20],\n [ 4]])\n\n```\n\n### Equal frequency binning\n\nTransformer that bins continuous data into `n_bins` of equal frequency.\n\n```python\n>>> import numpy as np\n>>> import xam\n\n>>> np.random.seed(42)\n>>> mu, sigma = 0, 0.1\n>>> x = np.random.normal(mu, sigma, 10).reshape(-1, 1)\n\n>>> binner = xam.preprocessing.EqualFrequencyBinner(n_bins=5)\n>>> binner.fit_transform(X=x)\narray([[2],\n [1],\n [3],\n [4],\n [0],\n [1],\n [4],\n [3],\n [0],\n [2]])\n\n```\n\n### Equal width binning\n\nTransformer that bins continuous data into `n_bins` of equal width.\n\n```python\n>>> import numpy as np\n>>> import xam\n\n>>> np.random.seed(42)\n>>> mu, sigma = 0, 0.1\n>>> x = np.random.normal(mu, sigma, 10).reshape(-1, 1)\n\n>>> binner = xam.preprocessing.EqualWidthBinner(n_bins=5)\n>>> binner.fit_transform(X=x)\narray([[2],\n [0],\n [2],\n [4],\n [0],\n [0],\n [5],\n [3],\n [0],\n [2]])\n\n```\n\n### Minimum Description Length Principle (MDLP) binning\n\n```python\n>>> from sklearn import datasets\n>>> import xam\n\n>>> iris = datasets.load_iris()\n>>> X, y = iris.data[:, 1:3], iris.target\n\n>>> binner = xam.preprocessing.MDLPBinner()\n>>> binner.fit_transform(X, y)[:10]\narray([[2, 0],\n [1, 0],\n [1, 0],\n [1, 0],\n [2, 0],\n [2, 0],\n [2, 0],\n [2, 0],\n [0, 0],\n [1, 0]])\n\n```\n\n## Combining features\n\n```python\n>>> import pandas as pd\n>>> import xam\n\n>>> df = pd.DataFrame({\n... 'col_a': ['a', 'b', 'c'],\n... 'col_b': ['d', 'e', 'f'],\n... 'col_c': ['g', 'h', 'i'],\n... })\n\n>>> xam.preprocessing.FeatureCombiner(separator='+', orders=[2, 3]).fit_transform(df)\n col_a col_b col_c col_a+col_b col_a+col_c col_b+col_c col_a+col_b+col_c\n0 a d g a+d a+g d+g a+d+g\n1 b e h b+e b+h e+h b+e+h\n2 c f i c+f c+i f+i c+f+i\n\n```\n\n## Cyclic features\n\nDay of week, hours, minutes, are cyclic ordinal features; cosine and sine transforms should be used to express the cycle. See [this StackEchange discussion](https://datascience.stackexchange.com/questions/5990/what-is-a-good-way-to-transform-cyclic-ordinal-attributes). This transformer returns an array with twice as many columns as the input array; the first columns are the cosine transforms and the last columns are the sine transforms.\n\n```python\n>>> import numpy as np\n>>> import xam\n\n>>> times = np.array([\n... np.linspace(0, 23, 4),\n... np.linspace(0, 59, 4),\n... ]).T\n\n>>> trans = xam.preprocessing.CycleTransformer()\n>>> trans.fit_transform(times)\narray([[ 1. , 1. , 0. , 0. ],\n [-0.42261826, -0.46947156, 0.90630779, 0.88294759],\n [-0.64278761, -0.5591929 , -0.76604444, -0.82903757],\n [ 0.96592583, 0.9945219 , -0.25881905, -0.10452846]])\n\n```\n\n## Groupby transformer\n\n```python\n>>> from sklearn import preprocessing\n>>> import xam\n\n>>> df = pd.DataFrame({\n... 'a': [1, None, 3, 3, 3, 3],\n... 'b': [4, None, 5, 5, None, 7],\n... 'c': [1, 1, 1, 2, 2, 2],\n... })\n\n>>> df\n a b c\n0 1.0 4.0 1\n1 NaN NaN 1\n2 3.0 5.0 1\n3 3.0 5.0 2\n4 3.0 NaN 2\n5 3.0 7.0 2\n\n>>> imp = xam.preprocessing.GroupbyTransformer(\n... base_transformer=preprocessing.Imputer(strategy='mean'),\n... by='c'\n... )\n\n>>> imp.fit_transform(df)\n a b c\n0 1.0 4.0 1\n1 2.0 4.5 1\n2 3.0 5.0 1\n3 3.0 5.0 2\n4 3.0 6.0 2\n5 3.0 7.0 2\n\n```\n\n## Likelihood encoding\n\nBased on [this paper](http://delivery.acm.org/10.1145/510000/507538/p27-micci-barreca.pdf?ip=195.220.58.237&id=507538&acc=ACTIVE%20SERVICE&key=7EBF6E77E86B478F%2EDD49F42520D8214D%2E4D4702B0C3E38B35%2E4D4702B0C3E38B35&CFID=815531231&CFTOKEN=41271394&__acm__=1507647876_89ea73f9273f9f852423613baaa9f9c8).\n\n\n```python\n>>> import pandas as pd\n>>> import xam\n\n>>> X = pd.DataFrame({'x_0': ['a'] * 5 + ['b'] * 5, 'x_1': ['a'] * 9 + ['b'] * 1})\n>>> y = pd.Series([1, 1, 1, 1, 0, 1, 0, 0, 0, 0])\n\n>>> be = xam.preprocessing.LikelihoodEncoder(columns=['x_0', 'x_1'], min_samples=3, smoothing=2)\n>>> be.fit_transform(X, y)\n x_0 x_1\n0 0.719318 0.542382\n1 0.719318 0.542382\n2 0.719318 0.542382\n3 0.719318 0.542382\n4 0.719318 0.542382\n5 0.280682 0.542382\n6 0.280682 0.542382\n7 0.280682 0.542382\n8 0.280682 0.542382\n9 0.280682 0.203072\n\n```\n\n## Resampling\n\nSee this [blog post](https://maxhalford.github.io/subsampling-1/).\n\n```python\n>>> import numpy as np\n>>> import pandas as pd\n>>> import scipy as sp\n>>> import xam\n\n>>> np.random.seed(0)\n\n>>> train = pd.DataFrame({\n... 'x': np.random.beta(1.5, 2, size=1000),\n... 'y': np.random.randint(0, 2, 1000)\n... })\n\n>>> test = pd.DataFrame({\n... 'x': np.random.beta(2, 1.5, size=1000),\n... 'y': np.random.randint(0, 2, 1000)\n... })\n\n# Calculate Kullback–Leibler divergence between the train and the test data\n>>> str(sp.stats.entropy(\n... np.histogram(train['x'], bins=30)[0],\n... np.histogram(test['x'], bins=30)[0]\n... ))[:5]\n'0.252'\n\n>>> resampler = xam.preprocessing.DistributionResampler(column='x', sample_frac=0.5, seed=0)\n>>> resampler.fit(test)\n\n>>> sample = resampler.transform(train)\n\n# The Kullback–Leibler divergence between sample and test is now lower\n>>> str(sp.stats.entropy(\n... np.histogram(sample['x'], bins=30)[0],\n... np.histogram(test['x'], bins=30)[0]\n... ))[:5]\n'0.073'\n\n```\n"
},
{
"alpha_fraction": 0.8571428656578064,
"alphanum_fraction": 0.8571428656578064,
"avg_line_length": 41,
"blob_id": "86df7c71c2ae91d0edcf66cc7eaf62f04828e313",
"content_id": "f37f00c49e6a31be0f907aa593e7bba7a93eee96",
"detected_licenses": [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 42,
"license_type": "permissive",
"max_line_length": 41,
"num_lines": 1,
"path": "/xam/nlp/__init__.py",
"repo_name": "algoding/xam",
"src_encoding": "UTF-8",
"text": "from .top_terms import TopTermsClassifier\n"
},
{
"alpha_fraction": 0.5935631990432739,
"alphanum_fraction": 0.6032183766365051,
"avg_line_length": 33.52381134033203,
"blob_id": "a36a2e1d457a16823437ef7fd2d2a11cfe3309d0",
"content_id": "c0b556d3a6b2931b4ada717f515bb695e7202f73",
"detected_licenses": [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2175,
"license_type": "permissive",
"max_line_length": 117,
"num_lines": 63,
"path": "/xam/preprocessing/likelihood_encoding.py",
"repo_name": "algoding/xam",
"src_encoding": "UTF-8",
"text": "import numpy as np\nimport pandas as pd\nfrom sklearn.base import BaseEstimator\nfrom sklearn.base import TransformerMixin\n\n\nclass LikelihoodEncoder(BaseEstimator, TransformerMixin):\n\n \"\"\"\n\n https://kaggle2.blob.core.windows.net/forum-message-attachments/225952/7441/high%20cardinality%20categoricals.pdf\n\n Args:\n columns (list of strs): Columns to encode.\n min_samples (int): Minimum samples.\n smoothing (float): Smoothing parameter.\n drop_columns (bool): Drop encoded columns or not.\n \"\"\"\n\n def __init__(self, columns=None, min_samples=50, smoothing=5, drop_columns=True):\n self.columns = columns\n self.min_samples = min_samples\n self.smoothing = smoothing\n self.drop_columns = drop_columns\n\n def fit(self, X, y=None, **fit_params):\n\n if not isinstance(X, pd.DataFrame):\n raise ValueError('X has to be a pandas.DataFrame')\n\n if not isinstance(y, pd.Series):\n raise ValueError('y has to be a pandas.Series')\n\n dtypes = X.dtypes\n if self.columns is None:\n self.columns = [col for col in X.columns if dtypes[col] in ('object', 'category')]\n\n # Compute posterior probabilities for each feature\n features = pd.concat((X[self.columns], y.rename('y')), axis='columns')\n self.priors_ = {}\n self.posteriors_ = {}\n for col in self.columns:\n agg = features.groupby(col)['y'].agg(['count', 'mean'])\n counts = agg['count']\n means = agg['mean']\n self.priors_[col] = means.mean()\n p = 1 / (1 + np.exp(-(counts - self.min_samples) / self.smoothing))\n self.posteriors_[col] = p * means + (1 - p) * self.priors_[col]\n\n return self\n\n def transform(self, X, y=None):\n\n if not isinstance(X, pd.DataFrame):\n raise ValueError('X has to be a pandas.DataFrame')\n\n for col in self.columns:\n prior = self.priors_[col]\n posteriors = self.posteriors_[col]\n new_col = col if self.drop_columns else col + '_be'\n X[new_col] = X[col].apply(lambda x: posteriors.get(x, prior))\n\n return X\n"
},
{
"alpha_fraction": 0.6733167171478271,
"alphanum_fraction": 0.6807979941368103,
"avg_line_length": 27.64285659790039,
"blob_id": "0cf60a5c6d06af11f39da3f5c27e2312a5dd1906",
"content_id": "54ce4a5a9c60ddfd5916fcd46ea4baf8bd8782d4",
"detected_licenses": [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 401,
"license_type": "permissive",
"max_line_length": 71,
"num_lines": 14,
"path": "/setup.py",
"repo_name": "algoding/xam",
"src_encoding": "UTF-8",
"text": "from setuptools import find_packages\nfrom setuptools import setup\n\nsetup(\n author='Max Halford',\n author_email='[email protected]',\n description='Data science utilities library',\n license='MIT',\n name='xam',\n install_requires=open('requirements/base.txt').read().splitlines(),\n packages=find_packages(exclude=['examples']),\n url='https://github.com/MaxHalford/xam',\n version='0.0.1dev',\n)\n"
},
{
"alpha_fraction": 0.8744186162948608,
"alphanum_fraction": 0.8744186162948608,
"avg_line_length": 46.77777862548828,
"blob_id": "ac2e8f037c16a8a725bb1c29f901eecd862c1297",
"content_id": "9dc2a75396d79c63f70dffc857aacdc3b99dec4a",
"detected_licenses": [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 430,
"license_type": "permissive",
"max_line_length": 57,
"num_lines": 9,
"path": "/xam/preprocessing/__init__.py",
"repo_name": "algoding/xam",
"src_encoding": "UTF-8",
"text": "from .binning.bayesian_blocks import BayesianBlocksBinner\nfrom .binning.equal_frequency import EqualFrequencyBinner\nfrom .binning.equal_width import EqualWidthBinner\nfrom .binning.mdlp import MDLPBinner\nfrom .combinations import FeatureCombiner\nfrom .cycle import CycleTransformer\nfrom .groupby_transformer import GroupbyTransformer\nfrom .likelihood_encoding import LikelihoodEncoder\nfrom .resampling import DistributionResampler\n"
}
] | 7 |
rehmanz/solar-system-discovery | https://github.com/rehmanz/solar-system-discovery | 629610cc83b4a1adc01cca5bf6dec658e590ab95 | 7b20142875b6ea5538794f971cf84b5113fc832a | 849d9a4fbc460361dab638a8663b02860bb055f9 | refs/heads/master | 2016-08-03T01:34:07.786686 | 2014-07-26T06:50:45 | 2014-07-26T06:50:45 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7009872794151306,
"alphanum_fraction": 0.7066290378570557,
"avg_line_length": 58.08333206176758,
"blob_id": "86f3e62ccc2a1772cd223ca9ce95ba9ebe79f93a",
"content_id": "f5326111bbb88dc85daad264fd48f37a48f1132d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 709,
"license_type": "no_license",
"max_line_length": 227,
"num_lines": 12,
"path": "/README.md",
"repo_name": "rehmanz/solar-system-discovery",
"src_encoding": "UTF-8",
"text": "=================================\n Solar System Discovery\n=================================\n\nThe intent of the Solar System Discovery application is to utilize the Celery framework. \n\nEach planet in our solar system, Sun, Mercury, Venus, Earth, Mars, Jupiter, Saturn, Uranus and Naptue, will be a separate task worker. Each planet will provide the information to the application for answering questions such as:\n\n- What is the smallest planet?\n- Which planet has the largest number of moons?\n- Which moon has the shortest orbital period in days and which planet does it belong to?\n- How far is Saturn from Earth? And how many days will it take to get there if our space craft travels at a speed of 2,000 mph?\n"
},
{
"alpha_fraction": 0.5789473652839661,
"alphanum_fraction": 0.5869565010070801,
"avg_line_length": 19.785715103149414,
"blob_id": "748ca9e293893fa521a421296bed7c4f63270bc8",
"content_id": "c2419b50dbdf4ee7a0b75ba3c8fb48d3305a76f0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 874,
"license_type": "no_license",
"max_line_length": 65,
"num_lines": 42,
"path": "/planet.py",
"repo_name": "rehmanz/solar-system-discovery",
"src_encoding": "UTF-8",
"text": "\n'''\nCreated on Jul 25, 2014\n\n@author: zrehman\n'''\nimport unittest\n\n\n\"\"\" Planet Class \"\"\"\nclass Planet(object):\n def __init__(self, mass, atmosphere):\n \"\"\"Generic planet class.\n Args:\n mass: planet mass in kilo grams\n atmosphere: collection of gasses surrounding the planet\n \"\"\"\n self.mass = mass\n self.atmosphere = atmosphere\n \n \n\"\"\" Unit Tests \"\"\"\nclass PlanetUnitTest(unittest.TestCase):\n @classmethod\n def setUpClass(self):\n pass\n \n def test_it(self):\n pass\n \n @classmethod\n def tearDownClass(self):\n pass\n\n\"\"\" Unit Test Runner \"\"\"\ndef PlanetUnitTestRunner():\n tests = ['test_it']\n \n return unittest.TestSuite(map(PlanetUnitTest, tests))\n\nif __name__ == \"__main__\":\n unittest.main(defaultTest='PlanetUnitTestRunner',\n verbosity=2)\n"
}
] | 2 |
Niskarsh/Sedimentation | https://github.com/Niskarsh/Sedimentation | 93808e0176405a512b5d41df966a49934c9521f4 | 1c593c26755743a42acdb66ee7dd47baef205241 | 5204423d3196471a56ce5566f227e68fea20a9b7 | refs/heads/master | 2023-01-20T16:06:45.520416 | 2020-11-24T17:37:35 | 2020-11-24T17:37:35 | 315,682,062 | 2 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.669217586517334,
"alphanum_fraction": 0.7113431692123413,
"avg_line_length": 38.8319091796875,
"blob_id": "4b5794e7e6b713170a0f964121a56e4622986b59",
"content_id": "d56ac7caa0b23510995c7430b8545294adc7d8c9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 13984,
"license_type": "no_license",
"max_line_length": 162,
"num_lines": 351,
"path": "/Project/index.py",
"repo_name": "Niskarsh/Sedimentation",
"src_encoding": "UTF-8",
"text": "from tkinter import *\nfrom tkinter import messagebox\nfrom colour import Color\nimport time as tm\n\n# Initialising main window\nroot = Tk()\nroot.resizable(0, 0)\n\nglobal speedEntry, distanceEntry, materialDensityEntry, mediumDensityEntry, mediumViscosityEntry, time, s_label, d_label, start_button, pause_button, stop_button \n\nspeedEntry, distanceEntry, time, materialDensityEntry, mediumDensityEntry, mediumViscosityEntry, distanceMapParameter = 1, 328.0, 0.0, 0.0, 0.0, 0.0, 1.0\nsizeRange = [0.0, 0.0]\n\nrun=False\n\n# Adding title to main window\nroot.title('MSE659A Python Project')\n\n# Main frame holding everything together\nwindow_frame = LabelFrame(root, borderwidth=3, relief=\"groove\")\n\n# Frame that holds title\ntitle_frame = Frame(window_frame)\ntitle_label = Label(title_frame, text=\"Simulation of Sedimentation technique with varying particle sizes under ideal conditions\")\ntitle_label.pack()\n\n# Frame holding simulation section of window\nsimulation_frame = LabelFrame(window_frame, text=\"Simulation\")\n\n# Selected Parameters\nsp = Label(simulation_frame, text=\"Selected Parameters\")\ns_label = Label(simulation_frame, text=\"Speed : \" + str(speedEntry) + \"x\", width=15, anchor=W)\nd_label = Label(simulation_frame, text=\"Distance Mapped : \" + str(distanceEntry), width=25, anchor=E)\nmt_label = Label(simulation_frame, text=\"Material Density : \" + str(materialDensityEntry), width=25, anchor=W)\nmd_label = Label(simulation_frame, text=\"Medium Density : \" + str(mediumDensityEntry), width=25, anchor=E)\nv_label = Label(simulation_frame, text=\"Medium Viscosity : \" + str(mediumViscosityEntry), width=25, anchor=W)\nsz_label = Label(simulation_frame, text=\"Size range : \" + str(sizeRange[0])+ \"μ to \" + str(sizeRange[len(sizeRange)-1]) + \"μ\", width=25, anchor=E)\ntime_passed = Label(simulation_frame, text=\"Time passed : \" + str(time))\n\ndef drawCanvas(canvas):\n\tglobal m1, m\n\tcanvas.create_rectangle(125, 358, 290, 30, width=3, outline=\"#3c5396\", fill=\"#b8c9fc\")\n\t# m1 = canvas.create_oval(128, 33, 138, 43, fill=\"red\")\n\t# (m1, a, v, reached, x1, y1, x2, y2, fill)\n\t# m = [(m1, 0.0, 0.0, sizeRange[0], False, 128, 33, 138, 43, \"red\")]\n\ncanvas = Canvas(simulation_frame, bg=\"white\", height=360)\ndrawCanvas(canvas)\n\nsp.grid(row=0, column=0, columnspan=2)\ns_label.grid(row=1, column=0, padx=(5, 5), columnspan=1, sticky=W)\nd_label.grid(row=1, column=1, padx=(5, 5), columnspan=1, sticky=E)\nmt_label.grid(row=2, column=0, padx=(5, 5), pady=(5, 0), columnspan=1, sticky=W)\nmd_label.grid(row=2, column=1, padx=(5, 5), pady=(5, 0), columnspan=1, sticky=E)\nv_label.grid(row=3, column=0, padx=(5, 5), pady=(5, 0), columnspan=1, sticky=W)\nsz_label.grid(row=3, column=1, padx=(5, 5), pady=(5, 0), columnspan=1, sticky=E)\ntime_passed.grid(row=4, column=0, padx=5, pady=(5, 0), columnspan=2, sticky=W)\ncanvas.grid(row=5, column=0, rowspan=2, padx=5, pady=(5, 0), columnspan=2, sticky=W+E)\n# Frame holding the section that takes input\ncontrol_frame = LabelFrame(window_frame, text=\"Controls\")\n\n# Speed Frame\ndef setSpeed(speed):\n\tglobal speedEntry\n\tspeedEntry = speed\n\tspeedEntry = speedEntry[:-1]\n\ts_label = Label(simulation_frame, text=\"Speed : \" + str(speedEntry) + \"x\", width=15, anchor=W)\n\ts_label.grid(row=1, column=0, padx=(5, 5), columnspan=1, sticky=W)\n\nspeed_frame = Frame(control_frame)\nspeed_label = Label(speed_frame, text=\"Speed: \")\nspeed = Entry(speed_frame, width=30)\nb_speed = Button(speed_frame, text=\"Set Speed\", command=lambda:setSpeed(speed.get()), state=DISABLED)\n\nspeed.insert(0, \"1x\")\n\nspeed_label.grid(row=0, column=0)\nspeed.grid(row=0, column=1, sticky=E)\nb_speed.grid(row=1, column=1, sticky=E, pady=(5, 0))\n\nspeed_frame.grid(row=0, column=0, padx=10, pady=(10, 5), sticky=E)\n\n# Distance Frame\ndef setMapping(distance):\n\tglobal distanceEntry, distanceMapParameter\n\tdistanceEntry = float(distance)\n\tdistanceMapParameter = 328/distanceEntry\n\td_label = Label(simulation_frame, text=\"Distance Mapped : \" + str(distanceEntry), width=25, anchor=E)\n\td_label.grid(row=1, column=1, padx=(5, 5), columnspan=1, sticky=E)\n\ndistance_frame = Frame(control_frame)\ndistance_label = Label(distance_frame, text=\"Distance to be mapped: \")\ndistance = Entry(distance_frame, width=30)\nb_distance = Button(distance_frame, text=\"Map Distance\", command=lambda:setMapping(distance.get()))\n\ndistance.insert(0, \"Default mapping: 328m to 328px\")\n\ndistance_label.grid(row=0, column=0)\ndistance.grid(row=0, column=1)\nb_distance.grid(row=1, column=1, sticky=E, pady=(5, 0))\n\ndistance_frame.grid(row=1, column=0, padx=10, pady=(5, 10), sticky=E)\n\n# Material Density Frame\ndef setMaterialDensity(density):\n\tglobal materialDensityEntry\n\tmaterialDensityEntry = float(density)\n\tmt_label = Label(simulation_frame, text=\"Material Density : \" + str(materialDensityEntry), width=25, anchor=W)\n\tmt_label.grid(row=2, column=0, padx=(5, 5), pady=(5, 0), columnspan=1, sticky=W)\n\t\nmaterialDensity_frame = Frame(control_frame)\nmaterialDensity_label = Label(materialDensity_frame, text=\"Material Density: \")\nmaterialDensity = Entry(materialDensity_frame, width=30)\nb_materialDensity = Button(materialDensity_frame, text=\"Set Density\", command=lambda:setMaterialDensity(materialDensity.get()))\n\n# materialDensity.insert(0, \"eg: 1x\")\n\nmaterialDensity_label.grid(row=0, column=0)\nmaterialDensity.grid(row=0, column=1)\nb_materialDensity.grid(row=1, column=1, sticky=E, pady=(5, 0))\n\nmaterialDensity_frame.grid(row=2, column=0, padx=10, pady=(5, 10), sticky=E)\n\n# Medium Density Frame\ndef setMediumDensity(density):\n\tglobal mediumDensityEntry\n\tmediumDensityEntry = float(density)\n\tmd_label = Label(simulation_frame, text=\"Medium Density : \" + str(mediumDensityEntry), width=25, anchor=E)\n\tmd_label.grid(row=2, column=1, padx=(5, 5), pady=(5, 0), columnspan=1, sticky=E)\n\nmediumDensity_frame = Frame(control_frame)\nmediumDensity_label = Label(mediumDensity_frame, text=\"Medium Density: \")\nmediumDensity = Entry(mediumDensity_frame, width=30)\nb_mediumDensity = Button(mediumDensity_frame, text=\"Set Density\", command=lambda:setMediumDensity(mediumDensity.get()))\n\n# mediumDensity.insert(0, \"eg: 1x\")\n\nmediumDensity_label.grid(row=0, column=0)\nmediumDensity.grid(row=0, column=1)\nb_mediumDensity.grid(row=1, column=1, sticky=E, pady=(5, 0))\n\nmediumDensity_frame.grid(row=3, column=0, padx=10, pady=(5, 10), sticky=E)\n\n# Medium Viscosity Frame\ndef setMediumViscosity(viscosity):\n\tglobal mediumViscosityEntry\n\tmediumViscosityEntry = float(viscosity)\n\tv_label = Label(simulation_frame, text=\"Medium Viscosity : \" + str(mediumViscosityEntry), width=25, anchor=W)\n\tv_label.grid(row=3, column=0, padx=(5, 5), pady=(5, 0), columnspan=1, sticky=W)\n\t\nmediumViscosity_frame = Frame(control_frame)\nmediumViscosity_label = Label(mediumViscosity_frame, text=\"Medium Viscosity: \")\nmediumViscosity = Entry(mediumViscosity_frame, width=30)\nb_mediumViscosity = Button(mediumViscosity_frame, text=\"Set Viscosity\", command=lambda:setMediumViscosity(mediumViscosity.get()))\n\n# mediumViscosity.insert(0, \"eg: 1x\")\n\nmediumViscosity_label.grid(row=0, column=0)\nmediumViscosity.grid(row=0, column=1)\nb_mediumViscosity.grid(row=1, column=1, sticky=E, pady=(5, 0))\n\nmediumViscosity_frame.grid(row=4, column=0, padx=10, pady=(5, 10), sticky=E)\n\n# Particle size range Frame\ndef setSizeRange(r1, r2):\n\tglobal sizeRange, m, canvas\n\tr1, r2 = float(r1), float(r2)\n\t\n\tblue = Color(\"#fffac7\")\n\tcolors = list(blue.range_to(Color(\"#c75300\"),16))\n\t\n\tsizeRange = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n\tm = [0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]\n\tfor i in range(16):\n\t\tsizeRange[i] = r1 + (i)*(r2-r1)/15\n\t\tml = canvas.create_oval(128+10*i, 33, 138+10*i, 43, fill=colors[i].hex)\n\t\tm[i] = (ml, 0.0, 0.0, sizeRange[i], False, False, 128+10*i, 33, 138+10*i, 43, 43, colors[i].hex)\n\n\tprint(sizeRange)\n\t# for index, (shape, a, v, size, reached, x1, y1, x2, y2, fill) in enumerate(m):\n\t# \tm[index] = (shape, a, v, sizeRange[0], reached, x1, y1, x2, y2, fill)\n\tsz_label = Label(simulation_frame, text=\"Size range : \" + str(sizeRange[0])+ \"m to \" + str(sizeRange[len(sizeRange)-1]) + \"m\", width=25, anchor=E)\n\tsz_label.grid(row=3, column=1, padx=(5, 5), pady=(5, 0), columnspan=1, sticky=E)\n\t\nsizeRange_frame = Frame(control_frame)\nsizeRange_label = Label(sizeRange_frame, text=\"Size Range: \")\nsizeRange_label_2 = Label(sizeRange_frame, text=\" : \")\nsizeRangeInitial = Entry(sizeRange_frame, width=10)\nsizeRangeFinal = Entry(sizeRange_frame, width=10)\nb_sizeRange = Button(sizeRange_frame, text=\"Set Size Range\", command=lambda:setSizeRange(sizeRangeInitial.get(), sizeRangeFinal.get()))\n\n# mediumViscosity.insert(0, \"eg: 1x\")\n\nsizeRange_label.grid(row=0, column=0)\nsizeRangeInitial.grid(row=0, column=1, sticky=E)\nsizeRange_label_2.grid(row=0, column=2, sticky=E)\nsizeRangeFinal.grid(row=0, column=3, sticky=E)\nb_sizeRange.grid(row=1, column=0, columnspan=4, sticky=E, pady=(5, 0))\n\nsizeRange_frame.grid(row=5, column=0, padx=10, pady=(5, 10), sticky=E)\n\n# Buttons\n\ncontrol_buttons_frame = Frame(control_frame)\n\n\ndef allStopped():\n\tglobal m\n\tstop = True\n\tfor index, (shape, a, v, size, reached, stopped, x1, y1, x2, y2, y, fill) in enumerate(m):\n\t\tif not(stopped):\n\t\t\tstop = False\n\n\treturn stop\n\n\ndef calculateNextMove():\n\tglobal time, time_passed, canvas, m1, m, mediumDensityEntry, materialDensityEntry, mediumViscosityEntry, distanceMapParameter\n\t# m = [(0, 0, False, 128, 33, 138, 43, \"red\")]\n\tincrement = 0\n\tif allStopped():\n\t\tpause()\n\t\treturn\n\n\tfor index, (shape, a, v, size, reached, stopped, x1, y1, x2, y2, y, fill) in enumerate(m):\n\t\tif reached:\n\t\t\tincrement = v*.1*distanceMapParameter\n\t\t\tif (y + increment > 358):\n\t\t\t\tincrement = 358 - y\n\t\t\t\ta = 0\n\t\t\t\tv = 0\n\t\t\t\tstopped = True\n\t\t\tm[index] = (shape, a, v, size, reached, stopped, x1, y1, x2, y2, y+increment, fill)\t\n\t\t\tcanvas.move(shape, 0, increment)\n\t\t\tprint(\"acc \"+str(a)+\" vel \"+ str(v))\n\t\telse:\n\t\t\ta = 9.8 - ((9.8*mediumDensityEntry)/materialDensityEntry) - ((18*v*mediumViscosityEntry)/(materialDensityEntry*size*size))\n\t\t\tif a>0:\n\t\t\t\tv = v + a*.1\n\t\t\t\tincrement = v*.1*distanceMapParameter\n\t\t\t\tif (y + increment > 358):\n\t\t\t\t\tincrement = 358 - y\n\t\t\t\t\ta = 0\n\t\t\t\t\tv = 0\n\t\t\t\t\tstopped = True\n\t\t\t\tm[index] = (shape, a, v, size, reached, stopped, x1, y1, x2, y2, y+increment, fill)\n\t\t\t\tcanvas.move(shape, 0, increment)\n\t\t\t\tprint(\"acc \"+str(a)+\" vel \"+ str(v))\n\t\t\telse:\n\t\t\t\tincrement = v*.1*distanceMapParameter\n\t\t\t\tif (y + increment > 358):\n\t\t\t\t\tincrement = 358 - y\n\t\t\t\t\ta = 0\n\t\t\t\t\tv = 0\n\t\t\t\t\tstopped = True\n\t\t\t\tm[index] = (shape, a, v, size, True, stopped, x1, y1, x2, y2, y+increment, fill)\n\t\t\t\tcanvas.move(shape, 0, increment)\n\t\t\t\tprint(\"Reached \"+str(reached)+ \" vel \"+ str(v))\n\n\ndef startSimulation():\n\troot.update()\n\tglobal run, time, time_passed, canvas, m1\n\trun=True\n\twhile(run):\n\t\ttime = time + .1\n\t\tcalculateNextMove()\n\t\t# canvas.move(m1, 0, 1)\n\t\tt = str(time)\n\t\ttime_passed.grid_forget()\n\t\ttime_passed = Label(simulation_frame, text=\"Time passed : \" + str(t[0:t.index(\".\")+1]+t[t.index(\".\")+1:t.index(\".\")+2]))\n\t\ttime_passed.grid(row=4, column=0, padx=5, pady=(5, 0), columnspan=2, sticky=W)\n\t\troot.update()\n\t\ttm.sleep(.1)\n\n\n\ndef start():\n\tglobal start_button, materialDensityEntry, mediumDensityEntry, mediumViscosityEntry, sizeRange, distanceEntry\n\t# Checks all entries are received or not\t \n\tif not(distanceEntry and materialDensityEntry and mediumDensityEntry and mediumViscosityEntry and sizeRange[0] and sizeRange[1]):\n\t\tmessagebox.showerror(\"Empty Entry\", \"Please fill all entries and press corresponding set button. Do cross check in Selected Parameters section on the left\")\n\t\treturn\n\n\tstart_button.grid_forget()\n\tstart_button = Button(control_buttons_frame, text=\"Start\", command=start, state=DISABLED)\n\tpause_button = Button(control_buttons_frame, text=\"Pause\", command=pause, state=NORMAL)\n\tstop_button = Button(control_buttons_frame, text=\"Stop\", command=stop, state=NORMAL)\n\t\n\tstart_button.grid(row=0, column=0)\n\tpause_button.grid(row=0, column=1)\n\tstop_button.grid(row=0, column=2)\n\t\n\tstartSimulation()\n\ndef pause():\n\tglobal run, start_button\n\tstart_button.grid_forget()\n\tstart_button = Button(control_buttons_frame, text=\"Resume\", command=start, state=NORMAL)\n\tpause_button = Button(control_buttons_frame, text=\"Pause\", command=pause, state=DISABLED)\n\tstop_button = Button(control_buttons_frame, text=\"Stop\", command=stop, state=NORMAL)\n\t\n\tstart_button.grid(row=0, column=0)\n\tpause_button.grid(row=0, column=1)\n\tstop_button.grid(row=0, column=2)\n\trun=False\n\ndef stop():\n\tglobal run, time, start_button, time_passed, canvas\n\tstart_button.grid_forget()\n\tstart_button = Button(control_buttons_frame, text=\"Start\", command=start, state=NORMAL)\n\tpause_button = Button(control_buttons_frame, text=\"Pause\", command=pause, state=DISABLED)\n\tstop_button = Button(control_buttons_frame, text=\"Stop\", command=stop, state=DISABLED)\n\t\n\tstart_button.grid(row=0, column=0)\n\tpause_button.grid(row=0, column=1)\n\tstop_button.grid(row=0, column=2)\n\trun=False\n\ttime=0\n\ttime_passed.grid_forget()\n\ttime_passed = Label(simulation_frame, text=\"Time passed : \" + str(time))\n\ttime_passed.grid(row=4, column=0, padx=5, pady=(5, 0), columnspan=2, sticky=W)\n\n\tcanvas.grid_forget()\n\tcanvas = Canvas(simulation_frame, bg=\"white\", height=360)\n\tdrawCanvas(canvas)\n\tcanvas.grid(row=5, column=0, padx=5, pady=(5, 0), columnspan=2, sticky=W+E)\n\nstart_button = Button(control_buttons_frame, text=\"Start\", state=NORMAL, command=start)\npause_button = Button(control_buttons_frame, text=\"Pause\", state=DISABLED, command=pause)\nstop_button = Button(control_buttons_frame, text=\"Stop\", state=DISABLED, command=stop)\n\nstart_button.grid(row=0, column=0)\npause_button.grid(row=0, column=1)\nstop_button.grid(row=0, column=2)\n\ncontrol_buttons_frame.grid(row=6, column=0, padx=10, pady=(5, 10))\n\n\n\n# Packing component frames in window\ntitle_frame.grid(row=0, column=0, columnspan=2, pady=(10, 5))\nsimulation_frame.grid(row=1, column=0, padx=(10, 5), pady=(5, 10), sticky=N+S)\ncontrol_frame.grid(row=1, column=1, padx=(5, 10), pady=(5, 10))\n\n# Packing main frame in window\nwindow_frame.pack(padx=5, pady=5)\n\n# Starting infinite loop\nroot.mainloop()\n\n"
},
{
"alpha_fraction": 0.8039215803146362,
"alphanum_fraction": 0.8235294222831726,
"avg_line_length": 24.5,
"blob_id": "458dc797cce796bbff96726427a49de7ee3d58c3",
"content_id": "70bfb504744b893285083cee672ebd438caf32ec",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Shell",
"length_bytes": 102,
"license_type": "no_license",
"max_line_length": 31,
"num_lines": 4,
"path": "/Project/install_dependencies.sh",
"repo_name": "Niskarsh/Sedimentation",
"src_encoding": "UTF-8",
"text": "sudo apt-get install python3-tk\npip3 install colour\nsudo apt-get install python-tk\npip install colour\n"
},
{
"alpha_fraction": 0.7681564092636108,
"alphanum_fraction": 0.7681564092636108,
"avg_line_length": 43.75,
"blob_id": "889c8fe59886fa23fb4ff312a6645a0b6f190d29",
"content_id": "12b380924aa49f6c2d504cd9b110e262e6c98af8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 358,
"license_type": "no_license",
"max_line_length": 157,
"num_lines": 8,
"path": "/Project/README.md",
"repo_name": "Niskarsh/Sedimentation",
"src_encoding": "UTF-8",
"text": "# Instructions to run script\n- Run ```sh install_dependencies.sh``` script to install dependencies for script\n- Run ```sh start.sh``` script to start python script\n\n# Dependencies\nIf there is some other way to install required dependencies (or above mentioned ways are not working), here are list of dependencies needed to run the script\n- tkinter\n- colour\n"
}
] | 3 |
KurutsuKaren/ALAuto | https://github.com/KurutsuKaren/ALAuto | 64000e862886bab21cb92f419d3a539b5d0449f4 | 7b2fb5e504d650cb776f2adf80b2c7fb987e175e | a96cbe81a13bf77d99a4e161e975c35a40e80182 | refs/heads/master | 2020-08-10T05:37:06.179240 | 2019-11-07T20:53:24 | 2019-11-07T20:53:24 | 214,270,744 | 0 | 0 | null | 2019-10-10T19:40:45 | 2019-10-08T23:37:40 | 2019-10-08T23:37:38 | null | [
{
"alpha_fraction": 0.46853145956993103,
"alphanum_fraction": 0.5213675498962402,
"avg_line_length": 25.102041244506836,
"blob_id": "573dcf01638463f118e01e2e4b785739c24e70f8",
"content_id": "ef474857ab51949015428adc37bec0eb2925bcf3",
"detected_licenses": [
"WTFPL"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1287,
"license_type": "permissive",
"max_line_length": 126,
"num_lines": 49,
"path": "/modules/drop.py",
"repo_name": "KurutsuKaren/ALAuto",
"src_encoding": "UTF-8",
"text": "'''\nimport json\n\ndict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}\n\njson = json.dumps(dict)\nf = open(\"dict.json\",\"w\")\nf.write(json)\nf.close()\n'''\nfrom util.utils import Utils\nfrom dotenv import load_dotenv\nload_dotenv()\nimport os\nfrom pymongo import MongoClient\n\nclass DropManager(object):\n\n pool = [5, 6, 11, 14, 15, 16, 17, 19, 43, 44, 52, 53, 72, 75, 76, 86, 87, 91, 101, 102, 167, 224, 225, 236, 238, 239, 240]\n drops = []\n\n @staticmethod\n def find_droped():\n for p in DropManager.pool:\n if Utils.find(\"ships/\"+str(p)):\n DropManager.drops.append(p)\n print(DropManager.drops)\n DropManager.send_drop(p)\n return p\n\n return -1\n\n @staticmethod\n def send_drop(p):\n client = MongoClient(os.getenv('MONGODB_URI'))\n collection = client['AL']['droprates']\n \n dropinfo = {\n 'map': 34,\n 'shipid': p\n }\n doc = collection.find_one(dropinfo)\n if doc:\n count = doc['count']+1\n values = { '$set': { 'count': count } }\n collection.update_one(dropinfo, values)\n else:\n values = { 'map': 34, 'shipid': p, 'count': 1 }\n collection.insert_one(values)\n "
}
] | 1 |
njpinton/sv_deploy | https://github.com/njpinton/sv_deploy | 3dde8157d90459410a6cf02e34da7de506df2e5a | 9e95428a6b4732f67fa42c45ea7a926164a46879 | e4745950d1dfbecd77e45bfa448b2ab60f9dce39 | refs/heads/master | 2020-04-19T15:58:26.644712 | 2019-01-30T06:55:13 | 2019-01-30T06:55:13 | 168,290,209 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6618993282318115,
"alphanum_fraction": 0.6630434989929199,
"avg_line_length": 29.66666603088379,
"blob_id": "d153059a874cc7be1b4a05453575da55180da239",
"content_id": "b2878dda9eb54e83dbacd7319b401ad30ab4e244",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1748,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 57,
"path": "/voice_capture_verification.py",
"repo_name": "njpinton/sv_deploy",
"src_encoding": "UTF-8",
"text": "import librosa\nimport sounddevice as sd\nimport os\nfrom configuration import get_config\nimport numpy as np\nimport tensorflow as tf\nfrom utils_deployment import *\nimport sys\nimport pandas as pd\nfrom datetime import datetime\n\nconfig = get_config()\n\ndef main():\n print(\"Who are you?\")\n name = input()\n print(\"Hi %s, Are you ready? (Press enter to continue. Records immediately)\" %name)\n print(\"The quick brown fox jumps over the lazy dog.\")\n\n ready = input()\n duration = config.duration\n print(\"Recording . . . (Plays immediately after recording)\")\n recording = sd.rec(int(duration * config.sr), samplerate=config.sr, channels=1)\n sd.wait()\n recording = np.reshape(recording,duration*config.sr)\n print(\"Done Recording.\")\n\n print(\"Playing recording. . .\")\n sd.play(recording,config.sr)\n sd.wait()\n print(\"Done.\")\n\n write_wav(name,recording,config.sr,enroll=False)\n write_npy(name,recording)\n # enroll_path = os.path.join(\"enroll_voice\",name)\n # create_folder(enroll_path)\n print(\"shape of recording array: \",recording.shape)\n utterances_spec = preprocess(recording)\n try:\n verif,score = verify(utterances_spec,name)\n except Exception as e:\n print(\"Please repeat verification process.\")\n exit()\n\n \n docname = 'verification.csv'\n if not os.path.isfile(docname):\n pd.DataFrame(columns=['claimant','accept/reject','score','date','time']).to_csv(docname,index=False)\n \n df = pd.read_csv(docname,index_col=0)\n now = datetime.now()\n\n df.append({'claimant':name,'accept/reject':verif,'score':score,'date':now.date(),'time':now.time(),\n },ignore_index=True).to_csv(docname,index=False)\n\nif __name__ == '__main__':\n main()\n"
},
{
"alpha_fraction": 0.7767489552497864,
"alphanum_fraction": 0.7788065671920776,
"avg_line_length": 22.707317352294922,
"blob_id": "75697545264118254ddfa519e2e5df67e9b8402a",
"content_id": "a12d775d62ca2655ab83cd130bf0653a3ec70927",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 972,
"license_type": "no_license",
"max_line_length": 91,
"num_lines": 41,
"path": "/README.md",
"repo_name": "njpinton/sv_deploy",
"src_encoding": "UTF-8",
"text": "# Speaker Verification Deployment \n\nInstall packages:\n\n`$ pip install -r requirements.txt`\n\nIt has two main functions:\n- enroll voice model of speaker\n- verify the speaker after enrollment\n\nTo enroll user:\n\n`$ python voice_capture_enrollment.py`\n\nIt will ask for a name, input name.\nIt will produce a prompt to ready the user for speaking.\nAfter pressing enter, it will record for 5 seconds.\n\nIf speaker is already enrolled, you can choose to overwrite old data or record a new one.\n\nWait until enrollment is finished.\n\n\nTo verify user:\n\n`$ python voice_capture_verification.py`\n\nInput name of speaker.\nPress enter after the prompt.\nRecord voice for 5 seconds.\nWait for verification.\n\n\nEnrollment of user will save the speaker's:\n- voice in the enroll_voice folder\n- numpy array representation in enroll_npy folder\n- model representation in MODEL folder\n\nA csv file is generated where all names of speaker and data/time of enrollment is recorded.\n\nSame with verification.\n"
},
{
"alpha_fraction": 0.6451454162597656,
"alphanum_fraction": 0.6461310982704163,
"avg_line_length": 28.420289993286133,
"blob_id": "d58603bee453544ad4863381a184a7f6ff1432e5",
"content_id": "8f6d8a3da2ff37f8f50e8f75339c2bc73b4e90cb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2029,
"license_type": "no_license",
"max_line_length": 92,
"num_lines": 69,
"path": "/voice_capture_enrollment.py",
"repo_name": "njpinton/sv_deploy",
"src_encoding": "UTF-8",
"text": "import librosa\nimport sounddevice as sd\nimport os\nfrom configuration import get_config\nimport numpy as np\nimport tensorflow as tf\nimport sys\nfrom utils_deployment import *\nimport tables\nimport pandas as pd\nfrom datetime import datetime\n\n\nconfig = get_config()\n\ndef main():\n \n print(\"Who are you?\")\n name = input()\n\n\n user_exist_path=os.path.join(\"MODEL/{}.npy\".format(name))\n if os.path.isfile(user_exist_path):\n print(\"User with the same name already enrolled. Do you want to continue?\")\n key = input()\n\n if str2bool(key) == False:\n sys.exit(\"Thank you for patronizing us.\")\n \n print(\"Hi %s, Are you ready? (Press enter to continue. Records immediately)\" %name)\n print(\"The quick brown fox jumps over the lazy dog.\")\n ready = input()\n\n print(\"Recording . . . (Plays immediately after recording)\")\n recording = sd.rec(int(config.duration * config.sr), samplerate=config.sr, channels=1)\n sd.wait()\n recording = np.reshape(recording,config.duration*config.sr)\n print(\"Done Recording.\")\n \n \n write_wav(name,recording,config.sr)\n write_npy(name,recording)\n \n print(\"Playing recording. . .\")\n sd.play(recording,config.sr)\n sd.wait()\n print(\"Done playing.\")\n\n utterances_spec = preprocess(recording)\n try:\n enrolled = enroll(utterances_spec,name)\n except Exception as e:\n print(\"Please repeat enrollment process.\")\n enrolled_voice_path = 'enrolled_voice_models.csv'\n# save_model_to_df(enrolled_voice_path,name,enrolled)\n \n docname = 'enroll.csv'\n if not os.path.isfile(docname):\n print(\"Savefile does not exist. Creating savefile, \", docname)\n pd.DataFrame(columns=['name','date','time']).to_csv(docname,index=False)\n \n df = pd.read_csv(docname)\n now = datetime.now()\n \n df.append({'name':name,'date':now.strftime(\"%Y-%m-%d\"),'time':now.strftime(\"%H:%M:%S\")},\n ignore_index=True).to_csv(docname,index=False)\n\nif __name__ == '__main__': \n main()"
},
{
"alpha_fraction": 0.6057467460632324,
"alphanum_fraction": 0.6160374283790588,
"avg_line_length": 41.63817596435547,
"blob_id": "94b7539bc6be45c14033057bd030026a1eb3c210",
"content_id": "330fe996fff7fd00611c2433eca330af042b4d6a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 14965,
"license_type": "no_license",
"max_line_length": 133,
"num_lines": 351,
"path": "/utils_deployment.py",
"repo_name": "njpinton/sv_deploy",
"src_encoding": "UTF-8",
"text": "import tensorflow as tf\nimport numpy as np\nimport os\nimport librosa\nimport matplotlib.pyplot as plt\nimport random\nfrom configuration import get_config\nfrom sklearn.metrics.pairwise import cosine_similarity\nimport soundfile as sf\nimport itertools\nfrom datetime import datetime\nimport argparse\n\n\nconfig = get_config()\n\n\ndef save_spectrogram_tisv():\n \"\"\" Full preprocess of text independent utterance. The log-mel-spectrogram is saved as numpy file.\n Each partial utterance is splitted by voice detection using DB\n and the first and the last 180 frames from each partial utterance are saved. \n Need : utterance data set (VTCK)\n \"\"\"\n print(\"start text independent utterance feature extraction\")\n os.makedirs(config.train_path, exist_ok=True) # make folder to save train file\n os.makedirs(config.test_path, exist_ok=True) # make folder to save test file\n\n enroll_folder = 'verif_tisv5'\n create_folder(enroll_folder)\n\n utter_min_len = (config.tisv_frame * config.hop + config.window) * config.sr # lower bound of utterance length\n total_speaker_num = len(os.listdir(audio_path))\n train_speaker_num= (total_speaker_num//10)*9 # split total data 90% train and 10% test\n print(\"total speaker number : %d\"%total_speaker_num)\n # print(\"train : %d, test : %d\"%(train_speaker_num, total_speaker_num-train_speaker_num))\n\n labels = []\n for i, folder in enumerate(os.listdir(audio_path)):\n speaker_path = os.path.join(audio_path, folder) # path of each speaker\n print(\"%dth speaker processing...\"%i)\n print(folder)\n utterances_spec = []\n k=0\n for utter_name in os.listdir(speaker_path):\n utter_path = os.path.join(speaker_path, utter_name) # path of each utterance\n utter, sr = librosa.core.load(utter_path, config.sr) # load utterance audio\n intervals = librosa.effects.split(utter, top_db=20) # voice activity detection\n for interval in intervals:\n if (interval[1]-interval[0]) > utter_min_len: # If partial utterance is sufficient long,\n utter_part = utter[interval[0]:interval[1]] # save first and last 180 frames of spectrogram.\n S = librosa.core.stft(y=utter_part, n_fft=config.nfft,\n win_length=int(config.window * sr), hop_length=int(config.hop * sr))\n S = np.abs(S) ** 2\n mel_basis = librosa.filters.mel(sr=config.sr, n_fft=config.nfft, n_mels=40)\n S = np.log10(np.dot(mel_basis, S) + 1e-6) # log mel spectrogram of utterances\n\n utterances_spec.append(S[:, :config.tisv_frame]) # first 180 frames of partial utterance\n utterances_spec.append(S[:, -config.tisv_frame:]) # last 180 frames of partial utterance\n\n labels.append('{} {}'.format(i,folder))\n\n utterances_spec = np.array(utterances_spec)\n print(utterances_spec.shape)\n\n np.save(os.path.join(enroll_folder, \"speaker%d.npy\"%(i)), utterances_spec)\n\n fname = 'labels_verif.txt'\n with open(fname,'w') as f:\n for item in labels:\n f.write(item+'\\n')\n \n\ndef preprocess(utter,top_db=config.top_db):\n \"\"\" returns utterance numpy array of users recording as an input\"\"\"\n utter_min_len = (config.tisv_frame * config.hop + config.window) * config.sr # lower bound of utterance length\n sr = config.sr\n\n utterances_spec = []\n intervals = librosa.effects.split(utter, top_db=top_db)\n \n utter_part = []\n for interval in intervals:\n utter_part = np.append(utter_part,utter[interval[0]:interval[1]])\n \n S = librosa.core.stft(y=utter_part, n_fft=config.nfft,\n win_length=int(config.window * sr), hop_length=int(config.hop * sr))\n S = np.abs(S) ** 2\n mel_basis = librosa.filters.mel(sr=config.sr, n_fft=config.nfft, n_mels=40)\n S = np.log10(np.dot(mel_basis, S) + 1e-6) # log mel spectrogram of utterances\n \n utterances_spec.append(S[:, :config.tisv_frame]) # first 180 frames of partial utterance\n utterances_spec.append(S[:, -config.tisv_frame:]) # last 180 frames of partial utterance\n\n utterances_spec = np.array(utterances_spec)\n print(utterances_spec.shape)\n return utterances_spec\n\ndef create_folder(path):\n \"\"\" creates a directory of the path if the directory does not exist \"\"\"\n if not os.path.exists(path):\n os.makedirs(path)\n\ndef enroll(utters,speaker,path=config.model_path,speaker_model_path = 'MODEL'):\n \"\"\" passes the utterance array of speaker to the network and extract it to a (1,64) feature array \"\"\"\n tf.reset_default_graph()\n\n # draw graph\n enroll = tf.placeholder(shape=[None, config.N*config.M, 40], dtype=tf.float32) # enrollment batch (time x batch x n_mel)\n batch = enroll\n # embedding lstm (3-layer default)\n with tf.variable_scope(\"lstm\"):\n lstm_cells = [tf.contrib.rnn.LSTMCell(num_units=config.hidden, num_proj=config.proj) for i in range(config.num_layer)]\n lstm = tf.contrib.rnn.MultiRNNCell(lstm_cells) # make lstm op and variables\n outputs, _ = tf.nn.dynamic_rnn(cell=lstm, inputs=batch, dtype=tf.float32, time_major=True) # for TI-VS must use dynamic rnn\n embedded = outputs[-1] # the last ouput is the embedded d-vector\n embedded = normalize(embedded)\n\n # enrollment embedded vectors (speaker model)\n enroll_embed = normalize(tf.reduce_mean(tf.reshape(embedded[:config.N*config.M, :], shape= [config.N, config.M, -1]), axis=1)) \n saver = tf.train.Saver(var_list=tf.global_variables())\n\n with tf.Session() as sess:\n tf.global_variables_initializer().run()\n\n # load model\n # print(\"model path :\", path)\n ckpt = tf.train.get_checkpoint_state(checkpoint_dir=os.path.join(path, \"Check_Point\"))\n ckpt_list = ckpt.all_model_checkpoint_paths\n loaded = 0\n for model in ckpt_list:\n if config.model_num == int(model[-1]): # find ckpt file which matches configuration model number\n # print(\"ckpt file is loaded !\", model)\n loaded = 1\n saver.restore(sess, model) # restore variables from selected ckpt file\n break\n\n if loaded == 0:\n raise AssertionError(\"ckpt file does not exist! Check config.model_num or config.model_path.\")\n\n try:\n utter_index = np.random.randint(0, utters.shape[0], config.M) # select M utterances per speaker\n utter_batch = utters[utter_index] # each speakers utterance [M, n_mels, frames] is appended\n utter_batch = np.transpose(utter_batch, axes=(2,0,1)) # transpose [frames, batch, n_mels]\n # print(utter_batch.shape)\n enroll = sess.run(enroll_embed, feed_dict={enroll:utter_batch})\n# print('enroll shape: ',enroll.shape)\n print('Enrolled: ',speaker)\n\n create_folder(speaker_model_path)\n np.save(os.path.join(speaker_model_path,'%s.npy'%speaker),enroll)\n except Exception as e:\n print(e)\n return enroll\n\n\ndef verify(utters,speaker,thres=config.threshold,path=config.model_path,speaker_model_folder = 'MODEL'):\n tf.reset_default_graph()\n # draw graph\n verif = tf.placeholder(shape=[None, config.M, 40], dtype=tf.float32) # verif batch (time x batch x n_mel)\n batch = verif\n # embedding lstm (3-layer default)\n with tf.variable_scope(\"lstm\"):\n lstm_cells = [tf.contrib.rnn.LSTMCell(num_units=config.hidden, num_proj=config.proj) for i in range(config.num_layer)]\n lstm = tf.contrib.rnn.MultiRNNCell(lstm_cells) # make lstm op and variables\n outputs, _ = tf.nn.dynamic_rnn(cell=lstm, inputs=batch, dtype=tf.float32, time_major=True) # for TI-VS must use dynamic rnn\n embedded = outputs[-1] # the last ouput is the embedded d-vector\n embedded = normalize(embedded)\n \n verif_embed = normalize(tf.reduce_mean(tf.reshape(embedded[:config.N*config.M, :], shape= [config.N, config.M, -1]), axis=1)) \n\n saver = tf.train.Saver(var_list=tf.global_variables())\n\n with tf.Session() as sess:\n tf.global_variables_initializer().run()\n\n # load model\n # print(\"model path :\", path)\n ckpt = tf.train.get_checkpoint_state(checkpoint_dir=os.path.join(path, \"Check_Point\"))\n ckpt_list = ckpt.all_model_checkpoint_paths\n loaded = 0\n for model in ckpt_list:\n if config.model_num == int(model[-1]): # find ckpt file which matches configuration model number\n print(\"ckpt file is loaded !\", model)\n\n loaded = 1\n saver.restore(sess, model) # restore variables from selected ckpt file\n break\n\n if loaded == 0:\n raise AssertionError(\"ckpt file does not exist! Check config.model_num or config.model_path.\")\n\n try:\n utter_index = np.random.randint(0, utters.shape[0], config.M) # select M utterances per speaker\n utter_batch = utters[utter_index] # each speakers utterance [M, n_mels, frames] is appended\n utter_batch = np.transpose(utter_batch, axes=(2,0,1)) # transpose [frames, batch, n_mels]\n print(utter_batch.shape)\n verif = sess.run(verif_embed, feed_dict={verif:utter_batch})\n # print('verif shape:',verif.shape)\n\n except Exception as e:\n print(e)\n\n\n for enrolled_speaker in os.listdir(speaker_model_folder):\n # print(enrolled_speaker[:-4])\n if enrolled_speaker[:-4] == speaker:\n speaker_model_path = os.path.join(speaker_model_folder,enrolled_speaker)\n # print(speaker_model_path)\n try:\n score = get_score(verif,speaker_model_path)\n print('confidence: ', str(score*100))\n\n if score > thres:\n print('Speaker verified. You are %s.'%speaker)\n verification = 'accepted'\n else:\n print('Speaker rejected. Please try again.')\n verification = 'rejected'\n except Exception as e:\n print(e)\n return verification, score\n\ndef normalize(x):\n \"\"\" normalize the last dimension vector of the input matrix\n :return: normalized input\n \"\"\"\n return x/tf.sqrt(tf.reduce_sum(x**2, axis=-1, keep_dims=True)+1e-6)\n\n# def get_score(speaker_feat,speaker,path='MODEL/model.npy'):\n# model = np.load(path)\n# # print('model: ', model[[speaker]])\n# score = cosine_similarity(speaker_feat,model[[speaker]])\n# # print('model shape: ', model.shape)\n# return score\n\ndef get_score(speaker_feat,speaker_model_path):\n \"\"\" compare the extracted feature of the speaker to the stored feature array of the speaker\n returns: score/similarity of the two features \n \"\"\"\n model = np.load(speaker_model_path)\n # print('model: ', model[[speaker]])\n score = cosine_similarity(speaker_feat,model)\n # print('model shape: ', model.shape)\n return score\n\ndef write_npy(path,rec,enroll=True):\n if enroll == True:\n enroll_npypath = os.path.join(\"enroll_npy/{}\".format(path))\n enroll_path=os.path.join(\"enroll_voice/{}\".format(path))\n create_folder(enroll_npypath)\n \n i = 0\n for file in os.listdir(enroll_path):\n i+=1\n np.save(os.path.join(enroll_npypath,\"{}{}.npy\".format(path,i)),rec)\n\n if enroll == False:\n verify_npypath = os.path.join(\"verify_npy/{}\".format(path))\n verify_path=os.path.join(\"verify_voice/{}\".format(path))\n create_folder(verify_npypath)\n \n i = 0\n for file in os.listdir(verify_path):\n i+=1\n np.save(os.path.join(verify_npypath,\"{}{}.npy\".format(path,i)),rec)\n \ndef write_wav(path,rec,sr,enroll=True):\n if enroll == True:\n enroll_path = os.path.join(\"enroll_voice/{}\".format(path))\n create_folder(enroll_path)\n i = 0\n for file in os.listdir(enroll_path):\n i += 1\n sf.write(\"{}/{}{}.wav\".format(enroll_path,path,i),rec,sr)\n \n if enroll == False:\n verify_path = os.path.join(\"verify_voice/{}\".format(path))\n create_folder(verify_path)\n i = 0\n for file in os.listdir(verify_path):\n i += 1\n sf.write(\"{}/{}{}.wav\".format(verify_path,path,i),rec,sr)\n\ndef save_model_to_df(enrolled_voice_path,name,enrolled):\n '''\n not yet complete something is wrong with the frame\n '''\n if not os.path.isfile(enrolled_voice_path):\n df = pd.DataFrame(columns=['name','model'])\n df.to_csv(enrolled_voice_path,index=False)\n df = pd.read_csv(enrolled_voice_path)\n print(type(enrolled))\n df.append({'name':name,'model':[np.array(enrolled)]},ignore_index=True).to_csv(enrolled_voice_path,index=False)\n\ndef str2bool(v):\n if v.lower() in ('yes', 'true', 't', 'y', '1'):\n return True\n elif v.lower() in ('no', 'false', 'f', 'n', '0'):\n return False\n else:\n raise argparse.ArgumentTypeError('Boolean value expected.')\n\ndef plot_confusion_matrix(cm, classes,\n normalize=False,\n title='Confusion matrix',\n cmap=plt.cm.Blues):\n \"\"\"\n This function prints and plots the confusion matrix.\n Normalization can be applied by setting `normalize=True`.\n \"\"\"\n if normalize:\n cm = cm.astype('float') / cm.sum(axis=1)[:, np.newaxis]\n print(\"Normalized confusion matrix\")\n else:\n print('Confusion matrix, without normalization')\n\n # print(cm)\n\n plt.imshow(cm, interpolation='nearest', cmap=cmap)\n plt.title(title)\n plt.colorbar()\n tick_marks = np.arange(len(classes))\n plt.xticks(tick_marks, classes, rotation=45)\n plt.yticks(tick_marks, classes)\n\n fmt = '.2f' if normalize else 'd'\n thresh = cm.max() / 2.\n for i, j in itertools.product(range(cm.shape[0]), range(cm.shape[1])):\n plt.text(j, i, format(cm[i, j], fmt),\n horizontalalignment=\"center\",\n color=\"white\" if cm[i, j] > thresh else \"black\")\n\n now = datetime.now()\n\n plt.savefig(\"plots/conf_{}.png\".format(now.strftime(\"%H%M%S\")))\n plt.tight_layout()\n plt.ylabel('True label')\n plt.xlabel('Predicted label')\n\nif __name__ == \"__main__\":\n random_batch()\n w= tf.constant([1], dtype= tf.float32)\n b= tf.constant([0], dtype= tf.float32)\n embedded = tf.constant([[0,1,0],[0,0,1], [0,1,0], [0,1,0], [1,0,0], [1,0,0]], dtype= tf.float32)\n sim_matrix = similarity(embedded,w,b,3,2,3)\n loss1 = loss_cal(sim_matrix, type=\"softmax\",N=3,M=2)\n loss2 = loss_cal(sim_matrix, type=\"contrast\",N=3,M=2)\n with tf.Session() as sess:\n print(sess.run(sim_matrix))\n print(sess.run(loss1))\n print(sess.run(loss2))"
}
] | 4 |
Owenknowsbest/RandomCraft | https://github.com/Owenknowsbest/RandomCraft | 3ebccbf20a3bec73ed3c21798893c30fca7e9a1e | 15045dbef52075c2214c92fd3c1c9c7d8c7d9283 | fa20db79c886a54970b1143b403f37302a2795c7 | refs/heads/master | 2023-03-02T18:32:40.206845 | 2021-02-08T21:47:22 | 2021-02-08T21:47:22 | 337,217,259 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6331058144569397,
"alphanum_fraction": 0.6365187764167786,
"avg_line_length": 35.6875,
"blob_id": "076abbf1c00d1e9c07110ede789f63b3806ce3a3",
"content_id": "c5dc8e63e524b6a13ce1086375ffd0355cd5dbbb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 586,
"license_type": "no_license",
"max_line_length": 136,
"num_lines": 16,
"path": "/randomize.py",
"repo_name": "Owenknowsbest/RandomCraft",
"src_encoding": "UTF-8",
"text": "import os\nimport shutil\nimport random\nfolders = {\"block\",\"colormap\",\"effect\",\"environment\",\"gui\",\"item\",\"map\",\"misc\",\"mob_effect\",\"models/armor\",\"painting\",\"particle\",\"font\"}\ndef randomize(t):\n filelist=os.listdir('textures/'+t)\n for fichier in filelist[:]:\n if not(fichier.endswith(\".png\")):\n filelist.remove(fichier)\n names = filelist\n for file in filelist:\n r = random.randint(0,len(names)-1)\n shutil.copy('textures/'+t+'/'+file,'assets/minecraft/textures/'+t+'/'+names[r])\n names.remove(names[r])\nfor t in folders:\n randomize(t)"
}
] | 1 |
pbarch/18534-Daejeon-Biennale | https://github.com/pbarch/18534-Daejeon-Biennale | 84d912e876ba880d23f7f8768cc8ee5074f75eee | 4c747fe977b8e15d7f45496208f02df1e5d46fd5 | 5fe071faf257402238f998c2bd641c3cfd3ced3c | refs/heads/master | 2018-10-14T02:36:37.854846 | 2018-07-19T17:56:01 | 2018-07-19T17:56:01 | 140,033,421 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.5729894042015076,
"alphanum_fraction": 0.6450682878494263,
"avg_line_length": 43.6779670715332,
"blob_id": "3a07e70b6f7c0c5dec893d8c032f3b0c34bd6d0c",
"content_id": "67ebe7dbdc93f40546fe52239a27aac6267c687c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 13180,
"license_type": "no_license",
"max_line_length": 250,
"num_lines": 295,
"path": "/Archive/Teensy/LuddyNode/Behaviours.h",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "/*\n* Behaviours.h - Library for Behaviour (actuation and sensing)\n* Created By Adam Francey March 27, 2018\n* Philip Beesley Architect Inc. / Living Architecture Systems Group\n*/\n\n#ifndef BEHAVIOURS_H_\n#define BEHAVIOURS_H_\n\n#include \"SMA.h\"\n#include \"DeviceLocator.h\"\n\nclass Behaviours{\n\n public:\n Behaviours(int input_frame_duration);\n ~Behaviours();\n \n int test_node_pin = 13;\n\n // This section is filled in by node.ino\n int my_type;\n int my_index;\n int my_num_pins = 0;\n int my_pins[35] = {0,0,0,0,0,0,0,\n 0,0,0,0,0,0,0,\n 0,0,0,0,0,0,0,\n 0,0,0,0,0,0,0,\n 0,0,0,0,0,0,0};\n int my_pins_types[35] = {-1,-1,-1,-1,-1,-1,-1,\n -1,-1,-1,-1,-1,-1,-1,\n -1,-1,-1,-1,-1,-1,-1,\n -1,-1,-1,-1,-1,-1,-1,\n -1,-1,-1,-1,-1,-1,-1};\n\n \n const static int max_SMA = 12;\n SMA SMA_list[max_SMA] = {SMA(13), SMA(13), SMA(13), SMA(13), SMA(13), SMA(13), SMA(13), SMA(13), SMA(13), SMA(13), SMA(13), SMA(13)};\n void init_all_SMA();\n\n \n\n //uint8_t MAX_PWM_VALUE_FOR_ALL = 190; // AMATRIA MOTH REQUIREMENT\n uint8_t MAX_PWM_VALUE_FOR_ALL = 255;\n uint8_t MAX_PWM_VALUE_FOR_MOTH = 200;\n\n DeviceLocator device_locator;\n\n int frame_duration;\n long current_millis;\n long elapsed_millis;\n\n const static uint8_t max_actuators = 18;\n uint8_t actuator_pins[max_actuators] = {3, 4, 5, 6, 9, 10, 16, 17, 20, 21, 22, 23, 25, 26, 29, 30, 31, 32};\n\n // used in any behaviours that set an actuator\n // each setting behaviour sets up an array\n // like PWM_values[max_pin_number + 1]\n // and sets PWM_values[pin] = value\n // so that the actual actuation takes the max of all setting behaviours\n const static uint8_t max_pin_number = 33;\n\n // behaviours\n // when possible, matches #defined message codes\n const static uint8_t num_behaviours = 12;\n const uint8_t _behaviour_TEST_LED_PIN = 0; // modifier: num_blinks, function: blinks led pin with 100 ms between on and off\n const uint8_t _behaviour_FADE_ACTUATOR_GROUP = 1;\n const uint8_t _behaviour_IR_TRIGGER = 2;\n const uint8_t _behaviour_IR_SAMPLING = 3;\n const uint8_t _behaviour_RANDOM_ACTUATOR = 4;\n const uint8_t _behaviour_LOCAL_IR_REACTION = 5;\n const uint8_t _behaviour_SINE = 6;\n const uint8_t _behaviour_EXCITOR = 7;\n const uint8_t _behaviour_LIGHT_CHAIN = 8;\n const uint8_t _behaviour_LIGHT_CHAIN_BACKGROUND = 9;\n const uint8_t _behaviour_AUTO_LIGHT_CHAIN = 10;\n const uint8_t _behaviour_IR_REACTION_LIGHT_COLUMN = 11;\n\n // behaviour state variables\n bool _behaviour_on[num_behaviours]; // whether on not the behaviour is currently running\n int _framecount[num_behaviours]; // tracks current frame of eah behaviour\n int _behaviour_max_frames[num_behaviours]; // maximum number of frames for each behaviour (may depend on modifiers)\n uint8_t _modifiers[num_behaviours]; // modifiers for each behaviour NOTE: changing to separate state variables for each behaviour\n // only TEST_LED_PIN uses this var\n\n void start_DELAYED_FADE_ACTUATOR_GROUP_one_pin(int wait_time, uint8_t pin, uint8_t end_value, int fade_time);\n void _resume_DELAYED_FADE_ACTUATOR_GROUP_one_pin();\n const static int num_DELAYED_FADE_ACTUATOR_GROUP = 30;\n uint8_t pins_DELAYED_FADE_ACTUATOR_GROUP[num_DELAYED_FADE_ACTUATOR_GROUP] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\n uint8_t end_values_DELAYED_FADE_ACTUATOR_GROUP[num_DELAYED_FADE_ACTUATOR_GROUP] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\n int fade_times_DELAYED_FADE_ACTUATOR_GROUP[num_DELAYED_FADE_ACTUATOR_GROUP] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\n int waiting_frames_DELAYED_FADE_ACTUATOR_GROUP[num_DELAYED_FADE_ACTUATOR_GROUP] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\n\n\n void start_DELAYED_one_pin_SMA(int wait_time, uint8_t pin_index);\n void _resume_DELAYED_one_pin_SMA();\n const static int num_DELAYED_SMA = 30;\n uint8_t pins_DELAYED_SMA[num_DELAYED_SMA] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\n uint8_t end_values_DELAYED_SMA[num_DELAYED_SMA] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\n int fade_times_DELAYED_SMA[num_DELAYED_SMA] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\n int waiting_frames_DELAYED_SMA[num_DELAYED_SMA] = {0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};\n \n\n // Behaviour 0: TEST_LED_PIN\n void start_TEST_LED_PIN(uint8_t num_blinks);\n void _resume_TEST_LED_PIN();\n\n // Behaviour 1: FADE_ACTUATOR_GROUP\n const static int _max_actuators_FADE_ACTUATOR_GROUP = 11; // max data length = 255, 5 bytes per actuator (pin, start, end, time1,time2)\n uint8_t _start_values_FADE_ACTUATOR_GROUP[max_pin_number+1];\n uint8_t _end_values_FADE_ACTUATOR_GROUP[max_pin_number+1];\n uint8_t _fade_times_FADE_ACTUATOR_GROUP[max_pin_number+1];\n uint8_t _num_frames_to_skip_FADE_ACTUATOR_GROUP[max_pin_number+1];\n int _num_total_frames_to_fade_FADE_ACTUATOR_GROUP[max_pin_number+1];\n uint8_t _num_actuators_FADE_ACTUATOR_GROUP;\n uint8_t PWM_values_FADE_ACTUATOR_GROUP[max_pin_number + 1];\n int _current_frame_FADE_ACTUATOR_GROUP[max_pin_number+1];\n uint8_t _previous_end_values_FADE_ACTUATOR_GROUP[max_pin_number+1];\n void start_FADE_ACTUATOR_GROUP(uint8_t pins[], uint8_t end_values[], int fade_times[], uint8_t num_actuators);\n void _resume_FADE_ACTUATOR_GROUP();\n\n // Behaviour 2: IR_TRIGGER\n const static uint8_t max_num_IR_sensors = 3;\n uint8_t my_num_IR_sensors = 0; // filled in by node.ino in set_pinMode function\n uint8_t IR_pins[max_num_IR_sensors] = {A0,A1,A13}; // This is reset in node.ino (in set_pinMode_for_all function)\n int IR_vals[max_num_IR_sensors] = {0,0,0};\n int IR_threshold[3] = {0,0,0}; // default, change with SET_IR_THRESHOLD\n long IR_min_time_between_triggers = 1000; // otherwise, trigger message sent constantly while IR triggered\n bool IR_triggered[max_num_IR_sensors] = {false,false,false};\n long IR_last_trigger_time[max_num_IR_sensors] = {0,0,0};\n void start_IR_TRIGGER(int threshold_value1, int threshold_value2, int threshold_value3);\n void _resume_IR_TRIGGER();\n\n // Behaviour 3: IR_SAMPLING\n // uses much of same variables as IR_TRIGGER\n long IR_sample_interval = 20; // millisconds\n long IR_last_sample_time = 0;\n int IR_sampled_vals[max_num_IR_sensors] = {0,0,0};\n bool IR_new_sample = false; \n void start_IR_SAMPLING(uint8_t on_or_off, int sample_interval);\n void _resume_IR_SAMPLING();\n\n // Behaviour 4: RANDOM_ACTUATOR\n\n // default/settable values\n uint8_t prob_RANDOM_ACTUATOR = 20;\n int ramp_up_time_RANDOM_ACTUATOR = 2000;//500;\n int hold_time_RANDOM_ACTUATOR = 1000;//1000;\n int ramp_down_time_RANDOM_ACTUATOR = 3000;//2000;\n int cooldown_time_RANDOM_ACTUATOR = 5000;\n uint8_t max_brightness_RANDOM_ACTUATOR = 240;\n\n // control vars\n long millis_of_last_attempt_RANDOM_ACTUATOR = millis();\n uint8_t stage_RANDOM_ACTUATOR = 0;\n uint8_t dormant_stage_RANDOM_ACTUATOR = 0;\n uint8_t ramp_up_stage_RANDOM_ACTUATOR = 1;\n uint8_t hold_stage_RANDOM_ACTUATOR = 2;\n uint8_t ramp_down_stage_RANDOM_ACTUATOR = 3;\n uint8_t active_pin_RANDOM_ACTUATOR = 13;\n uint8_t active_pin_type_RANDOM_ACTUATOR = 0;\n long actuation_start_time_RANDOM_ACTUATOR = millis();\n uint8_t PWM_values_RANDOM_ACTUATOR[max_pin_number + 1];\n void start_RANDOM_ACTUATOR(uint8_t prob, int ramp_up_time, int hold_time, int ramp_down_time, int cooldown_time);\n void _resume_RANDOM_ACTUATOR();\n\n // Behaviour 5: LOCAL_IR_REACTION\n\n uint8_t _num_moth_LOCAL_IR_REACTION;;\n uint8_t _pins_moth_LOCAL_IR_REACTION[_max_actuators_FADE_ACTUATOR_GROUP];\n uint8_t _num_RS_LOCAL_IR_REACTION;\n uint8_t _pins_RS_LOCAL_IR_REACTION[_max_actuators_FADE_ACTUATOR_GROUP]; \n uint8_t PWM_values_LOCAL_IR_REACTION[max_pin_number + 1];\n void start_LOCAL_IR_REACTION(uint8_t RS_pins[], uint8_t num_RS, uint8_t moth_pins[], uint8_t num_moth);\n void _resume_LOCAL_IR_REACTION();\n\n // Behaviour 6: SINE\n float _frequencies_SINE[max_pin_number + 1]; // 0 - 255 -> changed to 5*freq/255.0 to get 0 - 5 Hz\n float _amplitudes_SINE[max_pin_number + 1]; // 0 - 255 -> changed to 95.0*amp/255.0 to get 0 to 95.0\n float _phases_SINE[max_pin_number + 1]; // 0 - 255 -> changed to 2*pi*phase/255.0 to get 0 to 2pi\n uint8_t PWM_values_SINE[max_pin_number + 1];\n void start_SINE(uint8_t pins[], uint8_t frequencies[], uint8_t amplitudes[], uint8_t phases[], uint8_t num_actuators);\n void _resume_SINE();\n\n // Behaviour 7: Excitor\n void _resume_excitor();\n int _excitor_pos[3] = {30000,30000,30000};\n int _excitor_radius = 1000;\n int _excitor_force_RS = 255;\n int _excitor_force_moth = 255;\n bool do_excitor = false;\n uint8_t PWM_values_EXCITOR[max_pin_number + 1];\n uint8_t sphere_excitor_RS_pins[6] = {3,4,25,32,9,10};\n uint8_t sphere_excitor_moth_pins[6] = {5,20,6,21,22,23};\n const static int num_acts_ROM_sphere = 12;\n const static int num_coords = 3;\n int my_ROM_actuator_coords[num_acts_ROM_sphere][num_coords] = {{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0},{0,0,0}};\n\n // Behaviour 8: Light Chain\n void start_LIGHT_CHAIN(int act_time, float variance, float chain_width);\n void _resume_LIGHT_CHAIN();\n uint8_t PWM_values_LIGHT_CHAIN[max_pin_number + 1];\n const static int max_LC_triggers = 5;\n int LC_frame_count[max_LC_triggers] = {0,0, 0, 0, 0};\n bool LC_trigger_on[max_LC_triggers] = {false,false, false, false, false};\n int LC_trigger_index = 0;\n int chain_time_LIGHT_CHAIN[max_LC_triggers] = {3000, 3000, 3000, 3000, 3000};//ms\n float chain_width_LIGHT_CHAIN[max_LC_triggers] = {8.0,8.0, 8.0, 8.0, 8.0};//{0.5,0.5, 0.5, 0.5, 0.5};\n \n float variances_LIGHT_CHAIN[max_LC_triggers] = {0.01, 0.01, 0.1, 0.1, 0.1};\n\n // local tigger values;\n int local_trigger_act_time = 5000;\n float local_trigger_variance = 0.01;\n float local_trigger_chain_width = 0.5;\n\n // Behaviour 10: Auto Light Chain\n void start_AUTO_LIGHT_CHAIN(int act_time, float variance, float chain_width);\n void _resume_AUTO_LIGHT_CHAIN();\n uint8_t PWM_values_AUTO_LIGHT_CHAIN[max_pin_number + 1];\n const static int max_LC_triggers_AUTO_LIGHT_CHAIN = 5;\n int LC_frame_count_AUTO_LIGHT_CHAIN[max_LC_triggers] = {0,0,0,0,0};\n bool LC_trigger_on_AUTO_LIGHT_CHAIN[max_LC_triggers] = {false,false, false, false, false};\n int LC_trigger_index_AUTO_LIGHT_CHAIN = 0;\n int chain_time_AUTO_LIGHT_CHAIN[max_LC_triggers] = {3000, 3000, 3000, 3000, 3000};//ms\n float chain_width_AUTO_LIGHT_CHAIN[max_LC_triggers] = {0.5,0.5, 0.5, 0.5, 0.5};\n float variances_AUTO_LIGHT_CHAIN[max_LC_triggers] = {0.01, 0.01, 0.1, 0.1, 0.1};\n\n // local tigger values;\n int local_trigger_act_time_AUTO = 3000;\n //float local_trigger_variance = 0.01;\n //float local_trigger_chain_width = 0.5;\n\n //Behaviour 11: IR reaction light chain\n int time_between_auto_and_column_IR_REACTION_LIGHT_COLUMN = -1250;//500;\n void start_IR_REACTION_LIGHT_COLUMN();\n void _resume_IR_REACTION_LIGHT_COLUMN();\n \n\n // Behaviour 9: Light Chain Background\n float idle_LC_BACKGROUND = 0 ;\n void start_LIGHT_CHAIN_BACKGROUND();\n void _resume_LIGHT_CHAIN_BACKGROUND();\n uint8_t PWM_values_LIGHT_CHAIN_BACKGROUND[max_pin_number + 1];\n\n\n//Reflex behaviour BP\n void start_BP_IR_trigger_reflex(uint8_t ir_index);\n void start_BP_IR_triggedelar_SMA(uint8_t ir_index);\n void _resume_BP_IR_trigger_SMA();\n int ramp_up_time_BP_moth=1500;\n int ramp_up_time_BP_RS=1500;\n int ramp_down_time_BP_moth=2500;\n int ramp_down_time_BP_RS=2500;\n int hold_time_BP_moth=1000;\n int hold_time_BP_RS=1000;\n bool do_BP_IR_trigger_SMA = false;\n \n long start_trigger_time_SMA;\n int actuator_offset_var=700;\n int actuator_offset[12]={0,actuator_offset_var,2*actuator_offset_var,3*actuator_offset_var,4*actuator_offset_var,5*actuator_offset_var,0,actuator_offset_var,2*actuator_offset_var,3*actuator_offset_var,4*actuator_offset_var,5*actuator_offset_var};\n int SMA_to_actuate[12]={0,0,0,0,0,0,0,0,0,0,0,0};\n int check_active_SMA[12] = {0,0,0,0,0,0,0,0,0,0,0,0};\n int wait_time_SMA=2000;\n int SMA_active=0;\n \n void rand_light();\n int rand_pins[2] = {9,10};\n int rand_pin = 9;\n uint8_t fcount=1;\n int dir=1;\n int skip_size = 0; //wrong name: inner framecount\n int skip_millis = 10;\n int skip_millis_default = 10;\n bool force_pin = false;\n int forced_pin;\n //int last_pin_picked = 9;\n \n \n \n\n\n // MERGE ACTUATOR VALUES\n void merge_PWM_values_and_set_actuators();\n \n\n void loop();\n\n void safe_write(uint8_t pin, uint8_t val, uint8_t type);\n void safe_write_ROM(uint8_t pin, uint8_t val);\n\n\n};\n\n#endif //BEHAVIOURS_H_\n"
},
{
"alpha_fraction": 0.6073825359344482,
"alphanum_fraction": 0.6325503587722778,
"avg_line_length": 16.52941131591797,
"blob_id": "a4a927a4c6fa801b5244ac6f89cb07c261c36d82",
"content_id": "738df173d18cf2d9015eec67b2b28699563819e2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 596,
"license_type": "no_license",
"max_line_length": 63,
"num_lines": 34,
"path": "/Archive/Teensy/LuddyNode/SMA.h",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "/*\n* SMA.h - Library for SMA restricted actuation\n* Created By Adam Francey May 9, 2018\n* Philip Beesley Architect Inc. / Living Architecture Systems Group\n*/\n\n#ifndef SMA_H_\n#define SMA_H_\n\n\nclass SMA{\n\n public:\n SMA(int pin);\n ~SMA();\n\n void init_SMA(int pin);\n int SMA_pin;\n\n long max_actuation_time = 2000;\n long cooldown_time = 20000;\n\n long actuation_start_time = millis();\n long elapsed_time_since_actuation = 0;\n bool actuating = false;\n bool cooling_down = true;\n bool ready_to_actuate = false;\n\n bool actuate_if_ready();\n void loop();\n\n};\n\n#endif //SMA_H_\n"
},
{
"alpha_fraction": 0.525581419467926,
"alphanum_fraction": 0.6468438506126404,
"avg_line_length": 34.411766052246094,
"blob_id": "95fc3a2b7de42877a0bf2b9784f3446488793387",
"content_id": "6639a0d233dd6917fcd6079ee83b92736a8f30a5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 3010,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 85,
"path": "/Archive/Teensy/LuddyNode/AudioController.h",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "#include <Audio.h>\n#include <Wire.h>\n#include <SPI.h>\n#include <SD.h>\n#include <SerialFlash.h>\n\n\n#ifndef AUDIOCONTROLLER_H_\n#define AUDIOCONTROLLER_H_\n\nclass AudioController{\n\n public:\n AudioController();\n ~AudioController();\n\n //write wav\n unsigned long ChunkSize = 0L;\n unsigned long Subchunk1Size = 16;\n unsigned int AudioFormat = 1;\n unsigned int numChannels = 1;\n unsigned long sampleRate = 44100;\n unsigned int bitsPerSample = 16;\n unsigned long byteRate = sampleRate*numChannels*(bitsPerSample/8);// samplerate x channels x (bitspersample / 8)\n unsigned int blockAlign = numChannels*bitsPerSample/8;\n unsigned long Subchunk2Size = 0L;\n unsigned long recByteSaved = 0L;\n unsigned long NumSamples = 0L;\n byte byte1, byte2, byte3, byte4;\n //uint8_t byte1, byte2, byte3, byte4;\n \n const int myInput = AUDIO_INPUT_LINEIN;\n\n // GUItool: begin automatically generated code\n AudioPlaySdWav playSdWav1; //xy=69,280.5\n AudioInputI2S i2s1; //xy=119.3055419921875,219.4722137451172\n AudioMixer4 mixer1; //xy=211.49999321831598,294.24998643663196\n AudioFilterStateVariable filter1; //xy=338.999993218316,293.99998643663196\n AudioEffectReverb reverb1; //xy=457.9999932183159,281.99998643663196\n AudioRecordQueue queue1; //xy=487.61114501953125,136.80555725097656\n AudioMixer4 mixer2; //xy=623,240\n AudioOutputI2S i2s2; //xy=752.3611450195312,235.66665649414062\n /*\n AudioConnection patchCord1(playSdWav1, 0, mixer1, 0);\n AudioConnection patchCord2(playSdWav1, 1, mixer1, 1);\n AudioConnection patchCord3(i2s1, 0, queue1, 0);\n AudioConnection patchCord4(i2s1, 1, mixer2, 0);\n AudioConnection patchCord5(mixer1, 0, filter1, 0);\n AudioConnection patchCord6(mixer1, 0, filter1, 1);\n AudioConnection patchCord7(filter1, 0, reverb1, 0);\n AudioConnection patchCord8(reverb1, 0, mixer2, 1);\n AudioConnection patchCord9(mixer2, 0, i2s2, 0);\n AudioConnection patchCord10(mixer2, 0, i2s2, 1);\n */\n AudioControlSGTL5000 sgtl5000_1; //xy=379.77777099609375,429.5555419921875\n // GUItool: end automatically generated code\n\n\n int mode = 0; // 0=stopped, 1=recording, 2=playing\n File frec;\n \n // Use these with the Teensy 3.6 & Audio Shield\n #define SDCARD_CS_PIN BUILTIN_SDCARD\n #define SDCARD_MOSI_PIN 11 // not actually used\n #define SDCARD_SCK_PIN 13 // not actually used\n \n \n // Use these with the Teensy Audio Shield\n //#define SDCARD_CS_PIN 10\n //#define SDCARD_MOSI_PIN 7\n //#define SDCARD_SCK_PIN 14\n\n void loop();\n void startRecording();\n void stopRecording();\n void startPlaying();\n void stopPlaying();\n void continueRecording();\n void writeOutHeader();\n\n\n\n};\n\n#endif //AUDIOCONTROLLER_H_\n"
},
{
"alpha_fraction": 0.8006644248962402,
"alphanum_fraction": 0.8006644248962402,
"avg_line_length": 30.6842098236084,
"blob_id": "29f69c2cb73ae5b22735eff9de4d0401e69ebd5d",
"content_id": "8b7a396e3e94b00c2e2e16e227e36d0ff6fbcaa5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 602,
"license_type": "no_license",
"max_line_length": 128,
"num_lines": 19,
"path": "/Master Laptop/README.md",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "# Master Code\n\n## LuddyLaptopMaster.py\nMaster script that manages entire system network.\n\n## DeviceLocator.py\nGenerated by device_locator_generator.py, defines the system network for a particular sculpture (all actuators and sensors).\n\n## Excitor.py\nClass defining a single excitor.\n\n## FutureActions.py\nCreate a FutureActions object to queue functions and parameters for execution at a later time (without relying on time.sleep()).\n\n## GroupActions.py\nConstructs OSC message sequences for coordinated actuation among different sections of the sculpture.\n\n## Tools.py\nContains commonly used functions.\n"
},
{
"alpha_fraction": 0.5344418287277222,
"alphanum_fraction": 0.6294536590576172,
"avg_line_length": 23.05714225769043,
"blob_id": "4bf32adda8ce5143f50d1e8c24a3035aa8dd0199",
"content_id": "454db1bfde33604cf52da7fae9c712b17a520aa3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 842,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 35,
"path": "/Utilities/SET_IR_thresholds.py",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "# Tests all actuators one at a time\n# By fading up and down\n# Tests sphereunits and SSS for now\n\nimport random\nimport time\nimport threading\n\nfrom pythonosc import osc_message_builder\nfrom pythonosc import udp_client\n\nIP_MASTER = '10.14.4.198'\n\n# Adam's testing laptop IP\nIP_ADAM = \"10.14.4.178\"\nIP_MASTER = IP_ADAM\n\nclient = udp_client.UDPClient(IP_MASTER, 3001)\n\n\n# SET ALL IR THRESHOLDS\nthresholds = [400, 195, 140,\n 375, 170, 155,\n 370, 175, 245,\n 260, 190, 280,\n 350, 330, 200,\n 415, 140, 200]\n\nprint(\"Setting IR thresholds\")\nfor i in range(1,19):\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/SET_IR_THRESHOLD/IR\" + str(i))\n print(\"IR\" + str(i) + \": \" + str(thresholds[i-1]))\n msg.add_arg(thresholds[i-1])\n msg = msg.build()\n client.send(msg)\n"
},
{
"alpha_fraction": 0.7684210538864136,
"alphanum_fraction": 0.7684210538864136,
"avg_line_length": 22.75,
"blob_id": "e55ed5fd1edb9d1cc777c4d960d34ae9587c08a6",
"content_id": "e1325e9fe354f92b331c66e4f2ffeb29fcaa8e8c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 95,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 4,
"path": "/Archive/Teensy/LuddyNode/DeviceLocator.cpp",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "#include \"DeviceLocator.h\"\n\nDeviceLocator::DeviceLocator(){}\nDeviceLocator::~DeviceLocator(){}\n"
},
{
"alpha_fraction": 0.5614664554595947,
"alphanum_fraction": 0.6198446154594421,
"avg_line_length": 25.415788650512695,
"blob_id": "4878f4862531dc7556eaca4b7f62a60c57086b94",
"content_id": "51ec956dd857b7eea1a3f3fe800eb9a9e638754b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 5019,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 190,
"path": "/Archive/Teensy/LuddyNode/AudioController.cpp",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "#include <Arduino.h>\n#include <stdint.h>\n\n/*\n#include <Audio.h>\n#include <Wire.h>\n#include <SPI.h>\n#include <SD.h>\n#include <SerialFlash.h>\n*/\n#include \"AudioController.h\"\n\nAudioController::AudioController(){\n \n AudioConnection patchCord1(playSdWav1, 0, mixer1, 0);\n AudioConnection patchCord2(playSdWav1, 1, mixer1, 1);\n AudioConnection patchCord3(i2s1, 0, queue1, 0);\n AudioConnection patchCord4(i2s1, 1, mixer2, 0);\n AudioConnection patchCord5(mixer1, 0, filter1, 0);\n AudioConnection patchCord6(mixer1, 0, filter1, 1);\n AudioConnection patchCord7(filter1, 0, reverb1, 0);\n AudioConnection patchCord8(reverb1, 0, mixer2, 1);\n AudioConnection patchCord9(mixer2, 0, i2s2, 0);\n AudioConnection patchCord10(mixer2, 0, i2s2, 1);\n \n\n \n //Serial.begin(115200);\n\n // note: setting this too high causes a\n AudioMemory(60);\n \n sgtl5000_1.enable();\n sgtl5000_1.inputSelect(myInput);\n sgtl5000_1.volume(0.7);\n\n mixer1.gain(0,0.2);\n mixer1.gain(1,0.2); \n\n filter1.frequency(1000);\n reverb1.reverbTime(20);\n\n mixer2.gain(0,0.5);\n mixer2.gain(1,0.5);\n\n SPI.setMOSI(SDCARD_MOSI_PIN);\n SPI.setSCK(SDCARD_SCK_PIN);\n if (!(SD.begin(SDCARD_CS_PIN))) {\n // stop here, but print a message repetitively\n while (1) {\n Serial.println(\"Unable to access the SD card\");\n delay(500);\n }\n }\n}\n\nAudioController::~AudioController(){}\n\n\nvoid AudioController::loop(){\n if(Serial.available() > 0) {\n int incomingInt = Serial.read();\n \n //REC\n if(incomingInt == 1){\n if(mode == 2) stopPlaying();\n if(mode == 0) startRecording();\n }\n //STOP\n if(incomingInt == 2){\n if(mode == 1) stopRecording();\n if(mode == 2) stopPlaying(); \n }\n //PLAY\n if(incomingInt == 3) {\n if(mode == 1) stopRecording();\n if(mode == 0) startPlaying();\n }\n }\n if (mode == 1) {\n continueRecording();\n } \n}\n\nvoid AudioController::startRecording() {\n\n if(SD.exists(\"RECORD.WAV\")){\n SD.remove(\"RECORD.WAV\");\n }\n frec = SD.open(\"RECORD.WAV\",FILE_WRITE);\n if(frec) {\n queue1.begin();\n mode = 1;\n recByteSaved = 0L;\n }\n}\n\nvoid AudioController::continueRecording() {\n if(queue1.available() >= 2){\n byte buffer[512];\n \n memcpy(buffer, queue1.readBuffer(), 256);\n queue1.freeBuffer();\n memcpy(buffer + 256, queue1.readBuffer(),256);\n queue1.freeBuffer();\n \n frec.write(buffer, 512);\n recByteSaved += 512;\n\n \n }\n}\n\nvoid AudioController::stopRecording(){\n queue1.end();\n if(mode == 1){\n while(queue1.available() > 0){\n \n frec.write((byte*)queue1.readBuffer(), 256);\n queue1.freeBuffer();\n recByteSaved += 256;\n }\n writeOutHeader();\n frec.close();\n\n }\n mode = 0;\n}\n\nvoid AudioController::startPlaying(){ \n playSdWav1.play(\"RECORD.WAV\");\n mode = 2;\n}\n\nvoid AudioController::stopPlaying(){\n if (mode == 2) playSdWav1.stop();\n mode = 0;\n}\n\nvoid AudioController::writeOutHeader() { // update WAV header with final filesize/datasize\n\n// NumSamples = (recByteSaved*8)/bitsPerSample/numChannels;\n// Subchunk2Size = NumSamples*numChannels*bitsPerSample/8; // number of samples x number of channels x number of bytes per sample\n Subchunk2Size = recByteSaved;\n ChunkSize = Subchunk2Size + 36;\n frec.seek(0);\n frec.write(\"RIFF\");\n byte1 = ChunkSize & 0xff;\n byte2 = (ChunkSize >> 8) & 0xff;\n byte3 = (ChunkSize >> 16) & 0xff;\n byte4 = (ChunkSize >> 24) & 0xff; \n frec.write(byte1); frec.write(byte2); frec.write(byte3); frec.write(byte4);\n frec.write(\"WAVE\");\n frec.write(\"fmt \");\n byte1 = Subchunk1Size & 0xff;\n byte2 = (Subchunk1Size >> 8) & 0xff;\n byte3 = (Subchunk1Size >> 16) & 0xff;\n byte4 = (Subchunk1Size >> 24) & 0xff; \n frec.write(byte1); frec.write(byte2); frec.write(byte3); frec.write(byte4);\n byte1 = AudioFormat & 0xff;\n byte2 = (AudioFormat >> 8) & 0xff;\n frec.write(byte1); frec.write(byte2); \n byte1 = numChannels & 0xff;\n byte2 = (numChannels >> 8) & 0xff;\n frec.write(byte1); frec.write(byte2); \n byte1 = sampleRate & 0xff;\n byte2 = (sampleRate >> 8) & 0xff;\n byte3 = (sampleRate >> 16) & 0xff;\n byte4 = (sampleRate >> 24) & 0xff; \n frec.write(byte1); frec.write(byte2); frec.write(byte3); frec.write(byte4);\n byte1 = byteRate & 0xff;\n byte2 = (byteRate >> 8) & 0xff;\n byte3 = (byteRate >> 16) & 0xff;\n byte4 = (byteRate >> 24) & 0xff; \n frec.write(byte1); frec.write(byte2); frec.write(byte3); frec.write(byte4);\n byte1 = blockAlign & 0xff;\n byte2 = (blockAlign >> 8) & 0xff;\n frec.write(byte1); frec.write(byte2); \n byte1 = bitsPerSample & 0xff;\n byte2 = (bitsPerSample >> 8) & 0xff;\n frec.write(byte1); frec.write(byte2); \n frec.write(\"data\");\n byte1 = Subchunk2Size & 0xff;\n byte2 = (Subchunk2Size >> 8) & 0xff;\n byte3 = (Subchunk2Size >> 16) & 0xff;\n byte4 = (Subchunk2Size >> 24) & 0xff; \n frec.write(byte1); frec.write(byte2); frec.write(byte3); frec.write(byte4);\n frec.close();\n\n}\n"
},
{
"alpha_fraction": 0.47093749046325684,
"alphanum_fraction": 0.5012500286102295,
"avg_line_length": 34.16483688354492,
"blob_id": "21a9b37abdb1e6bb5b3cc6f267599cc7608f3b08",
"content_id": "7439dbf6ec7c48e7d42955a49479c779ec517039",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3200,
"license_type": "no_license",
"max_line_length": 131,
"num_lines": 91,
"path": "/Utilities/TEST_SMA.py",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "import random\nimport time\n\nfrom pythonosc import osc_message_builder\nfrom pythonosc import udp_client\n\n#IP_MASTER = \"192.168.1.8\"\n#IP_MASTER = \"192.168.2.24\"\nIP_MASTER = '10.14.4.178'\n\n\n\n\nif __name__ == \"__main__\":\n\n #time.sleep(15);\n \n client = udp_client.UDPClient(IP_MASTER, 3001)\n\n while True:\n\n time.sleep(0.7);\n\n r_bpc = random.randint(1,12)\n r_bp = random.randint(1,2)\n r_SMA = random.randint(1,6)\n msg = osc_message_builder.OscMessageBuilder(address = '/SMA' + str(r_bpc) + '-' + str(r_bp) + '-' + str(r_SMA))\n msg = msg.build()\n client.send(msg)\n \n\n## for bpc in range(1,13):\n## #for bp in range(1,3):\n## for bp in range(1,2):\n## for i in range(3):\n## r = random.randint(1,6)\n## #rr = random.randint(1,3)\n## if True: #if rr == 1:\n## msg = osc_message_builder.OscMessageBuilder(address = '/SMA' + str(bpc) + '-' + str(bp) + '-' + str(r))\n## #msg = osc_message_builder.OscMessageBuilder(address = '/SMA' + str(bpc) + '-' + str(1) + '-' + str(i+1))\n## msg = msg.build()\n## client.send(msg)\n #time.sleep(0.1)\n## msg = osc_message_builder.OscMessageBuilder(address = '/SMA' + str(bpc) + '-' + str(2) + '-' + str(i+1))\n## msg = msg.build()\n## client.send(msg)\n## time.sleep(0.2)\n\n \n \n \n\n## msg = osc_message_builder.OscMessageBuilder(address = '/SMA1-2-3')\n## msg = msg.build()\n## client.send(msg)\n## msg = osc_message_builder.OscMessageBuilder(address = '/SMA1-2-2')\n## msg = msg.build()\n## client.send(msg)\n## msg = osc_message_builder.OscMessageBuilder(address = '/SMA1-2-1')\n## msg = msg.build()\n## client.send(msg)\n## msg = osc_message_builder.OscMessageBuilder(address = '/SMA1-1-3')\n## msg = msg.build()\n## client.send(msg)\n## msg = osc_message_builder.OscMessageBuilder(address = '/SMA1-1-2')\n## msg = msg.build()\n## client.send(msg)\n## msg = osc_message_builder.OscMessageBuilder(address = '/SMA1-1-1')\n## msg = msg.build()\n## client.send(msg)\n## msg = osc_message_builder.OscMessageBuilder(address = '/SMA2-1-3')\n## msg = msg.build()\n## client.send(msg)\n## msg = osc_message_builder.OscMessageBuilder(address = '/SMA2-1-2')\n## msg = msg.build()\n## client.send(msg)\n## msg = osc_message_builder.OscMessageBuilder(address = '/SMA2-1-1')\n## msg = msg.build()\n## client.send(msg)\n## msg = osc_message_builder.OscMessageBuilder(address = '/SMA2-2-3')\n## msg = msg.build()\n## client.send(msg)\n## msg = osc_message_builder.OscMessageBuilder(address = '/SMA2-2-2')\n## msg = msg.build()\n## client.send(msg)\n## msg = osc_message_builder.OscMessageBuilder(address = '/SMA2-2-1')\n## msg = msg.build()\n## client.send(msg)\n##\n##\n##\n"
},
{
"alpha_fraction": 0.41607552766799927,
"alphanum_fraction": 0.43744170665740967,
"avg_line_length": 37.86798858642578,
"blob_id": "0af57c1d84acae1c53a0a80da605c5c17809f20c",
"content_id": "3ce405988ab725c15a4f048e4467ed3450ef7df9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 35383,
"license_type": "no_license",
"max_line_length": 129,
"num_lines": 909,
"path": "/Master Laptop/GroupActions.py",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "import threading\nfrom pythonosc import osc_message_builder\nfrom pythonosc import udp_client\nimport time\n\nclass GroupActions():\n\n def __init__(self, IP_MASTER):\n self.RS = [\"RS1\", 'RS2', 'RS3', 'RS4', 'RS5', 'RS6']\n self.moths = [\"MOTH1\", 'MOTH2', 'MOTH3', 'MOTH4', 'MOTH5', 'MOTH6']\n\n self.moths_2_5_11 = [\"MOTH1\", 'MOTH2', 'MOTH3', 'MOTH4','MOTH7', 'MOTH8', 'MOTH9']\n\n self.moths_SU = [\"MOTH1\", 'MOTH2', 'MOTH3', 'MOTH4', 'MOTH5', 'MOTH6', 'MOTH7', 'MOTH8', 'MOTH9']\n\n self.num_sphereunits = 12\n \n self.client = udp_client.UDPClient(IP_MASTER, 3001)\n\n # _pulse_small_sphere\n self.t_pulse = 3000\n self.max_pulse = 50\n self.on_pulse = True\n self.last_pulse_up_time_array = [0,0,0,\n 0,0,0,\n 0,0,0,\n 0,0,0,\n 0,0,0]\n\n default_time = 5000\n start_time = time.time()\n\n #################### THIS ARRAY MODIFIABLE: PERIOD OF PULSING\n self.t_pulse_array = [default_time, default_time, default_time,\n default_time, default_time, default_time,\n default_time, default_time, default_time,\n default_time, default_time, default_time]\n \n self.last_pulse_down_time_array = []\n for i in range(self.num_sphereunits): \n self.last_pulse_down_time_array.append(time.time() + default_time)\n\n ################ THIS ARRAY MODIFIABLE: MAXIMUM BRIGHTNESS\n self.max_pulse_array = [150,150,150,\n 150,150,150,\n 150,150,150,\n 150,150,150]\n\n self.on_pulse_array = [True, True, True,\n True, True, True,\n True, True, True,\n True, True, True]\n \n def SMA_ring(self, BP):\n thread = threading.Thread(target = self._SMA_ring, args = (BP,))\n thread.start()\n \n\n def _SMA_ring(self, BP):\n #BP = '1-1'\n if len(BP) == 3:\n BPC_num = int(BP[0])\n if len(BP) == 4:\n BPC_num = int(BP[:2])\n BP_index = BP[-1]\n \n for i in range(1,7):\n msg = osc_message_builder.OscMessageBuilder(address = '/SMA' + str(BP) + '-' + str(i))\n msg = msg.build()\n self.client.send(msg)\n time.sleep(0.3)\n\n #print(BP)\n #print(BP_index)\n back_count = 1\n\n for num in range(BPC_num, 13):\n prev_BPC = BPC_num - back_count\n for i in range(1,7):\n msg = osc_message_builder.OscMessageBuilder(address = '/SMA' + str(num) + '-' + BP_index + '-' + str(i))\n msg = msg.build()\n self.client.send(msg)\n \n if prev_BPC > 0:\n msg = osc_message_builder.OscMessageBuilder(address = '/SMA' + str(prev_BPC) + '-' + BP_index + '-' + str(i))\n msg = msg.build()\n self.client.send(msg)\n \n time.sleep(0.3)\n back_count = back_count + 1\n\n \n \n\n \n def SSS_ring(self, SSS):\n thread = threading.Thread(target = self._SSS_ring, args = (SSS,))\n thread.start()\n\n def pulse_small_sphere(self):\n thread = threading.Thread(target = self._pulse_small_sphere)\n thread.start()\n\n def pulse_sphereunit_1(self):\n thread = threading.Thread(target = self._pulse_sphereunit_1)\n thread.start()\n\n def pulse_sphereunit_2(self):\n thread = threading.Thread(target = self._pulse_sphereunit_2)\n thread.start()\n\n def pulse_sphereunit_3(self):\n thread = threading.Thread(target = self._pulse_sphereunit_3)\n thread.start()\n\n def pulse_sphereunit_4(self):\n thread = threading.Thread(target = self._pulse_sphereunit_4)\n thread.start()\n\n def pulse_sphereunit_5(self):\n thread = threading.Thread(target = self._pulse_sphereunit_5)\n thread.start()\n\n def pulse_sphereunit_6(self):\n thread = threading.Thread(target = self._pulse_sphereunit_6)\n thread.start()\n\n def pulse_sphereunit_7(self):\n thread = threading.Thread(target = self._pulse_sphereunit_7)\n thread.start()\n\n def pulse_sphereunit_8(self):\n thread = threading.Thread(target = self._pulse_sphereunit_8)\n thread.start()\n\n def pulse_sphereunit_9(self):\n thread = threading.Thread(target = self._pulse_sphereunit_9)\n thread.start()\n\n def pulse_sphereunit_10(self):\n thread = threading.Thread(target = self._pulse_sphereunit_10)\n thread.start()\n\n def pulse_sphereunit_11(self):\n thread = threading.Thread(target = self._pulse_sphereunit_11)\n thread.start()\n\n def pulse_sphereunit_12(self):\n thread = threading.Thread(target = self._pulse_sphereunit_12)\n thread.start()\n \n def _SSS_ring(self, SSS):\n t = 500\n max_PWM = 190\n step_val = 95\n #t = 250\n #max_PWM = 180\n #step_val = 45\n finished = False\n PWM_vals = [0*step_val, -step_val,-2*step_val,-3*step_val,-4*step_val,-5*step_val]\n direction = [1, 1, 1, 1, 1, 1]\n count = 0\n while not finished:\n count+=1\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SSS\" + str(SSS))\n for rs in range(len(self.RS)):\n PWM_vals[rs] = PWM_vals[rs] + direction[rs]*step_val\n val = PWM_vals[rs]\n if val >= step_val or direction[rs] == -1 and val >= 0:\n msg.add_arg(self.RS[rs])\n msg.add_arg(val)\n msg.add_arg(t)\n msg.add_arg(self.moths[rs])\n msg.add_arg(val)\n msg.add_arg(t)\n if val >= max_PWM:\n direction[rs] = -1\n msg = msg.build()\n self.client.send(msg)\n time.sleep(t/1000)\n\n if PWM_vals[5] <= 0 and direction[5] == -1:\n finished = True\n\n## def _pulse_small_sphere(self, ):\n## #self.last_pulse_up_time = 0\n## #self.last_pulse_down_time = time.time() + self.t_pulse\n##\n## fading_up = True\n## fading_down = False\n##\n## while self.on_pulse:\n##\n## if ((1000*time.time()) % self.t_pulse) <= self.t_pulse/2 and fading_down:\n## fading_down = False\n## fading_up = True\n## t = int(self.t_pulse/2)\n## val = self.max_pulse\n## msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE10\")\n## for rs in self.RS:\n## msg.add_arg(rs)\n## msg.add_arg(val)\n## msg.add_arg(t)\n## msg = msg.build()\n## self.client.send(msg)\n## self.last_pulse_up_time = time.time()\n##\n## elif ((1000*time.time()) % self.t_pulse) > self.t_pulse/2 and fading_up:\n## fading_up = False\n## fading_down = True\n## t = int(self.t_pulse/2)\n## msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE10\")\n## for rs in self.RS:\n## msg.add_arg(rs)\n## msg.add_arg(0)\n## msg.add_arg(t)\n## msg = msg.build()\n## self.client.send(msg)\n## self.last_pulse_down_time = time.time()\n\n def _pulse_sphereunit_1(self):\n\n unit = 1\n fading_up = True\n fading_down = False\n\n while self.on_pulse_array[unit-1]:\n\n if ((1000*time.time()) % self.t_pulse_array[unit-1]) <= self.t_pulse_array[unit-1]/2 and fading_down:\n fading_down = False\n fading_up = True\n t = int(self.t_pulse_array[unit-1]/2)\n val = self.max_pulse_array[unit-1]\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(val)\n msg.add_arg(t)\n\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n \n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_up_time_array[unit-1] = time.time()\n\n elif ((1000*time.time()) % self.t_pulse_array[unit-1]) > self.t_pulse_array[unit-1]/2 and fading_up:\n fading_up = False\n fading_down = True\n t = int(self.t_pulse_array[unit-1]/2)\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(0)\n msg.add_arg(t)\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_down_time_array[unit-1] = time.time()\n\n def _pulse_sphereunit_2(self):\n\n unit = 2\n fading_up = True\n fading_down = False\n\n while self.on_pulse_array[unit-1]:\n\n if ((1000*time.time()) % self.t_pulse_array[unit-1]) <= self.t_pulse_array[unit-1]/2 and fading_down:\n fading_down = False\n fading_up = True\n t = int(self.t_pulse_array[unit-1]/2)\n val = self.max_pulse_array[unit-1]\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(val)\n msg.add_arg(t)\n\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n \n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_up_time_array[unit-1] = time.time()\n\n elif ((1000*time.time()) % self.t_pulse_array[unit-1]) > self.t_pulse_array[unit-1]/2 and fading_up:\n fading_up = False\n fading_down = True\n t = int(self.t_pulse_array[unit-1]/2)\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(0)\n msg.add_arg(t)\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_down_time_array[unit-1] = time.time()\n\n def _pulse_sphereunit_3(self):\n\n unit = 3\n fading_up = True\n fading_down = False\n\n while self.on_pulse_array[unit-1]:\n\n if ((1000*time.time()) % self.t_pulse_array[unit-1]) <= self.t_pulse_array[unit-1]/2 and fading_down:\n fading_down = False\n fading_up = True\n t = int(self.t_pulse_array[unit-1]/2)\n val = self.max_pulse_array[unit-1]\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(val)\n msg.add_arg(t)\n\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n \n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_up_time_array[unit-1] = time.time()\n\n elif ((1000*time.time()) % self.t_pulse_array[unit-1]) > self.t_pulse_array[unit-1]/2 and fading_up:\n fading_up = False\n fading_down = True\n t = int(self.t_pulse_array[unit-1]/2)\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(0)\n msg.add_arg(t)\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_down_time_array[unit-1] = time.time()\n\n def _pulse_sphereunit_4(self):\n\n unit = 4\n fading_up = True\n fading_down = False\n\n while self.on_pulse_array[unit-1]:\n\n if ((1000*time.time()) % self.t_pulse_array[unit-1]) <= self.t_pulse_array[unit-1]/2 and fading_down:\n fading_down = False\n fading_up = True\n t = int(self.t_pulse_array[unit-1]/2)\n val = self.max_pulse_array[unit-1]\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(val)\n msg.add_arg(t)\n\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n \n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_up_time_array[unit-1] = time.time()\n\n elif ((1000*time.time()) % self.t_pulse_array[unit-1]) > self.t_pulse_array[unit-1]/2 and fading_up:\n fading_up = False\n fading_down = True\n t = int(self.t_pulse_array[unit-1]/2)\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(0)\n msg.add_arg(t)\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_down_time_array[unit-1] = time.time()\n\n def _pulse_sphereunit_5(self):\n\n unit = 5\n fading_up = True\n fading_down = False\n\n while self.on_pulse_array[unit-1]:\n\n if ((1000*time.time()) % self.t_pulse_array[unit-1]) <= self.t_pulse_array[unit-1]/2 and fading_down:\n fading_down = False\n fading_up = True\n t = int(self.t_pulse_array[unit-1]/2)\n val = self.max_pulse_array[unit-1]\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(val)\n msg.add_arg(t)\n\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n \n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_up_time_array[unit-1] = time.time()\n\n elif ((1000*time.time()) % self.t_pulse_array[unit-1]) > self.t_pulse_array[unit-1]/2 and fading_up:\n fading_up = False\n fading_down = True\n t = int(self.t_pulse_array[unit-1]/2)\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(0)\n msg.add_arg(t)\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_down_time_array[unit-1] = time.time()\n\n def _pulse_sphereunit_6(self):\n\n unit = 6\n fading_up = True\n fading_down = False\n\n while self.on_pulse_array[unit-1]:\n\n if ((1000*time.time()) % self.t_pulse_array[unit-1]) <= self.t_pulse_array[unit-1]/2 and fading_down:\n fading_down = False\n fading_up = True\n t = int(self.t_pulse_array[unit-1]/2)\n val = self.max_pulse_array[unit-1]\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(val)\n msg.add_arg(t)\n\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n \n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_up_time_array[unit-1] = time.time()\n\n elif ((1000*time.time()) % self.t_pulse_array[unit-1]) > self.t_pulse_array[unit-1]/2 and fading_up:\n fading_up = False\n fading_down = True\n t = int(self.t_pulse_array[unit-1]/2)\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(0)\n msg.add_arg(t)\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_down_time_array[unit-1] = time.time()\n\n def _pulse_sphereunit_7(self):\n\n unit = 7\n fading_up = True\n fading_down = False\n\n while self.on_pulse_array[unit-1]:\n\n if ((1000*time.time()) % self.t_pulse_array[unit-1]) <= self.t_pulse_array[unit-1]/2 and fading_down:\n fading_down = False\n fading_up = True\n t = int(self.t_pulse_array[unit-1]/2)\n val = self.max_pulse_array[unit-1]\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(val)\n msg.add_arg(t)\n\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n \n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_up_time_array[unit-1] = time.time()\n\n elif ((1000*time.time()) % self.t_pulse_array[unit-1]) > self.t_pulse_array[unit-1]/2 and fading_up:\n fading_up = False\n fading_down = True\n t = int(self.t_pulse_array[unit-1]/2)\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(0)\n msg.add_arg(t)\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_down_time_array[unit-1] = time.time()\n\n\n def _pulse_sphereunit_8(self):\n\n unit = 8\n fading_up = True\n fading_down = False\n\n while self.on_pulse_array[unit-1]:\n\n if ((1000*time.time()) % self.t_pulse_array[unit-1]) <= self.t_pulse_array[unit-1]/2 and fading_down:\n fading_down = False\n fading_up = True\n t = int(self.t_pulse_array[unit-1]/2)\n val = self.max_pulse_array[unit-1]\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(val)\n msg.add_arg(t)\n\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n \n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_up_time_array[unit-1] = time.time()\n\n elif ((1000*time.time()) % self.t_pulse_array[unit-1]) > self.t_pulse_array[unit-1]/2 and fading_up:\n fading_up = False\n fading_down = True\n t = int(self.t_pulse_array[unit-1]/2)\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(0)\n msg.add_arg(t)\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_down_time_array[unit-1] = time.time()\n\n\n def _pulse_sphereunit_9(self):\n\n unit = 9\n fading_up = True\n fading_down = False\n\n while self.on_pulse_array[unit-1]:\n\n if ((1000*time.time()) % self.t_pulse_array[unit-1]) <= self.t_pulse_array[unit-1]/2 and fading_down:\n fading_down = False\n fading_up = True\n t = int(self.t_pulse_array[unit-1]/2)\n val = self.max_pulse_array[unit-1]\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(val)\n msg.add_arg(t)\n\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n \n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_up_time_array[unit-1] = time.time()\n\n elif ((1000*time.time()) % self.t_pulse_array[unit-1]) > self.t_pulse_array[unit-1]/2 and fading_up:\n fading_up = False\n fading_down = True\n t = int(self.t_pulse_array[unit-1]/2)\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(0)\n msg.add_arg(t)\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_down_time_array[unit-1] = time.time()\n\n\n def _pulse_sphereunit_10(self):\n\n unit = 10\n fading_up = True\n fading_down = False\n\n while self.on_pulse_array[unit-1]:\n\n if ((1000*time.time()) % self.t_pulse_array[unit-1]) <= self.t_pulse_array[unit-1]/2 and fading_down:\n fading_down = False\n fading_up = True\n t = int(self.t_pulse_array[unit-1]/2)\n val = self.max_pulse_array[unit-1]\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(val)\n msg.add_arg(t)\n\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n \n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_up_time_array[unit-1] = time.time()\n\n elif ((1000*time.time()) % self.t_pulse_array[unit-1]) > self.t_pulse_array[unit-1]/2 and fading_up:\n fading_up = False\n fading_down = True\n t = int(self.t_pulse_array[unit-1]/2)\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(0)\n msg.add_arg(t)\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_down_time_array[unit-1] = time.time()\n\n\n def _pulse_sphereunit_11(self):\n\n unit = 11\n fading_up = True\n fading_down = False\n\n while self.on_pulse_array[unit-1]:\n\n if ((1000*time.time()) % self.t_pulse_array[unit-1]) <= self.t_pulse_array[unit-1]/2 and fading_down:\n fading_down = False\n fading_up = True\n t = int(self.t_pulse_array[unit-1]/2)\n val = self.max_pulse_array[unit-1]\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(val)\n msg.add_arg(t)\n\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n \n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_up_time_array[unit-1] = time.time()\n\n elif ((1000*time.time()) % self.t_pulse_array[unit-1]) > self.t_pulse_array[unit-1]/2 and fading_up:\n fading_up = False\n fading_down = True\n t = int(self.t_pulse_array[unit-1]/2)\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(0)\n msg.add_arg(t)\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_down_time_array[unit-1] = time.time()\n\n\n\n def _pulse_sphereunit_12(self):\n\n unit = 12\n fading_up = True\n fading_down = False\n\n while self.on_pulse_array[unit-1]:\n\n if ((1000*time.time()) % self.t_pulse_array[unit-1]) <= self.t_pulse_array[unit-1]/2 and fading_down:\n fading_down = False\n fading_up = True\n t = int(self.t_pulse_array[unit-1]/2)\n val = self.max_pulse_array[unit-1]\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(val)\n msg.add_arg(t)\n\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(val)\n msg.add_arg(t)\n \n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_up_time_array[unit-1] = time.time()\n\n elif ((1000*time.time()) % self.t_pulse_array[unit-1]) > self.t_pulse_array[unit-1]/2 and fading_up:\n fading_up = False\n fading_down = True\n t = int(self.t_pulse_array[unit-1]/2)\n msg = osc_message_builder.OscMessageBuilder(address = \"/4D/FADE_ACTUATOR_GROUP/SPHERE\" + str(unit))\n for rs in self.RS:\n msg.add_arg(rs)\n msg.add_arg(0)\n msg.add_arg(t)\n if unit in [2,5,11]:\n for moth in self.moths_2_5_11:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n else:\n for moth in self.moths_SU:\n msg.add_arg(moth)\n msg.add_arg(0)\n msg.add_arg(t)\n msg = msg.build()\n self.client.send(msg)\n self.last_pulse_down_time_array[unit-1] = time.time()\n \n \n\n \n"
},
{
"alpha_fraction": 0.6134610176086426,
"alphanum_fraction": 0.6272944808006287,
"avg_line_length": 36.130001068115234,
"blob_id": "7a41ea77a296fcd69df62198cec96f93159b2c4f",
"content_id": "fccaf0b983f95d3112af022e6a135769571beb1b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3759,
"license_type": "no_license",
"max_line_length": 107,
"num_lines": 100,
"path": "/Raspberry Pi/LuddyPiSlave.py",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "# LuddyPiSlave.py - LASG/PBAI\n# Created by Adam Francey, March 16 2018\n# This code resides on each Raspberry Pi within Amatria at Luddy Hall\n# Reads serial data from each connected node and sends received bytes to the laptop over UDP\n# Reads UDP packets from the laptop and sends it to the appropriate node\n\nimport NodeSerial # LASG library for reading serial ports\nimport PiUDP # LASG library for UDP communication\nfrom serial import SerialException\nimport queue\nimport time\n\n# instruction codes\nREQUEST_TEENSY_IDS = b'\\x01' # send back ids of all connected teensies\n\n# code handlers\ndef handle_REQUEST_TEENSY_IDS():\n SOM = b'\\xff\\xff'\n tid = b'\\x00\\x00\\x00' # if teensy ID is \\x00\\x00\\x00 then raspberry pi knows this message is for itself\n length = bytes([serial_manager.num_nodes*3])\n REQUEST_TEENSY_IDS = b'\\x01'\n data_bytes = b''\n for teensy in range(serial_manager.num_nodes):\n data_bytes += serial_manager.teensy_ids_bytes[teensy]\n EOM = b'\\xfe\\xfe'\n raw_bytes = SOM + tid + length + REQUEST_TEENSY_IDS + data_bytes + EOM\n UDP_manager.send_bytes(raw_bytes)\n\nIP_LAPTOP = '10.14.4.198' # CHANGE THIS TO IP OF MASTER LAPTOP\nIP_LAPTOP = '10.14.4.178'\nPORT_RECEIVE = 4001 # receive input on this port\nPORT_SEND = 4000 # send output on this port\n\n# object for managing serial communication to and from each node\nprint(\"Waiting for Teensies to boot...\")\ntime.sleep(5)\nserial_manager = NodeSerial.NodeSerial()\n\n# object for managing UDP communication to and from master laptop\nUDP_manager = PiUDP.PiUDP(IP_LAPTOP, PORT_RECEIVE, PORT_SEND)\n\n# run forever\nwhile True:\n\n try:\n\n # check for serial message from nodes\n for i in range(serial_manager.num_nodes):\n code, data, tid, raw_bytes = serial_manager.checkIncomingMessageFromNode(i)\n if code != 'error':\n # if we get a message, pass it on to the laptop\n UDP_manager.send_bytes(raw_bytes)\n\n # check for UDP message from laptop\n try:\n # get a UDP packet from the queue\n # if the queue is empty it raises queue.Empty exception\n data_bytes = UDP_manager.data_bytes_queue.get(block = False)\n code, data, tid = UDP_manager.decode_bytes(data_bytes)\n if tid == 0:\n # A teensy ID of 0 indicates that this message is for the Pi itself\n if code == REQUEST_TEENSY_IDS:\n handle_REQUEST_TEENSY_IDS()\n \n else:\n # if the teensy ID is not zero this message is destined for a node\n # node_number = -1 indicates that the teensy ID in the UDP packet\n # is not recognized by this pi\n node_number = serial_manager.getNodeNumberFromId(tid)\n\n if node_number != -1:\n # if the teensy is on this Pi, send the bytes to the\n # appropriate node\n serial_manager.sendMessage(code, data, node_number)\n \n except queue.Empty:\n # there are no packets waiting in the queue\n pass\n\n # catch serial port errors\n except SerialException:\n print(\"SerialException, closing serial ports\")\n serial_manager.close()\n UDP_manager.close()\n break\n\n # catch serial port errors\n except IOError:\n print(\"IOError, closing serial ports\")\n serial_manager.close()\n UDP_manager.close()\n break\n \n # pressing ctrl-c closes the program\n except KeyboardInterrupt:\n print(\"Closing Main Program and Serial Ports\")\n serial_manager.close()\n UDP_manager.close()\n print(\"Completed, Goodbye!\")\n break\n\n \n \n\n \n \n \n\n\n\n"
},
{
"alpha_fraction": 0.7653866410255432,
"alphanum_fraction": 0.7743293046951294,
"avg_line_length": 64.55172729492188,
"blob_id": "84312e00edd5d020a6036ade7aa15d554d496489",
"content_id": "9843aa944a663bcb1e46ab922333d245c3526746",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1901,
"license_type": "no_license",
"max_line_length": 191,
"num_lines": 29,
"path": "/README.md",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "# 1531-ROM-Transforming-Space\n\nThis code has directly evolved from 17540-Luddy-Hall and contains references to that project.\n\n## Folders\n* Master Laptop: contains python code (.py) to run on the Master Laptop.\n* Raspberry Pi: contains python code (.py) to run on the Raspberry Pi.\n* Teensy: contains Arduino code (.ino, .h, .cpp) to compile and run on the Teensy.\n* Device Locator: contains python code (.py) that generates DeviceLocator.py from a specific .csv\n* Utilities: collection of python scripts that interact with the Master Laptop through OSC.\n\n## Simple Usage (See Basecamp for detailed instructions)\n1. Find and login to your desired Raspberry Pi. (SSH/NoMachine)\n2. If there are python scripts running, stop them.\n3. Open TyCommander with `sudo ` and upload the .hex file to each Teensy.\n2. Close TyCommander.\n2. Copy the whole Raspberry Pi folder to the Pi, and run `python3 LuddyPiSlave.py`.\n3. Copy the whole Master Laptop folder to the master laptop and run `LuddyLaptopMaster.py` with python3.\n\nOSC scripts should be run on the master laptop in a different window while LuddyLaptopMaster.py is running.\n\n## Troubleshooting\n\n* Do you have the correct IP addresses?\n* .hex file not loading on to the Teensy? Did you copy and paste the .hex file from this page? Make sure to open it in a text editor ensure that there is one blank line at the bottom.\n* Nodes not responding on TyCommander? Make sure to open it with `sudo`, and stop any running python scripts.\n* Raspberry Pi script can't find any nodes? Close TyCommander.\n* Raspberry Pi script seems to find devices but they are not a Teensy? If you stop a python script, restart (or upload to) the Teensies before starting the script again.\n* Raspberry Pi script finds nodes but then is spammed with \"SOM not found\" messages? Teensies have been on for a while without a python script running, restart them before starting the script\n"
},
{
"alpha_fraction": 0.6309785842895508,
"alphanum_fraction": 0.6464613080024719,
"avg_line_length": 33.52553939819336,
"blob_id": "493bb6e9124478681dcff7311a8e17a3c1215767",
"content_id": "0767b939912bc30772eeae096b7fe91311ffecf4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 30421,
"license_type": "no_license",
"max_line_length": 214,
"num_lines": 881,
"path": "/Archive/Teensy/LuddyNode/Behaviours.cpp",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "/*\n* Behaviours.cpp - Library for Behaviours\n* created By Adam Francey March 27, 2018\n* Released for Luddy Hall 2018\n* Philip Beesley Architect Inc. / Living Architecture Systems Group\n*/\n\n#include <Arduino.h>\n#include <stdint.h>\n#include \"Behaviours.h\"\n#include \"SMA.h\"\n#include <SoftPWM.h>\n\n//--------\n\nBehaviours::Behaviours(int input_frame_duration){\n // set frame duration\n frame_duration = input_frame_duration;\n\n // get current time for first frame\n current_millis = millis();\n\n // initial state of behaviour\n for (int i = 0; i < num_behaviours; i++){\n _behaviour_on[i] = false;\n _framecount[i] = 0;\n }\n\n // begin software PWM\n SoftPWMBegin(SOFTPWM_NORMAL);\n\n // set initial state of actuators\n for (uint8_t i = 0; i < max_pin_number + 1; i++){\n _previous_end_values_FADE_ACTUATOR_GROUP[i] = 0;\n }\n\n //initialize empty PWM value array\n for (uint8_t i = 0; i < max_pin_number + 1; i++){\n PWM_values_FADE_ACTUATOR_GROUP[i] = 0;\n PWM_values_SINE[i] = 0;\n PWM_values_EXCITOR[i] = 0;\n PWM_values_LIGHT_CHAIN[i] = 0;\n } \n\n}\n\nBehaviours::~Behaviours(){}\n\nvoid Behaviours::init_all_SMA(){\n if (my_type == device_locator.type_BP){\n uint8_t SMA_count = 0;\n for (int pin = 0; pin < device_locator.BP_pins_num; pin++){\n if (device_locator.BP_pins_types[pin] == device_locator.type_SMA){\n pinMode(device_locator.BP_pins[pin], OUTPUT);\n SMA_list[SMA_count].init_SMA(device_locator.BP_pins[pin]);\n SMA_count++;\n }\n }\n}\n \n}\n\n\n// Behaviour 0: TEST_LED_PIN\n// Blinks the on board LED\n\nvoid Behaviours::rand_light(){\n\n skip_size = skip_size + 1;\n if (skip_size == skip_millis){\n skip_size = 0;\n fcount = fcount+1*dir;\n }\n\n if (fcount > 200){\n dir = -1;\n }\n if (fcount <= 0){\n dir = 1;\n long r = rand()%6;\n\n if (r == 1){\n rand_pin = 9;\n }\n if (r == 2){\n rand_pin = 10;\n } else {\n rand_pin = 13;\n }\n skip_millis = skip_millis_default;\n force_pin = false;\n }\n\n if (force_pin){\n rand_pin = forced_pin;\n }\n\n SoftPWMSet(rand_pin, fcount);\n\n \n \n}\n\nvoid Behaviours::start_TEST_LED_PIN(uint8_t num_blinks){\n\n // initialize this behaviour\n _behaviour_on[_behaviour_TEST_LED_PIN] = true;\n _framecount[_behaviour_TEST_LED_PIN] = 0;\n\n // off for 100ms, on for 100ms = 200ms per blink\n // 200ms/frame_duration = number of frames per blink\n _behaviour_max_frames[_behaviour_TEST_LED_PIN] = num_blinks*200/frame_duration;\n\n _modifiers[_behaviour_TEST_LED_PIN] = num_blinks;\n\n\n}\n\nvoid Behaviours::_resume_TEST_LED_PIN(){\n uint8_t num_blinks = _modifiers[_behaviour_TEST_LED_PIN];\n int framecount = _framecount[_behaviour_TEST_LED_PIN];\n\n int milliseconds_since_behaviour_started = framecount*frame_duration;\n \n // oscillates between true and false, changes every 100 ms\n // starts true for first 100ms\n bool on = ((milliseconds_since_behaviour_started % 1000) % 200) < 100;\n\n // the actual behaviour\n if (on){\n SoftPWMSet(13, 50);\n } else {\n SoftPWMSet(13, 0); \n }\n\n // check to see if the behaviour is complete,\n // otherwise\n if (framecount >= _behaviour_max_frames[_behaviour_TEST_LED_PIN]){\n _behaviour_on[_behaviour_TEST_LED_PIN] = false;\n _framecount[_behaviour_TEST_LED_PIN] = 0;\n SoftPWMSet(13, 0); // turn off light (on stays true, assuming because of timing)\n } else {\n _framecount[_behaviour_TEST_LED_PIN]++;\n \n }\n \n}\n\n//--------------------------------------------------------------------------------------------------------------------------------------------------------------------\n// Behaviour 1: FADE_ACTUATOR_GROUP\n// Fades a group of actuators (could be only one)\n// to delay, give negative numbers as start values?\nvoid Behaviours::start_FADE_ACTUATOR_GROUP(uint8_t pins[], uint8_t end_values[], int fade_times[], uint8_t num_actuators){\n _behaviour_on[_behaviour_FADE_ACTUATOR_GROUP] = true;\n _framecount[_behaviour_FADE_ACTUATOR_GROUP] = 0;\n\n // get modifiers for behaviour\n int max_fade_time = 0;\n _num_actuators_FADE_ACTUATOR_GROUP = num_actuators;\n \n for (int actuator = 0; actuator < num_actuators; actuator++){\n uint8_t pin = pins[actuator];\n // set each behaviour modifier to the given input\n _start_values_FADE_ACTUATOR_GROUP[pin] = PWM_values_FADE_ACTUATOR_GROUP[pin];//_previous_end_values_FADE_ACTUATOR_GROUP[pin];\n _end_values_FADE_ACTUATOR_GROUP[pin] = end_values[actuator];\n _fade_times_FADE_ACTUATOR_GROUP[pin] = fade_times[actuator];\n \n uint8_t num_state_changes = abs(_end_values_FADE_ACTUATOR_GROUP[pin] - _start_values_FADE_ACTUATOR_GROUP[pin]) + 1;\n int num_frames_in_fade_time = fade_times[actuator]/frame_duration;\n _num_frames_to_skip_FADE_ACTUATOR_GROUP[pin] = num_frames_in_fade_time/num_state_changes;\n _num_total_frames_to_fade_FADE_ACTUATOR_GROUP[pin] = _num_frames_to_skip_FADE_ACTUATOR_GROUP[pin]*num_state_changes;\n _current_frame_FADE_ACTUATOR_GROUP[pin] = 0;\n // determine maximum fade time\n if (fade_times[actuator] > max_fade_time){\n max_fade_time = fade_times[actuator];\n _behaviour_max_frames[_behaviour_FADE_ACTUATOR_GROUP] = _num_frames_to_skip_FADE_ACTUATOR_GROUP[pin]*num_state_changes;\n \n }\n\n } \n \n\n}\n\n\nvoid Behaviours::_resume_FADE_ACTUATOR_GROUP(){\n int framecount = _framecount[_behaviour_FADE_ACTUATOR_GROUP];\n for (uint8_t pin = 0; pin < max_pin_number + 1; pin++){\n uint8_t start_value = _start_values_FADE_ACTUATOR_GROUP[pin];\n uint8_t end_value = _end_values_FADE_ACTUATOR_GROUP[pin];\n uint8_t num_frames_to_skip = _num_frames_to_skip_FADE_ACTUATOR_GROUP[pin];\n int num_total_frames_to_fade = _num_total_frames_to_fade_FADE_ACTUATOR_GROUP[pin];\n int current_frame = _current_frame_FADE_ACTUATOR_GROUP[pin];\n uint8_t PWM_value;\n\n if (current_frame < num_total_frames_to_fade){\n if (start_value <= end_value){\n // fading up\n PWM_value = start_value + current_frame/num_frames_to_skip;\n if (current_frame % num_frames_to_skip == 0 && PWM_value <= end_value){\n PWM_values_FADE_ACTUATOR_GROUP[pin] = PWM_value;\n }\n \n } else {\n // fading down\n PWM_value = start_value - current_frame/num_frames_to_skip;\n if (current_frame % num_frames_to_skip == 0 && PWM_value >= end_value){\n PWM_values_FADE_ACTUATOR_GROUP[pin] = PWM_value;\n }\n }\n _current_frame_FADE_ACTUATOR_GROUP[pin]++;\n } else {\n // fade is done on this pin\n // set each actuator to its ending value\n PWM_values_FADE_ACTUATOR_GROUP[pin] = _end_values_FADE_ACTUATOR_GROUP[pin];\n // store end values for next time\n _previous_end_values_FADE_ACTUATOR_GROUP[pin] = _end_values_FADE_ACTUATOR_GROUP[pin];\n }\n }\n}\n\n\nvoid Behaviours::start_SINE(uint8_t pins[], uint8_t frequencies[], uint8_t amplitudes[], uint8_t phases[], uint8_t num_actuators){\n _behaviour_on[_behaviour_SINE] = true;\n \n for (int actuator = 0; actuator < num_actuators; actuator++){\n uint8_t pin = pins[actuator];\n // set each behaviour modifier to the given input\n _frequencies_SINE[pin] = 2*float(frequencies[actuator])/255.0; // 0 - 255 -> changed to 5*freq/255.0 to get 0 - 5 Hz\n _amplitudes_SINE[pin] = 95.0*float(amplitudes[actuator])/255.0; // 0 - 255 -> changed to 95.0*amp/255.0 to get 0 to 95.0\n _phases_SINE[pin] = 2*3.14*float(phases[actuator])/255.0; // 0 - 255 -> changed to 2*pi*phase/255.0 to get 0 to 2pi\n } \n \n\n}\n\n\nvoid Behaviours::_resume_SINE(){\n\n // framecount will max out and start count up from -(2^31 - 1)\n if (_framecount[_behaviour_SINE] < 0){\n _framecount[_behaviour_SINE] = 0;\n }\n int framecount = _framecount[_behaviour_SINE];\n for (uint8_t pin = 0; pin < max_pin_number + 1; pin++){\n // want t to go from 0 to 1 in one second\n // 1000/frame_duration frames in second\n // framecount/(1000/frame_duration) goes from 0 to one in one second\n float t = float(framecount)/(1000.0/float(frame_duration));\n PWM_values_SINE[pin] = 95.0 - _amplitudes_SINE[pin]*sin(t*_frequencies_SINE[pin]*2.0*3.14 + _phases_SINE[pin]); \n }\n\n _framecount[_behaviour_SINE]++;\n}\n\nvoid Behaviours::start_IR_TRIGGER(int threshold_value1, int threshold_value2, int threshold_value3){\n _behaviour_on[_behaviour_IR_TRIGGER] = true;\n _framecount[_behaviour_IR_TRIGGER] = 0;\n\n IR_threshold[0] = threshold_value1;\n IR_threshold[1] = threshold_value2;\n IR_threshold[2] = threshold_value3;\n\n _behaviour_max_frames[_behaviour_IR_TRIGGER] = 0;\n\n \n}\n\nvoid Behaviours::_resume_IR_TRIGGER(){\n for (uint8_t sensor = 0; sensor < my_num_IR_sensors; sensor++){\n int IR_val = analogRead(IR_pins[sensor]);\n IR_vals[sensor] = IR_val;\n long elapsed_millis_since_last_trigger = millis() - IR_last_trigger_time[sensor];\n if (IR_val >= IR_threshold[sensor] && (elapsed_millis_since_last_trigger >= IR_min_time_between_triggers || elapsed_millis_since_last_trigger < 0)){\n // we check for elapsed_millis_since_last_trigger < 0 because millis() will max out and roll over to 0\n // about every 50 days, which may cause elapsed_millis to be negative\n IR_triggered[sensor] = true;\n IR_last_trigger_time[sensor] = millis();\n }\n }\n}\n\nvoid Behaviours::start_IR_SAMPLING(uint8_t on_or_off, int sampling_interval){\n if (on_or_off == 1){\n _behaviour_on[_behaviour_IR_SAMPLING] = true;\n IR_sample_interval = sampling_interval;\n } else {\n _behaviour_on[_behaviour_IR_SAMPLING] = false;\n }\n \n _framecount[_behaviour_IR_SAMPLING] = 0;\n _behaviour_max_frames[_behaviour_IR_SAMPLING] = 0;\n \n}\n\nvoid Behaviours::_resume_IR_SAMPLING(){\n long elapsed_time_since_last_sample = millis() - IR_last_sample_time;\n if (elapsed_time_since_last_sample > IR_sample_interval || elapsed_time_since_last_sample < 0){\n for (uint8_t ir = 0; ir < my_num_IR_sensors; ir++){\n IR_sampled_vals[ir] = analogRead(IR_pins[ir]);\n }\n IR_new_sample = true;\n IR_last_sample_time = millis();\n }\n}\n\n/*\nvoid Behaviours::start_IR_REACTION_BP(){\n \n}\n*/\n\nvoid Behaviours::start_RANDOM_ACTUATOR(uint8_t prob, int ramp_up_time, int hold_time, int ramp_down_time, int cooldown_time){\n _behaviour_on[_behaviour_RANDOM_ACTUATOR] = true;\n prob_RANDOM_ACTUATOR = prob;\n if (my_type == device_locator.type_BP){\n prob_RANDOM_ACTUATOR = 40;\n }\n ramp_up_time_RANDOM_ACTUATOR = ramp_up_time;\n hold_time_RANDOM_ACTUATOR = hold_time;\n ramp_down_time_RANDOM_ACTUATOR = ramp_down_time;\n cooldown_time_RANDOM_ACTUATOR = cooldown_time; \n}\n\nvoid Behaviours::_resume_RANDOM_ACTUATOR(){\n\n // check if we are cooling down\n if (stage_RANDOM_ACTUATOR == dormant_stage_RANDOM_ACTUATOR && millis() - millis_of_last_attempt_RANDOM_ACTUATOR > cooldown_time_RANDOM_ACTUATOR){\n millis_of_last_attempt_RANDOM_ACTUATOR = millis();\n\n // pick random number\n long r = random(0, 100);\n\n // if we exceed probability threshold, pick random actuator and start ramp_up\n if (r < prob_RANDOM_ACTUATOR){\n long random_pin_index = random(0, my_num_pins);\n uint8_t type = my_pins_types[random_pin_index];\n uint8_t pin = my_pins[random_pin_index];\n active_pin_RANDOM_ACTUATOR = pin;\n active_pin_type_RANDOM_ACTUATOR = type;\n if (type == device_locator.type_LED || type == device_locator.type_moth){\n uint8_t pins[1] = {pin};\n uint8_t end_val[1] = {max_brightness_RANDOM_ACTUATOR};\n int fade_time[1] = {ramp_up_time_RANDOM_ACTUATOR};\n uint8_t num_actuators = 1;\n start_FADE_ACTUATOR_GROUP(pins, end_val, fade_time, num_actuators);\n }\n stage_RANDOM_ACTUATOR = ramp_up_stage_RANDOM_ACTUATOR;\n actuation_start_time_RANDOM_ACTUATOR = millis();\n }\n } else if (stage_RANDOM_ACTUATOR == ramp_up_stage_RANDOM_ACTUATOR && millis() - actuation_start_time_RANDOM_ACTUATOR > ramp_up_time_RANDOM_ACTUATOR){\n stage_RANDOM_ACTUATOR = hold_stage_RANDOM_ACTUATOR;\n } else if (stage_RANDOM_ACTUATOR == hold_stage_RANDOM_ACTUATOR && millis() - actuation_start_time_RANDOM_ACTUATOR > ramp_up_time_RANDOM_ACTUATOR + hold_time_RANDOM_ACTUATOR){\n if (active_pin_type_RANDOM_ACTUATOR == device_locator.type_LED || active_pin_type_RANDOM_ACTUATOR == device_locator.type_moth){ \n uint8_t pins[1] = {active_pin_RANDOM_ACTUATOR};\n uint8_t end_val[1] = {0};\n int fade_time[1] = {ramp_down_time_RANDOM_ACTUATOR};\n uint8_t num_actuators = 1;\n start_FADE_ACTUATOR_GROUP(pins, end_val, fade_time, num_actuators);\n }\n stage_RANDOM_ACTUATOR = ramp_down_stage_RANDOM_ACTUATOR;\n } else if (stage_RANDOM_ACTUATOR == ramp_down_stage_RANDOM_ACTUATOR && millis() - actuation_start_time_RANDOM_ACTUATOR > ramp_up_time_RANDOM_ACTUATOR + hold_time_RANDOM_ACTUATOR + ramp_down_time_RANDOM_ACTUATOR){\n stage_RANDOM_ACTUATOR = dormant_stage_RANDOM_ACTUATOR;\n }\n \n}\n\n\nvoid Behaviours::start_DELAYED_FADE_ACTUATOR_GROUP_one_pin(int wait_time, uint8_t pin, uint8_t end_value, int fade_time){\n int wait_frames = wait_time/frame_duration;\n int count = 0;\n bool found_open_slot = false;\n while (found_open_slot == false && count < num_DELAYED_FADE_ACTUATOR_GROUP){\n if (waiting_frames_DELAYED_FADE_ACTUATOR_GROUP[count] == -1){\n found_open_slot = true;\n waiting_frames_DELAYED_FADE_ACTUATOR_GROUP[count] = wait_frames;\n pins_DELAYED_FADE_ACTUATOR_GROUP[count] = pin;\n end_values_DELAYED_FADE_ACTUATOR_GROUP[count] = end_value;\n fade_times_DELAYED_FADE_ACTUATOR_GROUP[count] = fade_time;\n }\n count++;\n }\n \n}\n\nvoid Behaviours::_resume_DELAYED_FADE_ACTUATOR_GROUP_one_pin(){\n\n for (int i = 0; i < num_DELAYED_FADE_ACTUATOR_GROUP; i++){\n if (waiting_frames_DELAYED_FADE_ACTUATOR_GROUP[i] == 0){\n uint8_t pins[1] = {pins_DELAYED_FADE_ACTUATOR_GROUP[i]};\n uint8_t end_values[1] = {end_values_DELAYED_FADE_ACTUATOR_GROUP[i]};\n int fade_times[1] = {fade_times_DELAYED_FADE_ACTUATOR_GROUP[i]};\n uint8_t num_actuators = 1;\n start_FADE_ACTUATOR_GROUP(pins,end_values,fade_times,num_actuators);\n waiting_frames_DELAYED_FADE_ACTUATOR_GROUP[i] = -1;\n } else if (waiting_frames_DELAYED_FADE_ACTUATOR_GROUP[i] > 0){\n waiting_frames_DELAYED_FADE_ACTUATOR_GROUP[i]--;\n }\n }\n \n}\n\n\nvoid Behaviours::start_DELAYED_one_pin_SMA(int wait_time, uint8_t pin_index){\n int wait_frames = wait_time/frame_duration;\n int count = 0;\n bool found_open_slot = false;\n while (found_open_slot == false && count < num_DELAYED_FADE_ACTUATOR_GROUP){\n if (waiting_frames_DELAYED_SMA[count] == -1){\n found_open_slot = true;\n waiting_frames_DELAYED_SMA[count] = wait_frames;\n pins_DELAYED_SMA[count] = pin_index;\n }\n count++;\n }\n \n}\n\nvoid Behaviours::_resume_DELAYED_one_pin_SMA(){\n for (int i = 0; i < num_DELAYED_SMA; i++){\n if (waiting_frames_DELAYED_SMA[i] == 0){\n uint8_t pins = pins_DELAYED_SMA[i];\n SMA_list[pins].actuate_if_ready();\n Serial.println(pins);\n waiting_frames_DELAYED_SMA[i] = -1;\n } else if (waiting_frames_DELAYED_SMA[i] > 0){\n waiting_frames_DELAYED_SMA[i]--;\n }\n }\n \n}\n\nvoid Behaviours::start_LOCAL_IR_REACTION(uint8_t RS_pins[], uint8_t num_RS, uint8_t moth_pins[], uint8_t num_moth){\n _behaviour_on[_behaviour_LOCAL_IR_REACTION] = true;\n _framecount[_behaviour_LOCAL_IR_REACTION] = 0;\n\n _num_RS_LOCAL_IR_REACTION = num_RS;\n for (uint8_t rs = 0; rs < num_RS; rs++){\n _pins_RS_LOCAL_IR_REACTION[rs] = RS_pins[rs];\n }\n\n _num_moth_LOCAL_IR_REACTION = num_moth;\n for (uint8_t moth = 0; moth < num_moth; moth++){\n _pins_moth_LOCAL_IR_REACTION[moth] = moth_pins[moth];\n }\n\n\n _behaviour_max_frames[_behaviour_LOCAL_IR_REACTION] = 0;\n \n}\n\nvoid Behaviours::_resume_LOCAL_IR_REACTION(){\n\n uint8_t num_RS_per_IR = _num_RS_LOCAL_IR_REACTION/my_num_IR_sensors;\n for (uint8_t ir = 0; ir < my_num_IR_sensors; ir++){\n uint8_t ir_val = IR_vals[ir];\n for (uint8_t rs = 0; rs < num_RS_per_IR; rs++){\n uint8_t pin = _pins_RS_LOCAL_IR_REACTION[ir*num_RS_per_IR + rs]; \n PWM_values_LOCAL_IR_REACTION[pin] = MAX_PWM_VALUE_FOR_ALL*ir_val/1024; // 1024 is max IR sensor val\n }\n }\n \n}\n\nvoid Behaviours::_resume_excitor(){\n \n if (my_type == device_locator.type_SU){\n for (int act = 0; act < device_locator.SU_pins_num; act++){\n uint8_t act_pin = device_locator.SU_pins[act];\n uint8_t act_type = device_locator.SU_pins_types[act];\n if (act_type == device_locator.type_LED || act_type == device_locator.type_moth){\n int act_x = device_locator.coordinates[my_index][act][0];\n int act_y = device_locator.coordinates[my_index][act][1];\n int act_z = device_locator.coordinates[my_index][act][2];\n \n int64_t norm = (int64_t)sqrt(sq((int64_t)(_excitor_pos[0] - act_x)) + sq((int64_t)(_excitor_pos[1] - act_y)) + sq((int64_t)(_excitor_pos[2] - act_z)));\n\n int force;\n if (act_type == device_locator.type_LED){\n force = _excitor_force_RS;\n } else {\n force = _excitor_force_moth;\n }\n if (_excitor_radius - norm < 0){\n PWM_values_EXCITOR[act_pin] = 0;\n } else {\n PWM_values_EXCITOR[act_pin] = (uint8_t)force*abs((_excitor_radius-norm))/_excitor_radius;\n }\n }\n \n }\n }\n \n}\n\nvoid Behaviours::start_BP_IR_trigger_reflex(uint8_t ir_index){\n int RS_time_offset = ramp_up_time_BP_moth;\n int max_SMA = 6;\n uint8_t fade_val = 200;\n uint8_t moth_pin;\n uint8_t RS_pin;\n if (ir_index == 0){\n moth_pin = 9;\n RS_pin = 22;\n } else if (ir_index == 1){\n moth_pin = 10;\n RS_pin = 23;\n }\n start_DELAYED_FADE_ACTUATOR_GROUP_one_pin(0, moth_pin, fade_val, ramp_up_time_BP_moth);\n start_DELAYED_FADE_ACTUATOR_GROUP_one_pin(RS_time_offset, RS_pin, fade_val, ramp_up_time_BP_RS);\n\n start_DELAYED_FADE_ACTUATOR_GROUP_one_pin(ramp_up_time_BP_moth + hold_time_BP_moth, moth_pin, 0, ramp_down_time_BP_moth);\n start_DELAYED_FADE_ACTUATOR_GROUP_one_pin(RS_time_offset + ramp_up_time_BP_RS + hold_time_BP_RS, RS_pin, 0, ramp_down_time_BP_RS);\n \n for(int i=max_SMA*ir_index; i<max_SMA+max_SMA*ir_index; i++)\n start_DELAYED_one_pin_SMA(700*(i - max_SMA*ir_index), i);\n}\n\nvoid Behaviours::start_LIGHT_CHAIN(int act_time, float variance, float chain_width){\n\n _behaviour_on[_behaviour_LIGHT_CHAIN] = true;\n LC_trigger_index++;\n LC_trigger_index = LC_trigger_index % max_LC_triggers;\n if (LC_trigger_on[LC_trigger_index] == false){\n LC_frame_count[LC_trigger_index] = 0;\n LC_trigger_on[LC_trigger_index] = true;\n chain_time_LIGHT_CHAIN[LC_trigger_index] = act_time;//ms\n chain_width_LIGHT_CHAIN[LC_trigger_index] = chain_width;\n variances_LIGHT_CHAIN[LC_trigger_index] = variance; \n }\n\n}\n\nvoid Behaviours::_resume_LIGHT_CHAIN(){\n\n int dir = -1;\n int num_lights = 12;\n float range_offset[max_LC_triggers];\n float width_per_frame[max_LC_triggers];\n int frame_offset_per_actuator[max_LC_triggers];\n int num_frames[max_LC_triggers];\n\n for (int i = 0; i< max_LC_triggers; i++){\n int act_time = chain_time_LIGHT_CHAIN[i];\n float unscaled_chain_width = chain_width_LIGHT_CHAIN[i];\n float variance = variances_LIGHT_CHAIN[i]; \n num_frames[i] = int(float(act_time)/float(frame_duration));\n \n range_offset[i] = sqrt(11.0825*variance); // interval of non-zero values: [-range_offset, range_offset]\n // see Adam's notebook for calculation\n float chain_width = unscaled_chain_width*2*range_offset[i]; //scale to curve size\n \n float total_width = 2*range_offset[i] + chain_width;\n width_per_frame[i] = total_width/float(num_frames[i]);\n float width_between_actuators = chain_width/float(num_lights);\n frame_offset_per_actuator[i] = int(width_between_actuators/width_per_frame[i]);\n }\n\n\n\n uint8_t LED_count = 0;\n\n // for each pin, determine PWM value\n for (int pin_index = 0; pin_index < num_lights; pin_index++){\n uint8_t pin = my_pins[pin_index];\n\n // if we are going in opposite direction, mirror the lights\n if (dir == -1){\n pin = my_pins[num_lights - 1 - pin_index];\n }\n\n int max_PWM_val = 0;\n\n // cycle through possible triggers\n for (int trig = 0; trig < max_LC_triggers; trig++){\n if (LC_trigger_on[trig]){\n float x_val = -range_offset[trig] + width_per_frame[trig]*(LC_frame_count[trig] - frame_offset_per_actuator[trig]*LED_count);\n int PWM_val = int(255*(exp(pow(x_val,2)/float(-2.0*variances_LIGHT_CHAIN[trig]))));\n if (PWM_val > max_PWM_val){\n max_PWM_val = PWM_val;\n }\n }\n }\n \n if (my_pins_types[pin_index] == device_locator.type_LED){\n PWM_values_LIGHT_CHAIN[pin] = max_PWM_val;\n LED_count++;\n }\n \n }\n\n for (int index = 0; index < max_LC_triggers; index++){\n if (LC_frame_count[index] >= num_frames[index]){\n LC_trigger_on[index] = false;\n } else {\n LC_frame_count[index]++;\n }\n }\n \n}\n\n\nvoid Behaviours::start_AUTO_LIGHT_CHAIN(int act_time, float variance, float chain_width){\n\n _behaviour_on[_behaviour_AUTO_LIGHT_CHAIN] = true;\n LC_trigger_index_AUTO_LIGHT_CHAIN++;\n LC_trigger_index_AUTO_LIGHT_CHAIN = LC_trigger_index_AUTO_LIGHT_CHAIN % max_LC_triggers_AUTO_LIGHT_CHAIN;\n if (LC_trigger_on_AUTO_LIGHT_CHAIN[LC_trigger_index_AUTO_LIGHT_CHAIN] == false){\n LC_frame_count_AUTO_LIGHT_CHAIN[LC_trigger_index_AUTO_LIGHT_CHAIN] = 0;\n LC_trigger_on_AUTO_LIGHT_CHAIN[LC_trigger_index_AUTO_LIGHT_CHAIN] = true;\n chain_time_AUTO_LIGHT_CHAIN[LC_trigger_index_AUTO_LIGHT_CHAIN] = act_time;//ms\n chain_width_AUTO_LIGHT_CHAIN[LC_trigger_index_AUTO_LIGHT_CHAIN] = chain_width;\n variances_AUTO_LIGHT_CHAIN[LC_trigger_index_AUTO_LIGHT_CHAIN] = variance; \n }\n\n}\n\nvoid Behaviours::_resume_AUTO_LIGHT_CHAIN(){\n\n int dir = 1;\n int num_lights = 6;\n float range_offset[max_LC_triggers_AUTO_LIGHT_CHAIN];\n float width_per_frame[max_LC_triggers_AUTO_LIGHT_CHAIN];\n int frame_offset_per_actuator[max_LC_triggers_AUTO_LIGHT_CHAIN];\n int num_frames[max_LC_triggers_AUTO_LIGHT_CHAIN];\n\n for (int i = 0; i< max_LC_triggers_AUTO_LIGHT_CHAIN; i++){\n int act_time = chain_time_AUTO_LIGHT_CHAIN[i];\n float unscaled_chain_width = chain_width_AUTO_LIGHT_CHAIN[i];\n float variance = variances_AUTO_LIGHT_CHAIN[i]; \n num_frames[i] = int(float(act_time)/float(frame_duration));\n \n range_offset[i] = sqrt(11.0825*variance); // interval of non-zero values: [-range_offset, range_offset]\n // see Adam's notebook for calculation\n float chain_width = unscaled_chain_width*2*range_offset[i]; //scale to curve size\n \n float total_width = 2*range_offset[i] + chain_width;\n width_per_frame[i] = total_width/float(num_frames[i]);\n float width_between_actuators = chain_width/float(num_lights);\n frame_offset_per_actuator[i] = int(width_between_actuators/width_per_frame[i]);\n }\n\n\n\n uint8_t LED_count = 0;\n\n // for each pin, determine PWM value\n for (int pin_index = 12; pin_index < 12 + num_lights; pin_index++){\n uint8_t pin = my_pins[pin_index];\n\n // if we are going in opposite direction, mirror the lights\n if (dir == -1){\n pin = my_pins[num_lights - 1 - pin_index];\n }\n\n int max_PWM_val = 0;\n\n // cycle through possible triggers\n for (int trig = 0; trig < max_LC_triggers_AUTO_LIGHT_CHAIN; trig++){\n if (LC_trigger_on_AUTO_LIGHT_CHAIN[trig]){\n float x_val = -range_offset[trig] + width_per_frame[trig]*(LC_frame_count_AUTO_LIGHT_CHAIN[trig] - frame_offset_per_actuator[trig]*LED_count);\n int PWM_val = int(255*(exp(pow(x_val,2)/float(-2.0*variances_AUTO_LIGHT_CHAIN[trig]))));\n if (PWM_val > max_PWM_val){\n max_PWM_val = PWM_val;\n }\n }\n }\n \n if (my_pins_types[pin_index] == device_locator.type_LED){\n PWM_values_AUTO_LIGHT_CHAIN[pin] = max_PWM_val;\n LED_count++;\n }\n \n }\n\n for (int index = 0; index < max_LC_triggers_AUTO_LIGHT_CHAIN; index++){\n if (LC_frame_count_AUTO_LIGHT_CHAIN[index] == num_frames[index] + time_between_auto_and_column_IR_REACTION_LIGHT_COLUMN/frame_duration){\n start_LIGHT_CHAIN(local_trigger_act_time,local_trigger_variance,local_trigger_chain_width);\n }\n if (LC_frame_count_AUTO_LIGHT_CHAIN[index] >= num_frames[index]){\n LC_trigger_on_AUTO_LIGHT_CHAIN[index] = false;\n } else {\n LC_frame_count_AUTO_LIGHT_CHAIN[index]++;\n }\n }\n \n}\n\nvoid Behaviours::start_IR_REACTION_LIGHT_COLUMN(){\n _behaviour_on[_behaviour_IR_REACTION_LIGHT_COLUMN] = true;\n _framecount[_behaviour_IR_REACTION_LIGHT_COLUMN] = 0;\n}\n\nvoid Behaviours::_resume_IR_REACTION_LIGHT_COLUMN(){\n if (_framecount[_behaviour_IR_REACTION_LIGHT_COLUMN] == 0){\n start_AUTO_LIGHT_CHAIN(local_trigger_act_time_AUTO,local_trigger_variance,local_trigger_chain_width);\n }\n\n //if (_framecount[_behaviour_IR_REACTION_LIGHT_COLUMN] == int(float(local_trigger_act_time_AUTO)/float(frame_duration)) + time_between_auto_and_column_IR_REACTION_LIGHT_COLUMN/frame_duration){\n // start_LIGHT_CHAIN(local_trigger_act_time,local_trigger_variance,local_trigger_chain_width);\n //}\n\n if (_framecount[_behaviour_IR_REACTION_LIGHT_COLUMN] == int(float(local_trigger_act_time+local_trigger_act_time_AUTO)/float(frame_duration))){\n _behaviour_on[_behaviour_IR_REACTION_LIGHT_COLUMN] = false;\n }\n \n _framecount[_behaviour_IR_REACTION_LIGHT_COLUMN]++;\n \n}\n\nvoid Behaviours::start_LIGHT_CHAIN_BACKGROUND(){\n _behaviour_on[_behaviour_LIGHT_CHAIN_BACKGROUND] = true;\n _framecount[_behaviour_LIGHT_CHAIN_BACKGROUND] = 0;\n}\n\nvoid Behaviours::_resume_LIGHT_CHAIN_BACKGROUND(){\n int act_offset_BACKGROUND = 0;\n int offset_step_BACKGROUND = 25;\n int num_frames_BACKGROUND = 2000;\n float variance_BACKGROUND = 0.001;\n \n for (int pin_index = 0; pin_index < my_num_pins/2; pin_index++){\n uint8_t pin = my_pins[pin_index];\n uint8_t pin1= my_pins[11-pin_index];\n float x_val = float(6)*float(_framecount[_behaviour_LIGHT_CHAIN_BACKGROUND] + act_offset_BACKGROUND)/float(num_frames_BACKGROUND) - float(3);\n int PWM_val = int(255*(exp(pow(x_val,2)/float(-2*variance_BACKGROUND))));\n if (my_pins_types[pin_index] == device_locator.type_LED){\n PWM_values_LIGHT_CHAIN_BACKGROUND[pin] = PWM_val;\n PWM_values_LIGHT_CHAIN_BACKGROUND[pin1] = PWM_val;\n act_offset_BACKGROUND = act_offset_BACKGROUND + offset_step_BACKGROUND;\n }\n }\n \n if (_framecount[_behaviour_LIGHT_CHAIN_BACKGROUND] >= num_frames_BACKGROUND){\n _behaviour_on[_behaviour_LIGHT_CHAIN_BACKGROUND] = false;\n } else {\n _framecount[_behaviour_LIGHT_CHAIN_BACKGROUND]++;\n } \n\n \n}\n\n\n\nvoid Behaviours::merge_PWM_values_and_set_actuators(){\n\n // for each behaviour that sets an actuator, determine the max value and set pin\n for (uint8_t i = 0; i < my_num_pins; i++){\n uint8_t pin = my_pins[i];\n uint8_t value_FADE_ACTUATOR_GROUP = PWM_values_FADE_ACTUATOR_GROUP[pin];\n uint8_t value_RANDOM_ACTUATOR = PWM_values_RANDOM_ACTUATOR[pin];\n uint8_t value_LOCAL_IR_REACTION = PWM_values_LOCAL_IR_REACTION[pin];\n uint8_t value_SINE = PWM_values_SINE[pin];\n uint8_t value_excitor = PWM_values_EXCITOR[pin];\n uint8_t value_LIGHT_CHAIN = PWM_values_LIGHT_CHAIN[pin];\n uint8_t value_LIGHT_CHAIN_BACKGROUND = PWM_values_LIGHT_CHAIN_BACKGROUND[pin];\n uint8_t value_AUTO_LIGHT_CHAIN = PWM_values_AUTO_LIGHT_CHAIN[pin];\n uint8_t some_other_val = 0;\n\n uint8_t max_val = max(value_FADE_ACTUATOR_GROUP, value_RANDOM_ACTUATOR);\n max_val = max(max_val, value_LOCAL_IR_REACTION);\n max_val = max(max_val, value_SINE);\n max_val = max(max_val, value_excitor);\n max_val = max(max_val, value_LIGHT_CHAIN);\n max_val = max(max_val, value_LIGHT_CHAIN_BACKGROUND);\n max_val = max(max_val, value_AUTO_LIGHT_CHAIN);\n max_val = max(max_val, some_other_val);\n // keep adding more max statements for each type of setter\n\n uint8_t type = my_pins_types[i];\n if (type != device_locator.type_SMA && type != device_locator.type_IR){\n safe_write(pin, max_val, type);\n }\n }\n}\n\nvoid Behaviours::loop(){\n elapsed_millis = millis() - current_millis;\n if (elapsed_millis >= frame_duration || elapsed_millis < 0){\n //long cur = millis();\n current_millis = millis(); // record time of frame beginning\n\n // we check for elapsed_millis < 0 because millis() will max out and roll over to 0\n // about every 50 days, which may cause elapsed_millis to be negative\n if (_behaviour_on[_behaviour_TEST_LED_PIN]){\n _resume_TEST_LED_PIN();\n }\n if (_behaviour_on[_behaviour_FADE_ACTUATOR_GROUP]){\n _resume_FADE_ACTUATOR_GROUP();\n }\n if (_behaviour_on[_behaviour_IR_TRIGGER]){\n _resume_IR_TRIGGER();\n }\n if (_behaviour_on[_behaviour_IR_SAMPLING]){\n _resume_IR_SAMPLING();\n }\n\n if (_behaviour_on[_behaviour_RANDOM_ACTUATOR]){\n _resume_RANDOM_ACTUATOR();\n }\n\n if (_behaviour_on[_behaviour_LOCAL_IR_REACTION]){\n _resume_LOCAL_IR_REACTION();\n }\n \n if (_behaviour_on[_behaviour_SINE]){\n _resume_SINE();\n \n }\n \n if (_behaviour_on[_behaviour_EXCITOR]){\n _resume_excitor();\n }\n\n if (_behaviour_on[_behaviour_LIGHT_CHAIN]){\n _resume_LIGHT_CHAIN();\n }\n\n if (_behaviour_on[_behaviour_AUTO_LIGHT_CHAIN]){\n _resume_AUTO_LIGHT_CHAIN();\n }\n \n if (_behaviour_on[_behaviour_LIGHT_CHAIN_BACKGROUND]){\n _resume_LIGHT_CHAIN_BACKGROUND();\n }\n\n if (_behaviour_on[_behaviour_IR_REACTION_LIGHT_COLUMN]){\n _resume_IR_REACTION_LIGHT_COLUMN();\n }\n \n\n \n// if(do_BP_IR_trigger_SMA)\n// {\n// _resume_BP_IR_trigger_SMA();\n// }\n\n // always do this one\n _resume_DELAYED_FADE_ACTUATOR_GROUP_one_pin();\n\n _resume_DELAYED_one_pin_SMA();\n\n if (my_type == device_locator.type_BP && false){\n rand_light();\n }\n \n for (int sma_num = 0; sma_num < max_SMA; sma_num++){\n SMA_list[sma_num].loop();\n }\n\n // TEST\n \n // we always set actuator values regardless of active behaviours\n merge_PWM_values_and_set_actuators();\n\n //Serial.print(\"loop time: \");\n //Serial.println(millis() - cur);\n }\n\n}\n\nvoid Behaviours::safe_write(uint8_t pin, uint8_t val, uint8_t type){\n uint8_t maximum_PWM = MAX_PWM_VALUE_FOR_ALL;\n if (type == device_locator.type_moth){\n maximum_PWM = MAX_PWM_VALUE_FOR_MOTH;\n }\n\n if (val < maximum_PWM + 1){\n SoftPWMSet(pin, val);\n } else {\n SoftPWMSet(pin, maximum_PWM);\n }\n}\n\nvoid Behaviours::safe_write_ROM(uint8_t pin, uint8_t val){\n if (val < 190 + 1){\n SoftPWMSet(pin,val);\n } else {\n SoftPWMSet(pin,190);\n }\n}\n\n\n\n\n"
},
{
"alpha_fraction": 0.5089687705039978,
"alphanum_fraction": 0.5163403749465942,
"avg_line_length": 39.56146240234375,
"blob_id": "f64e07db89a1f3aabb3715ffb1f535731b3fb9e6",
"content_id": "9265cca1cb4308a5f104b65c81ead4b968760e74",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 12209,
"license_type": "no_license",
"max_line_length": 140,
"num_lines": 301,
"path": "/Raspberry Pi/NodeSerial.py",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "# NodeSerial.py - LASG/PBAI\n# Created by Kevin Lam\n# Updated by Adam Francey March 16 2018\n# Handles serial connection and communication between Raspberry Pi and Node\n\nimport serial\nfrom serial import SerialException\nimport time\n\nclass NodeSerial():\n\n def __init__(self):\n\n # num_nodes: number of nodes expected to be attached\n self.num_nodes = 0\n self.num_nodes_max = 10\n\n #Initialized Serial Comm Locations, To Be Rearranged Later\n self.node_addresses = ['']*self.num_nodes_max\n\n #Teensy ID's in Physical Locations\n self.teensy_ids = [0]*self.num_nodes_max\n self.teensy_ids_bytes = [b'\\x00\\x00\\x00']*self.num_nodes_max\n\n # list of serial ports\n self.serial_list = [None]*self.num_nodes_max\n\n # SOM (Start Of Message)\n # EOM (End Of Message)\n # this means that bytes 0xfe and 0xff\n # are OFF LIMITS for any other purpose!\n self.SOM = b'\\xff\\xff' # beginning of every message\n self.EOM = b'\\xfe\\xfe' # ending of every message\n self.padding_byte = b'\\xfd'\n\n # fixed message length\n self.message_length = 25\n\n # password sent by node\n self.password = b'\\xff\\xff\\x04\\x00\\x00\\x01\\xfe\\xfe'\n\n # NOTE on bytes objects\n # example\n # byte_sequence = b'\\xff\\xfe\\xfc'\n # byte_sequence[i] = integer (ie byte_sequence[0] = 255)\n # byte_sequence[i:i+1] = bytes object (ie byte_sequence[0:1] = b'\\xff')\n \n self.baud_rate = 57600\n\n # register all port before initializing\n self.registerSerialPorts()\n\n def registerSerialPorts(self):\n \n # searches serial ports to find attached nodes\n # constructs self.node_addresses and self.serial_list\n\n prefix = '/dev/ttyACM' # linux serial port prefix, append integer for address\n #prefix = 'COM' # windows serial port prefix, append integer for address\n port_max = 200 # maximum number of ports to check\n port_timeout_limit = 2 # wait time in seconds to receive password from Teensy\n \n print(\"Beginning serial port registration\")\n print(\"Looking for a maximum of \" + str(self.num_nodes_max) + \" nodes\")\n\n # find all nodes\n port_number = 0\n last_address_found = ''\n last_port_found = None\n num_registered_nodes = 0\n for node in range(self.num_nodes_max):\n print(\"Looking for node \" + str(node))\n\n # try to open serial ports until a node is found\n teensy_found = False\n while teensy_found == False and port_number <= port_max:\n\n try:\n # try to open port\n # the try block will exit after this line if a serial device is not found\n ser = serial.Serial(prefix + str(port_number), self.baud_rate, write_timeout = 2)\n\n print(\"Serial device found on \" + prefix + str(port_number) + \": \", end = '')\n \n PASSWORD = b'\\xaa'\n self.node_addresses[node] = prefix + str(port_number)\n self.serial_list[node] = ser\n\n time.sleep(1)\n\n #if (port_number> 50):\n try:\n self.sendMessage(PASSWORD, [4,5], num_registered_nodes)\n password_received = False\n timed_out = False\n start_time = time.time()\n while password_received == False and not timed_out:\n code, data, tid, raw_bytes = self.checkIncomingMessageFromNode(num_registered_nodes)\n if code == PASSWORD:\n password_received = True\n teensy_found = True\n print(\"Teensy Detected\")\n #print(tid)\n #print(raw_bytes)\n self.teensy_ids_bytes[num_registered_nodes] = raw_bytes[2:5]\n self.teensy_ids[num_registered_nodes] = tid\n num_registered_nodes += 1 \n\n if time.time() - start_time > port_timeout_limit:\n\n timed_out = True\n ser.close()\n print(\"Not a Teensy (response time out)\")\n except serial.SerialTimeoutException:\n print(\"Not a teensy (write time out)\")\n \n \n except SerialException:\n # there is no serial device on this port\n # do nothing\n pass\n\n port_number += 1\n\n if port_number >=port_max:\n # otherwise, we have hit port max, stop looking for nodes\n print(\"Port maximum (\" + str(port_max) + \") reached: \" + str(port_number>=port_max))\n break\n\n # print out info for registered nodes\n self.num_nodes = num_registered_nodes\n print(\"Serial registration complete: \" + str(num_registered_nodes) + \" nodes found\")\n for node in range(num_registered_nodes):\n print(\"Node: \" + str(node) + \" - Address: \" + self.node_addresses[node] +\n \" - ID: \" + str(self.teensy_ids[node]) + \" (\" + str(self.teensy_ids_bytes[node]) + \")\")\n\n def waitUntilSerialPortsOpen(self):\n # DEPRECATED ---------------------------------------------------------------\n # only continue once we are able to open all serial ports\n print(\"Attempting to open serial ports...\")\n while True:\n try:\n for i in range(len(self.serial_list)):\n self.serial_list[i] = serial.Serial(self.node_addresses[i],self.baud_rate)\n self.serial_list[i].flush()\n self.serial_list[i].flushInput()\n break # if we are able to open all, break out of loop\n\n # catch the exception, wait one second before trying again\n except SerialException:\n time.sleep(1)\n print(\"Serial Ports Opened Sucessfully\")\n\n def rearrangeSerialPorts(self):\n # NEEDS TO BE UPDATED -------------------------------------------------------------\n for i in range(len(self.serial_list)):\n sendMessage(INSTRUCT_CODE_GET_TEENSY_ID)\n code, tid = checkIncomingMessageFromNode(i)\n\n def checkIncomingMessageFromNode(self, node_number):\n\n # the raw bytes coming from serial port\n raw_bytes = b''\n\n #Serial port for Target Node\n ser = self.serial_list[node_number]\n\n #Check if port has minimum message length in buffer\n if ser.inWaiting() > 6: # at lseat enough bytes for SOM, ID, length, code\n\n #Check for Start of Message\n for i in range(len(self.SOM)):\n current_SOM = ser.read()\n raw_bytes += current_SOM\n if current_SOM != self.SOM[i:i+1]:\n # Fail: SOM byte missing\n # CheckIncomingMessageFromNode fails, stop reading serial port\n print(\"SOM Not Found\")\n print(current_SOM)\n return \"error\", \"SOM missing\", None, None\n\n #Teensy IDs, TODO: Use these for validation\n t1 = ser.read()\n t2 = ser.read()\n t3 = ser.read()\n raw_bytes = raw_bytes + t1 + t2 + t3\n received_tid = ((t1[0] << 16) | (t2[0] << 8)) | t3[0]\n \n # Read in Length and Code\n #data_length = int.from_bytes(ser.read(), byteorder = 'big')\n data_length = ser.read()\n raw_bytes += data_length\n data_length = data_length[0] # taking first element of one-element bytes object changes the byte to int\n message_code = ser.read()\n raw_bytes += message_code\n\n # read data\n incoming_data = []\n\n if ser.inWaiting() > data_length + 1: # at least enough bytes for data and EOM\n\n # read in data bytes (could be no bytes)\n for i in range(data_length):\n data_byte = ser.read()\n incoming_data.append(data_byte)\n raw_bytes += data_byte\n\n #Check for End of Message\n for i in range(len(self.EOM)):\n current_EOM = ser.read()\n raw_bytes += current_EOM\n if current_EOM != self.EOM[i:i+1]:\n # Fail: EOM byte missing\n # stop reading serial port, all read bytes are unused (aka discarded)\n return \"error\", \"EOM missing\", None, None\n # if we get here, we have found EOM and therefore whole message\n \n\n # Success: return message\n # Returns identifier byte for message code and relevant data list\n #print(\"Received message from node \" + str(node_number) + \" - Code: \" + str(message_code) + \", Data: \" + str(incoming_data))\n return message_code, incoming_data, received_tid, raw_bytes\n else:\n return \"error\", \"not enough data bytes\", None, None\n\n\n else:\n\n return \"error\", \"not enough bytes before data\", None, None\n\n def sendMessage(self, outgoing_message_code, outgoing_data, node_number):\n # input:\n # outgoing_message_code: bytes object of length 1\n # outgoing_data: list of ints (can be empty), ASSUMES EACH ITEM CAN BE TRANSFORMED INTO ONE SINGLE BYTE EACH\n # node_number: int\n\n data_length = len(outgoing_data) # outgoing data bytes\n\n # select serial port\n ser = self.serial_list[node_number]\n\n # the bytes object the we will construct and send to the serial port\n message = (self.SOM # 2 bytes\n + self.teensy_ids_bytes[node_number] # 3 bytes\n + bytes([data_length]) # 1 byte\n + outgoing_message_code # 1 byte\n + bytes(outgoing_data) # len(outgoing_data) bytes\n + self.EOM) # 2 bytes\n\n ser.write(message)\n\n #print(\"Sending message to node \" + str(node_number) + \" - Code: \" + str(outgoing_message_code) + \", Data: \" + str(outgoing_data))\n\n def getNodeNumberFromId(self, teensy_id):\n # returns indexed node number of Teensy\n # if this Teensy ID doesn't exist, returns -1\n for i in range(self.num_nodes):\n if teensy_id == self.teensy_ids[i]:\n return i\n return -1\n\n def close(self):\n for i in range(self.num_nodes):\n print (\"Stopping port: \" + str(self.node_addresses[i]))\n self.serial_list[i].close()\n \n\nif __name__ == '__main__':\n\n num_nodes = 1\n\n # test message\n TEST_LED_PIN_AND_RESPOND = b'\\x00'\n num_blinks = 10\n\n S = NodeSerial()\n\n S.sendMessage(TEST_LED_PIN_AND_RESPOND, [num_blinks], 0)\n\n time.sleep(1) # wait a second for response\n # this is not needed on windows\n # is needed on Pi\n\n code, data, tid, raw_bytes = S.checkIncomingMessageFromNode(0)\n print(\"Message received from node 0 - Code: \" + str(code) + \", Data: \" + str(data))\n print(\"Raw bytes of message: \" + str(raw_bytes))\n \n\n while True:\n try:\n\n # just some code to fill in this gap (this will be where main program code goes\n # for some reason if it is empty the KeyboardInterrupt doesn't get caught below\n for i in range(100):\n filler = 0\n except KeyboardInterrupt:\n print(\"Closing Main Program and Serial Ports\")\n S.close()\n\n print(\"Completed, Goodbye!\")\n break\n"
},
{
"alpha_fraction": 0.4939879775047302,
"alphanum_fraction": 0.5110220313072205,
"avg_line_length": 32.830509185791016,
"blob_id": "66d665f61669927b8852525eb2f645119aa9fe0c",
"content_id": "e0ea4f3cc875e0a003daa25caf40467e78a8d014",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1996,
"license_type": "no_license",
"max_line_length": 121,
"num_lines": 59,
"path": "/Master Laptop/Tools.py",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "class Tools():\n\n def __init__(self):\n self.pi_ip_addresses = []\n self.connected_teensies = []\n\n def set_params(self, pi_ip_addresses, connected_teensies):\n self.pi_ip_addresses = pi_ip_addresses\n self.connected_teensies = connected_teensies\n\n def decode_bytes(self,raw_bytes):\n # decodes a serial message bytes object\n # input: raw bytes sequence from node\n # ouput: code [byte]\n # data [list of ints]\n # tid (teensy id) [int] \n\n # teensy id\n tid_bytes = raw_bytes[2:5]\n tid =((tid_bytes[0] << 16) | (tid_bytes[1] << 8)) | tid_bytes[2]\n\n # number of data bytes\n length = raw_bytes[5:6][0]\n\n # instruction code\n code = raw_bytes[6:7]\n\n # data in bytes\n data_bytes = raw_bytes[7:7+length]\n\n #convert data to list of ints\n data = []\n for d in range(length):\n data.append(data_bytes[d])\n\n return code, data, tid\n\n def find_pi_from_teensy_int_id(self,int_id):\n # input: integer teensy id\n # output: (pi ip address [string], teensy id [bytes])\n\n # note: int.to_bytes(362262, byteorder = 'big', length = 3) = b'\\x05\\x87\\x16' \n \n for pi in self.pi_ip_addresses:\n\n try:\n for teensy in self.connected_teensies[pi]:\n #print(\"teensy: \" + str(teensy))\n #print(\"int id: \" + str(int_id))\n \n int_from_bytes = ((teensy[0] << 16) | (teensy[1] << 8)) | teensy[2]\n #print(\"bytes: \" + str(int_from_bytes))\n if int_from_bytes == int_id:\n return pi,teensy\n except KeyError:\n pass\n #print(\"Minor error: pi not on network -- RPi \" + pi)\n #print(\"ERROR: Cannot locate Pi for this Teensy ID - is DeviceLocator.py out of date? TEENSY ID: \" + str(int_id))\n return \"error\", \"error\"\n"
},
{
"alpha_fraction": 0.800000011920929,
"alphanum_fraction": 0.800000011920929,
"avg_line_length": 43.92307662963867,
"blob_id": "1ea5d0913b94ae63f390201cb027428980787ce4",
"content_id": "f6adf15ea44e5039ec807bfadefa562ccf9eaf06",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 585,
"license_type": "no_license",
"max_line_length": 120,
"num_lines": 13,
"path": "/Raspberry Pi/README.md",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "# Raspberry Pi\nThese python scripts reside on the Raspberry Pi and provide an interface between the Master Laptop and each Teensy.\n\n## LuddyPiSlave.py\nReceives UDP packets from the Master Laptop, translates to serial, and sends to a Teensy. \nReceives serial packets from a Teensy, translates to UDP, and sends to the Master Laptop.\nResponds to REQUEST_TEENSY_IDS message.\n\n## NodeSerial.py\nManages serial ports and communication to all connected Teensies, paired with NodeSerial.h/NodeSerial.cpp on the Teensy.\n\n## PiUDP.py\nHandles UDP sockets and communication to the Master Laptop.\n\n"
},
{
"alpha_fraction": 0.8267716765403748,
"alphanum_fraction": 0.8267716765403748,
"avg_line_length": 41.33333206176758,
"blob_id": "9c80c08c8b9938ff514659a850b7d0f716f7f633",
"content_id": "16de1dd24e97317d8e0e08f8dd109ae902b39adb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 127,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 3,
"path": "/Device Locator/README.md",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "# Generating DeviceLocator.py\n\ndevice_locator_generator.py will generate DeviceLocator.py from a suitably formatted .csv file.\n"
},
{
"alpha_fraction": 0.5347957015037537,
"alphanum_fraction": 0.5602163672447205,
"avg_line_length": 38.73466110229492,
"blob_id": "33cb55051b2b7d742d2e69ad6bb7e122201039af",
"content_id": "eb6a7e3b56f3a9910eae7f480e1500344e6670d2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 49920,
"license_type": "no_license",
"max_line_length": 165,
"num_lines": 1255,
"path": "/Master Laptop/DaejeonMasterLaptop.py",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "# LuddyLaptopMaster.py - LASG/PBAI\n# Created by Adam Francey, March 16 2018\n# This code resides on the master laptop at Amatria in Luddy Hall\n# Reads and writes UDP data to each connected Raspberry Pi\n# Reads and writes OSC messages to the 4DSOUND laptop\n# Coordinates global behaviour\n\n# THINGS TO CHANGE WHEN TESTING:\n# IP addresses, path_to_logs_folder\n\n#TEST_teensy_int = 336632\n#TEST_teensy_bytes = bytes([(TEST_teensy_int >> 16) & 255,(TEST_teensy_int >> 8) & 255, (TEST_teensy_int) & 255])\n#TEST_pi = '192.168.2.91'\nTEST_teensy_int = 245744\nTEST_teensy_bytes = bytes([(TEST_teensy_int >> 16) & 255,(TEST_teensy_int >> 8) & 255, (TEST_teensy_int) & 255])\nTEST_pi = '192.168.1.94'\n\n# standard python libraries\nimport socket # for UDP\nimport threading\nimport time\nimport queue\nimport random\n\n#Server\nfrom pythonosc import dispatcher\nfrom pythonosc import osc_server\n\n#Client\nfrom pythonosc import osc_message_builder\nfrom pythonosc import udp_client\n\n# LASG python libraries\nimport DeviceLocator # Auto generated from device_locator_generator.py and a .csv file of actuator properties\nimport FutureActions # Execute functions at a certain time in the future\nimport GroupActions # Coordinated actions for groups of actuators (aka sphereunit, SSS, breathing pore, etc).\n # Uses OSC interface\n \nimport Excitor # Stores incoming excitor information\nimport Tools # Useful functions\n\ndevice_locator = DeviceLocator.DeviceLocator()\nfuture_manager = FutureActions.FutureActions()\nexcitor = Excitor.Excitor()\n\n# log files\n#path_to_logs_folder = 'C:\\\\Users\\\\Adam Francey\\\\Documents\\\\ROM2018\\\\logs3\\\\' #Adam's laptop\n#path_to_logs_folder = 'C:\\\\Users\\\\amatriaadmin\\\\Desktop\\\\logs\\\\' # Amatria\n#path_to_logs_folder = 'C:\\\\Users\\\\ROM Control\\\\Desktop\\\\logs\\\\' #ROM\npath_to_logs_folder = 'C:\\\\Users\\\\User\\\\Desktop\\\\Code\\\\logs\\\\' # Daejeon\n\n# if logs folder doesn't exist, create it\nimport os\nif not os.path.isdir(path_to_logs_folder):\n os.makedirs(path_to_logs_folder)\n\n# CHANGE THESE IP ADDRESSES\nIP_4D_LAPTOP = device_locator.IP_4D_LAPTOP\nIP_MASTER = device_locator.IP_MASTER\npi_ip_addresses = device_locator.pi_ip_addresses\n\n# for testing at home\n#pi_ip_addresses = ['192.168.1.94']\n\ngroup_actions = GroupActions.GroupActions(IP_MASTER)\n\n# class for holding global variables\nclass SYSTEM():\n\n def __init__(self):\n self.on = True\n\n # modifiable params\n # Background Behaviour Timing Parameters\n self.background_behaviour_min_time = 45000\n self.background_behaviour_max_time = 90000\n\n #Lone Actuator Selection\n self.prob_RANDOM_ACTUATOR = 20\n self.ramp_up_time_RANDOM_ACTUATOR = 2000\n self.hold_time_RANDOM_ACTUATOR =1000\n self.ramp_down_time_RANDOM_ACTUATOR = 3000\n self.cooldown_time_RANDOM_ACTUATOR = 20000\n self.max_brightness_RANDOM_ACTUATOR = 240\n\n #Light Column Timing Parameters\n self.local_trigger_act_time = 5000\n self.local_trigger_variance = 1# on Teensy: 1/100.0 = 0.01 default, range: 0-100\n self.local_trigger_chain_width = 5 # on teensy: 10.0*5/100.0 = 0.5 default, range = 0-100\n self.local_trigger_act_time_AUTO = 3000\n\n #BP reflex behaviour\n self.ramp_up_time_BP_moth=1500\n self.ramp_up_time_BP_RS=1500\n self.ramp_down_time_BP_moth=2500\n self.ramp_down_time_BP_RS=2500\n self.hold_time_BP_moth=1000\n self.hold_time_BP_RS=1000\n\n #IR cool down time between triggers\n self.IR_min_time_between_triggers=1000\n self.next_random_sweep_time = int(time.time()) + 60\n\nsystem = SYSTEM()\n\n# instruction codes\nTEST_LED_PIN_AND_RESPOND = b'\\x00'\nREQUEST_TEENSY_IDS = b'\\x01'\nFADE_ACTUATOR_GROUP = b'\\x06'\nIR_TRIGGER = b'\\x07'\nIR_SAMPLING = b'\\x08'\nSET_IR_THRESHOLD = b'\\x09'\nSET_SINE_FREQUENCY = b'\\x0a'\nSET_SINE_AMPLITUDE = b'\\x0b'\nSET_SINE_PHASE = b'\\x0c'\nACTUATE_SMA = b'\\x0d'\nEXCITOR_POSITION = b'\\x0e'\nEXCITOR_PROPERTIES = b'\\x0f'\nGAUSSIAN_SHOT = b'\\x10'\nSYSTEM_PROPERTIES = b'\\x11'\nDO_NEIGHBOUR_BEHAVIOUR = b'\\x12'\n\n# command delimiters\nSOM = b'\\xff\\xff'\nEOM = b'\\xfe\\xfe'\n\nconnected_teensies = {} # connected_teensies[pi_addr] = [list of bytes objects, each element is bytes objects for one teensy]\nreceived_connected_teensies = {} #received_connected_teensies[pi_addr] = True or False if we received connected Teensies\n\n# initialize a queue for each pi\npi_incoming_bytes_queue = {} # pi_incoming_bytes_queue[pi ip address] = queue for that pi\nfor pi_addr in pi_ip_addresses:\n pi_incoming_bytes_queue[pi_addr] = queue.Queue()\n received_connected_teensies[pi_addr] = False\n\ntested_teensies = False\n\n\n# UDP Initialization \nUDP_PORT_RECEIVE = 4000\nUDP_PORT_TRANSMIT = 4001\nMY_IP ='0.0.0.0'\n\nsock_transmit = socket.socket(socket.AF_INET, # Internet\n socket.SOCK_DGRAM) # UDP\n\nsock_receive = socket.socket(socket.AF_INET, # Internet\n socket.SOCK_DGRAM) # UDP\nsock_receive.bind((MY_IP, UDP_PORT_RECEIVE))\n\n\ndef send_bytes(raw_bytes, ip_addr):\n sock_transmit.sendto(raw_bytes, (ip_addr, UDP_PORT_TRANSMIT))\n\n\ndef receive_bytes():\n while True:\n data, addr = sock_receive.recvfrom(1024) # buffer size is 1024 bytes\n pi_incoming_bytes_queue[addr[0]].put(data)\n #print(\"[\" + time.strftime(\"%B_%d_%Y_at_%H-%M-%S\") + \"] Received UDP - Address: \" + addr[0] + \", Data: \" + str(data))\n\n# this thread receives and stores UDP packets in the background\nlistening_thread = threading.Thread(target = receive_bytes)\n\n# OSC Initialization\nOSC_packet_queue = queue.Queue()\n\n# Server\nOSC_PORT_RECEIVE = 3001\n\n# default handler function for all incoming OSC\ndef receive_all_OSC(addr, *values):\n # expect addresses like\n # /4D/code/data\n OSC_packet_queue.put([addr, values])\n #print(addr)\n\n# parses and acts on all OSC messages\ndef parse_and_process_OSC(incoming_OSC):\n\n addr = incoming_OSC[0]\n data = incoming_OSC[1]\n\n # addr = '/SOURCE/CODE/IDENTIFIER'\n # data = [list of data]\n\n addr_list = addr.split('/')\n\n # addr[0] will always be ''\n source = addr_list[1]\n code = 'null'\n identifier = 'null'\n\n if len(addr_list) > 2:\n code = addr_list[2]\n\n if len(addr_list) > 3:\n identifier = addr_list[3]\n #print(identifier)\n\n #print(source)\n #print(code)\n if code == 'IR_SAMPLING':\n # message format\n # /TV/IR_SAMPLING/[START,STOP]\n if identifier == \"START\":\n send_IR_SAMPLING_command_to_all_nodes_with_sensors(1,100)\n else:\n send_IR_SAMPLING_command_to_all_nodes_with_sensors(0,100) \n\n if code == 'FADE_ACTUATOR_GROUP':\n\n # message format\n # /4D/FADE_ACTUATOR_GROUP/SSS1 RS1 0 50 2000 RS2 50 25 2000 MOTH3 50 0 6000\n \n # message format\n # /4D/FADE_ACTUATOR_GROUP/SPHERE1 RS1 50 2000 RS2 25 2000 MOTH3 0 6000\n \n # data should look like\n # (actuator_id1,end1,time1,actuator_id2,end2,time2,...,actuator_idN,endN,timeN)\n\n pi_ip_teensy_id_tuples = []\n pin_lists = []\n end_lists = []\n time_lists = []\n\n num_args_per_actuator = 3\n for d in range(0, len(data),num_args_per_actuator):\n actuator = data[d]\n end = data[d+1]\n time = data[d+2]\n pin = device_locator.amatria[identifier][actuator]['pin_number']\n\n pi_node = (device_locator.amatria[identifier][actuator]['pi_ip'], device_locator.amatria[identifier][actuator]['teensy_id_bytes'])\n if pi_node not in pi_ip_teensy_id_tuples:\n pi_ip_teensy_id_tuples.append(pi_node)\n pin_lists.append([])\n end_lists.append([])\n time_lists.append([])\n\n index = pi_ip_teensy_id_tuples.index(pi_node)\n pin_lists[index].append(pin)\n end_lists[index].append(end)\n time_lists[index].append(time)\n\n\n for node in range(len(pi_ip_teensy_id_tuples)):\n pi = pi_ip_teensy_id_tuples[node][0]\n teensy_bytes = pi_ip_teensy_id_tuples[node][1]\n pin_list = pin_lists[node]\n end_list = end_lists[node]\n time_list = time_lists[node]\n send_fade_command(pi,teensy_bytes, pin_list,end_list,time_list)\n\n \n\n elif code == \"ACTIVATE\":\n if \"SSS\" in identifier:\n # message format\n # /4D/ACTIVATE/SSS3 1 10000\n \n SSS_num = int(identifier[3])\n strength = data[0]\n timespan = data[1]\n ACTIVATE_SSS(SSS_num, strength, timespan)\n \n elif \"SPHERE\" in identifier:\n # message format\n # /4D/ACTIVATE/SPHERE3 1 10000\n \n sphere_num = int(identifier[6:])\n strength = data[0]\n timespan = data[1]\n ACTIVATE_SPHEREUNIT(sphere_num, strength, timespan)\n\n elif code == \"RIPPLE\":\n if \"SSS\" in identifier:\n # message format\n # /4D/RIPPLE/SSS3 1 10000\n \n SSS_num = int(identifier[3])\n strength = data[0]\n timespan = data[1]\n RIPPLE_SSS(SSS_num, strength, timespan)\n \n elif \"SPHERE\" in identifier:\n # message format\n # /4D/RIPPLE/SPHERE3 1 10000\n \n sphere_num = int(identifier[6:])\n strength = data[0]\n timespan = data[1]\n RIPPLE_SPHEREUNIT(sphere_num, strength, timespan)\n\n elif \"ENVFOLLOW\" in code:\n # message format\n # /4D/ENVFOLLOW_[letter]:\n\n letter = code.split(\"_\")[1]\n val = data[0] \n\n elif code == \"SET_IR_THRESHOLD\":\n # message format:\n # /4D/SET_IR_THRESHOLD/IR2 400\n\n threshold = data[0]\n sensor_number = int(identifier[2:])\n send_SET_IR_THRESHOLD_to_sensor(sensor_number, threshold)\n\n elif \"excitor\" in source:\n if code == \"positions\":\n x = int(data[0]*1000)\n y = int(data[1]*1000)\n z = int(data[2]*1000)\n excitor.position = [x,y,z]\n\n send_excitor_position_to_all(excitor)\n if code == \"dimensions\":\n x_dist = data[0]\n force_RS = data[1]\n force_moth = data[2]\n #excitor.radius = max(1,int(x_dist*100/2))\n #excitor.force = max(0,min(int(255*force/100), 255))\n excitor.radius = max(1,int(abs(x_dist)*100/2))\n excitor.force_RS = max(0,min(int(255*abs(force_RS)/100), 255))\n excitor.force_moth = max(0,min(int(255*abs(force_moth)/100), 255))\n send_excitor_properties_to_all(excitor)\n \n \n elif \"SMA\" in source:\n if len(source) == 8:\n section = \"BP\" + source[3:6]\n if len(source) == 9:\n section = 'BP' + source[3:7]\n actuator = source\n send_actuate_SMA(section, [actuator])\n elif 'RS' in source:\n actuator = source\n \n if len(source) == 5:\n section = \"BP\" + source[2:5]\n if len(source) == 6:\n section = 'BP' + source[2:6]\n pi, teensy_bytes = device_locator.amatria[section][actuator]['pi_ip'], device_locator.amatria[section][actuator]['teensy_id_bytes']\n pin = device_locator.amatria[section][actuator]['pin_number']\n end_list = [data[0]]\n time_list = [data[1]]\n #print('sending_fade')\n send_fade_command(pi,teensy_bytes, [pin],end_list,time_list)\n \n elif code == 'SYSTEM_PROPERTIES':\n system.background_behaviour_min_time = data[0]\n system.background_behaviour_max_time = data[1]\n\n system.prob_RANDOM_ACTUATOR = data[2]\n system.ramp_up_time_RANDOM_ACTUATOR = data[3]\n system.hold_time_RANDOM_ACTUATOR =data[4]\n system.ramp_down_time_RANDOM_ACTUATOR = data[5]\n system.cooldown_time_RANDOM_ACTUATOR = data[6]\n system.max_brightness_RANDOM_ACTUATOR = data[7]\n\n system.local_trigger_act_time = data[8]\n system.local_trigger_variance = data[9] \n system.local_trigger_chain_width = data[10]\n system.local_trigger_act_time_AUTO = data[11]\n\n system.ramp_up_time_BP_moth=data[12]\n system.ramp_up_time_BP_RS=data[13]\n system.ramp_down_time_BP_moth=data[14]\n system.ramp_down_time_BP_RS=data[15]\n system.hold_time_BP_moth=data[16]\n system.hold_time_BP_RS=data[17]\n\n #IR cool down time between triggers\n system.IR_min_time_between_triggers=data[18]\n\n send_SYSTEM_PROPERTIES_to_all()\n\n\ndef send_excitor_position_to_all(ex):\n pos = ex.position\n\n x_sign, y_sign, z_sign = 0,0,0\n\n if pos[0] < 0:\n x_sign = 1\n if pos[1] < 0:\n y_sign = 1\n if pos[2] < 0:\n z_sign = 1\n \n x_hi =(abs(pos[0]) >> 8) & 255 # high byte\n x_lo = abs(pos[0]) & 255 # low byte\n y_hi =(abs(pos[1]) >> 8) & 255 # high byte\n y_lo = abs(pos[1]) & 255 # low byte\n z_hi =(abs(pos[2]) >> 8) & 255 # high byte\n z_lo = abs(pos[2]) & 255 # low byte\n\n data = bytes([x_sign, x_hi, x_lo, y_sign, y_hi, y_lo, z_sign, z_hi, z_lo])\n length = bytes([9])\n actuator = 'RS1'\n for i in range(1,16):\n section = 'SPHERE' + str(i)\n pi = device_locator.amatria[section][actuator]['pi_ip']\n teensy_bytes = device_locator.amatria[section][actuator]['teensy_id_bytes']\n raw_bytes = SOM + teensy_bytes + length + EXCITOR_POSITION + data + EOM\n #print(pi)\n send_bytes(raw_bytes, pi)\n\n #print(\"here\") \n\n \n \ndef ACTIVATE_SSS(SSS_num, strength, timespan):\n group_actions.SSS_ring(SSS_num)\n\n\ndef ACTIVATE_SPHEREUNIT(sphere_num, strength, timespan):\n pass\n\ndef RIPPLE_SSS(SSS_start, strength, timespan):\n RIPPLE_SSS_RING(SSS_start)\n\ndef RIPPLE_SSS_RING(SSS_start):\n\n # first activate the starting SSS\n group_actions.SSS_ring(SSS_start)\n \n\n # now propagate the actuation away\n for index in range(1, 7):\n forward_SSS = index + SSS_start\n backward_SSS = SSS_start - index\n time_to_wait = 500*9*index # 9 iterations for each chain (empirically determined from function in group_actions)\n # 500ms per\n\n if forward_SSS <= 6:\n # maximum index for SSS is 5\n future_manager.add_function(time_to_wait, group_actions.SSS_ring, forward_SSS)\n if backward_SSS >= 1:\n future_manager.add_function(time_to_wait, group_actions.SSS_ring, backward_SSS)\n \n \n \ndef RIPPLE_SPHEREUNIT(sphere_start, strength, timespan):\n\n max_distance = max(sphere_start - 1, 12 - sphere_start)\n\n jump_time = int(timespan/max_distance)\n\n # first activate the starting sphere\n ACTIVATE_SPHEREUNIT(sphere_start, strength, jump_time)\n\n # now propagate the actuation away\n for index in range(1, max_distance + 1):\n forward_sphere = index + sphere_start\n backward_sphere = sphere_start - index\n time_to_wait = jump_time*index\n\n if forward_sphere <= 12:\n # maximum index for sphere is 5\n future_manager.add_function(time_to_wait, ACTIVATE_SPHEREUNIT, forward_sphere, strength, jump_time)\n if backward_sphere >= 1:\n future_manager.add_function(time_to_wait, ACTIVATE_SPHEREUNIT, backward_sphere, strength, jump_time)\n \n# OSC initialization\ndispatcher = dispatcher.Dispatcher()\ndispatcher.set_default_handler(receive_all_OSC)\nOSC_listener = osc_server.BlockingOSCUDPServer(('0.0.0.0', OSC_PORT_RECEIVE), dispatcher)\nOSC_listener_thread = threading.Thread(target=OSC_listener.serve_forever)\n\n# Client\nOSC_PORT_TRANSMIT = 3000\nOSC_client = udp_client.UDPClient(IP_4D_LAPTOP, OSC_PORT_TRANSMIT)\n\n# UDP clients for TV\nTV_PORT_TRANSMIT = 8051\nTV1_client = ('140.182.98.224', TV_PORT_TRANSMIT)\nTV2_client = ('140.182.98.225', TV_PORT_TRANSMIT)\nTV3_client = ('140.182.98.226', TV_PORT_TRANSMIT)\nTV4_client = ('140.182.98.227', TV_PORT_TRANSMIT)\nTV5_client = ('140.182.98.228', TV_PORT_TRANSMIT)\nTV6_client = ('140.182.98.229', TV_PORT_TRANSMIT)\nTV7_client = ('140.182.98.230', TV_PORT_TRANSMIT)\nTV8_client = ('140.182.98.231', TV_PORT_TRANSMIT)\n\nTV_UDPsocket = socket.socket(socket.AF_INET, # Internet\n socket.SOCK_DGRAM) # UDP\n\nTV_clients = [TV1_client, TV2_client, TV3_client, TV4_client, TV5_client, TV6_client, TV7_client,TV8_client]\n\ndef send_OSC_to_4D(addr, data):\n #print(\"[\" + time.strftime(\"%B_%d_%Y_at_%H-%M-%S\") + \"] Sending to 4D: \" + str([addr, data]))\n msg = osc_message_builder.OscMessageBuilder(address = addr)\n for d in data:\n msg.add_arg(d)\n msg = msg.build()\n OSC_client.send(msg)\n\ndef send_UDP_to_TV(bytes_to_send):\n count = 1\n for c in TV_clients:\n \n #print(\"[\" + time.strftime(\"%B_%d_%Y_at_%H-%M-%S\") + \"] Sending to TV\" + str(count) + \": \" + str(bytes_to_send))\n TV_UDPsocket.sendto(bytes_to_send,c)\n count+=1\n\n\n\n# UDP message handlers\ndef request_connected_teensies(f):\n \n\n # ask for connected Teensies\n tid = b'\\x00\\x00\\x00' # if teensy ID is \\x00\\x00\\x00 then raspberry pi knows this message is for itself\n length = b'\\x00' # no data\n raw_bytes = SOM + tid + length + REQUEST_TEENSY_IDS + EOM\n for pi in pi_ip_addresses:\n time.sleep(0.05)\n send_bytes(raw_bytes, pi)\n print(\"Requesting Teensies from Pi at \" + pi)\n f.write(\"Requesting Teensies from Pi at \" + pi + \"\\n\")\n\ndef get_connected_teensies(data):\n # data is list of ints, change back to bytes\n data_bytes = bytes(data)\n teensy_ids_bytes = []\n int_ids = []\n for i in range(0, len(data), 3):\n id_bytes = data_bytes[i:i+1] + data_bytes[i+1:i+2] + data_bytes[i+2:i+3]\n teensy_ids_bytes.append(id_bytes)\n int_id = ((data_bytes[i] << 16) | (data_bytes[i+1] << 8)) | data_bytes[i+2]\n int_ids.append(int_id)\n print(str(int_id) + \" (\" + str(id_bytes) + \")\")\n return teensy_ids_bytes\n\ndef get_connected_teensies_tofile(data, f):\n # data is list of ints, change back to bytes\n data_bytes = bytes(data)\n teensy_ids_bytes = []\n int_ids = []\n for i in range(0, len(data), 3):\n id_bytes = data_bytes[i:i+1] + data_bytes[i+1:i+2] + data_bytes[i+2:i+3]\n teensy_ids_bytes.append(id_bytes)\n int_id = ((data_bytes[i] << 16) | (data_bytes[i+1] << 8)) | data_bytes[i+2]\n int_ids.append(int_id)\n f.write(str(int_id) + \" (\" + str(id_bytes) + \")\\n\")\n print(str(int_id) + \" (\" + str(id_bytes) + \")\")\n return teensy_ids_bytes\n\ndef test_connected_teensies():\n # checks to see if we have collected Teensy IDs from connected Pis\n # if so, send a TEST command to each teensy and returns True\n # if not, exits and returns False\n for pi in pi_ip_addresses:\n if received_connected_teensies[pi] == False:\n return False\n\n # test connected Teensies\n length = b'\\x01' # data is only number of blinks\n data = b'\\x05' # blink 20 times\n print(\"Sending TEST_LED_PIN_AND_RESPOND to all connected Teensies\")\n for pi in pi_ip_addresses:\n for teensy in connected_teensies[pi]:\n tid = teensy\n raw_bytes = SOM + tid + length + TEST_LED_PIN_AND_RESPOND + data + EOM\n send_bytes(raw_bytes, pi)\n\n\ndef send_fade_command(pi, tid, pin_list, end_list, time_list):\n\n # pi: ip address of pi\n # tid: teensy id [bytes of len 3]\n # pin_list: pins to actuate [int list]\n # end_list: end values [int list]\n # time_list: fade times in ms [list of int]\n\n # to recover: fade_time == (fade_hi << 8) + fade_lo\n\n num_bytes_per_actuator = 4\n\n length = bytes([len(pin_list)*num_bytes_per_actuator])\n data = b''\n for a in range(len(pin_list)):\n fade_hi =(time_list[a] >> 8) & 255 # high byte\n fade_lo = time_list[a] & 255 # low byte\n data = data + bytes([pin_list[a], end_list[a],fade_hi, fade_lo])\n\n raw_bytes = SOM + tid + length + FADE_ACTUATOR_GROUP + data + EOM\n #print(\"[\" + time.strftime(\"%B_%d_%Y_at_%H-%M-%S\") + \"] Sending FADE_ACTUATOR_GROUP to \" + str(tid) + \", raw_bytes: \" + str(raw_bytes))\n\n #print(\"pin list: \" + str(pin_list))\n send_bytes(raw_bytes, pi)\n\ndef send_IR_SAMPLING_command_to_all_nodes_with_sensors(on_or_off, sampling_interval):\n\n pi_node_tuples = get_nodes_with_sensors()\n for node in pi_node_tuples:\n pi = node[0]\n tid = node[1]\n length = bytes([3])\n sample_hi =(sampling_interval >> 8) & 255 # high byte\n sample_lo = sampling_interval & 255 # low byte\n data = bytes([on_or_off, sample_hi, sample_lo])\n raw_bytes = SOM + tid + length + IR_SAMPLING + data + EOM\n send_bytes(raw_bytes, pi)\n \n\ndef get_nodes_with_sensors():\n # returns a set of (pi, node) tuples that contains sensors\n pi_ip_teensy_id_tuples = []\n for section in device_locator.amatria.keys():\n for actuator in device_locator.amatria[section].keys():\n if device_locator.amatria[section][actuator]['type'] == 'sensor':\n pi_node = (device_locator.amatria[section][actuator]['pi_ip'], device_locator.amatria[section][actuator]['teensy_id_bytes'])\n if pi_node not in pi_ip_teensy_id_tuples:\n pi_ip_teensy_id_tuples.append(pi_node)\n return pi_ip_teensy_id_tuples\n\n \ndef send_SET_IR_THRESHOLD_to_SSS(SSS, threshold):\n\n for sensor in [1,2,3]:\n sensor_index = (SSS-1)*3 + sensor\n send_SET_IR_THRESHOLD_to_sensor(sensor_index,threshold)\n\ndef send_SET_IR_THRESHOLD_to_sensor(sensor, threshold):\n # sets IR threshold for single IR sensor\n\n # IR sensor num = (SSS-1)*num_IR_per_SSS + ir_index + 1\n num_IR_per_SSS = 3\n SSS_num = int((sensor-1)/num_IR_per_SSS) + 1\n SSS = \"SSS\" + str(SSS_num)\n\n ir_index = (sensor - 1) % num_IR_per_SSS # ir_index ranges from 0 - 2\n ir = \"IR\" + str(ir_index)\n\n pi, tid = device_locator.amatria[SSS][ir]['pi_ip'], device_locator.amatria[SSS][ir]['teensy_id_bytes']\n\n\n # send command to pi/teensy\n length = bytes([3])\n thresh_hi =(threshold >> 8) & 255 # high byte\n thresh_lo = threshold & 255 # low byte\n data = bytes([ir_index, thresh_hi, thresh_lo])\n\n raw_bytes = SOM + tid + length + SET_IR_THRESHOLD + data + EOM\n #print(\"Sending SET_IR_THRESHOLD (\" + str(threshold) + \") to \" + str(tid) + \" on SSS\" + str(SSS) + \" for IR\" + str(sensor) + \", raw_bytes: \" + str(raw_bytes))\n send_bytes(raw_bytes, pi)\n\ndef send_SET_SINE_to_actuators_on_sphereunit(section, actuator_list, arg_list, instruction_code):\n\n # sphereunit: \"SPHERE##\"\n # actuator_list: \"RS#\", \"MOTH#\"\n # arg_list: frequencies, amplitudes, or phases [ints < 255]\n # instruction_code: SET_SINE_FREQUENCY, SET_SINE_AMPLITUDE, SET_SINE_PHASE\n\n pi_ip_teensy_id_tuples = []\n pin_lists = []\n arg_lists = []\n data_lists = []\n \n for a in range(len(actuator_list)):\n actuator = actuator_list[a]\n pi_node = (device_locator.amatria[section][actuator]['pi_ip'], device_locator.amatria[section][actuator]['teensy_id_bytes'])\n if pi_node not in pi_ip_teensy_id_tuples:\n pi_ip_teensy_id_tuples.append(pi_node)\n pin_lists.append([])\n arg_lists.append([])\n data_lists.append([])\n \n pin = device_locator.amatria[section][actuator]['pin_number']\n arg = arg_list[a]\n\n index = pi_ip_teensy_id_tuples.index(pi_node)\n pin_lists[index].append(pin)\n arg_lists[index].append(arg)\n data_lists[index].append(pin)\n data_lists[index].append(arg)\n\n num_bytes_per_actuator = 2\n for node in range(len(pi_ip_teensy_id_tuples)):\n pi = pi_ip_teensy_id_tuples[node][0]\n teensy_bytes = pi_ip_teensy_id_tuples[node][1]\n pin_list = pin_lists[node]\n data_list = data_lists[node]\n length = bytes([len(pin_list)*num_bytes_per_actuator]) \n data = bytes(data_list)\n raw_bytes = SOM + teensy_bytes + length + instruction_code + data + EOM\n send_bytes(raw_bytes, pi)\n\ndef send_actuate_SMA(section, actuator_list):\n pi_ip_teensy_id_tuples = []\n pin_lists = []\n \n for a in range(len(actuator_list)):\n actuator = actuator_list[a]\n pi_node = (device_locator.amatria[section][actuator]['pi_ip'], device_locator.amatria[section][actuator]['teensy_id_bytes'])\n if pi_node not in pi_ip_teensy_id_tuples:\n pi_ip_teensy_id_tuples.append(pi_node)\n pin_lists.append([])\n \n pin = device_locator.amatria[section][actuator]['pin_number']\n\n index = pi_ip_teensy_id_tuples.index(pi_node)\n pin_lists[index].append(pin)\n\n num_bytes_per_actuator = 1\n for node in range(len(pi_ip_teensy_id_tuples)):\n pi = pi_ip_teensy_id_tuples[node][0]\n teensy_bytes = pi_ip_teensy_id_tuples[node][1]\n pin_list = pin_lists[node]\n length = bytes([len(pin_list)*num_bytes_per_actuator]) \n data = bytes(pin_list)\n raw_bytes = SOM + teensy_bytes + length + ACTUATE_SMA + data + EOM\n send_bytes(raw_bytes, pi)\n\ndef send_excitor_properties_to_all(ex):\n pi_node_tuples = []\n for section in device_locator.amatria.keys():\n for actuator in device_locator.amatria[section].keys():\n pi_node = (device_locator.amatria[section][actuator]['pi_ip'], device_locator.amatria[section][actuator]['teensy_id_bytes'])\n if pi_node not in pi_node_tuples:\n pi_node_tuples.append(pi_node)\n\n #print(pi_node_tuples)\n for pi_node in pi_node_tuples:\n pi = pi_node[0]\n teensy_bytes = pi_node[1]\n\n length = bytes([4])\n radius_hi =(ex.radius >> 8) & 255 # high byte\n radius_lo = ex.radius & 255 # low byte\n data = bytes([radius_hi, radius_lo, ex.force_RS, ex.force_moth])\n raw_bytes = SOM + teensy_bytes + length + EXCITOR_PROPERTIES + data + EOM\n #print(\"raw: \" + str(raw_bytes))\n #print('pi: ' + pi)\n send_bytes(raw_bytes, pi)\n\ndef send_SYSTEM_PROPERTIES_to_all():\n\n data = bytes([(system.background_behaviour_min_time >> 16) & 255,(system.background_behaviour_min_time >> 8) & 255, (system.background_behaviour_min_time) & 255,\n (system.background_behaviour_max_time >> 16) & 255,(system.background_behaviour_max_time >> 8) & 255, (system.background_behaviour_max_time) & 255,\n system.prob_RANDOM_ACTUATOR,\n (system.ramp_up_time_RANDOM_ACTUATOR >> 8) & 255, (system.ramp_up_time_RANDOM_ACTUATOR) & 255,\n (system.hold_time_RANDOM_ACTUATOR >> 8) & 255, (system.hold_time_RANDOM_ACTUATOR) & 255,\n (system.ramp_down_time_RANDOM_ACTUATOR >> 8) & 255, (system.ramp_down_time_RANDOM_ACTUATOR) & 255,\n (system.cooldown_time_RANDOM_ACTUATOR >> 8) & 255, (system.cooldown_time_RANDOM_ACTUATOR) & 255,\n system.max_brightness_RANDOM_ACTUATOR,\n (system.local_trigger_act_time >> 8) & 255, (system.local_trigger_act_time) & 255,\n system.local_trigger_variance,\n system.local_trigger_chain_width,\n (system.local_trigger_act_time_AUTO >> 8) & 255, (system.local_trigger_act_time_AUTO) & 255,\n (system.ramp_up_time_BP_moth >> 8) & 255, (system.ramp_up_time_BP_moth) & 255,\n (system.ramp_up_time_BP_RS >> 8) & 255, (system.ramp_up_time_BP_RS) & 255,\n (system.ramp_down_time_BP_moth >> 8) & 255, (system.ramp_down_time_BP_moth) & 255,\n (system.ramp_down_time_BP_RS >> 8) & 255, (system.ramp_down_time_BP_RS) & 255,\n (system.hold_time_BP_moth >> 8) & 255, (system.hold_time_BP_moth) & 255,\n (system.hold_time_BP_RS >> 8) & 255, (system.hold_time_BP_RS) & 255,\n (system.IR_min_time_between_triggers >> 8) & 255, (system.IR_min_time_between_triggers) & 255])\n length = bytes([len(data)])\n\n pi_node_tuples = []\n for section in device_locator.amatria.keys():\n for actuator in device_locator.amatria[section].keys():\n pi_node = (device_locator.amatria[section][actuator]['pi_ip'], device_locator.amatria[section][actuator]['teensy_id_bytes'])\n if pi_node not in pi_node_tuples:\n pi_node_tuples.append(pi_node)\n\n #print(pi_node_tuples)\n for pi_node in pi_node_tuples:\n pi = pi_node[0]\n teensy_bytes = pi_node[1]\n raw_bytes = SOM + teensy_bytes + length + SYSTEM_PROPERTIES + data + EOM\n send_bytes(raw_bytes, pi)\n\ndef send_GAUSSIAN_SHOT_to_node(pi, teensy_id_bytes, num_frames, variance, offset_step):\n\n num_frames_hi =(num_frames >> 8) & 255 # high byte\n num_frames_lo = num_frames & 255 # low byte\n variance_hi =(variance >> 8) & 255 # high byte\n variance_lo = variance & 255 # low byte\n data = bytes([num_frames_hi, num_frames_lo, variance_hi, variance_lo, offset_step])\n length = bytes([len(data)])\n raw_bytes = SOM + teensy_id_bytes + length + GAUSSIAN_SHOT + data + EOM\n send_bytes(raw_bytes, pi)\n\ndef send_DO_BP_NEIGHBOUR_BEHAVIOUR(section):\n BP = section[-1]\n ident = section[2:]\n pi = device_locator.amatria[section]['RS' + ident]['pi_ip']\n teensy_bytes = device_locator.amatria[section]['RS' + ident]['teensy_id_bytes']\n data = bytes([int(BP)])\n length = bytes([len(data)])\n raw_bytes = SOM + teensy_bytes + length + DO_NEIGHBOUR_BEHAVIOUR + data + EOM\n send_bytes(raw_bytes, pi)\n\ndef LC_neighbour_behaviour(triggered_lc):\n \n max_col_number = 6\n delay_time = 2000 # ms\n # triggered_lc looks like 'LC1', etc\n LC_index = int(triggered_lc[2:])\n\n for i in range(1, max_col_number + 1):\n dist = abs(i-LC_index)\n if dist != 0:\n time_to_wait = dist*delay_time\n section = 'LC' + str(i)\n pi = device_locator.amatria[section]['RS1']['pi_ip']\n teensy_id_bytes = device_locator.amatria[section]['RS1']['teensy_id_bytes']\n future_manager.add_function(time_to_wait, send_GAUSSIAN_SHOT_to_node, pi, teensy_id_bytes, 3000, 1000, 1)\n\n\ndef BP_neighbour_behaviour(triggered_bp, sensor_num):\n # triggered_bp looks like 'BP1-1', which contains 'IR1-1'\n # but is only accurate up to 'BP1'\n # so need sensor num to identify actual bp\n # sensor_num = 0,1\n BP_order = ['BP1-1', 'BP1-2','BP2-1', 'BP2-2','BP3-1', 'BP3-2', 'BP4-1', 'BP4-2','BP5-1', 'BP5-2', 'BP6-1', 'BP6-2']\n max_BP_number = 6\n num_SMA = 6\n delay_time = 1800 # ms\n BP_index = int(triggered_bp[triggered_bp.index('P')+1:triggered_bp.index('-')])\n\n actual_triggered_BP_ident = 'BP' + str(BP_index) + '-' + str(sensor_num+1)\n triggered_BP_index = BP_order.index(actual_triggered_BP_ident)\n\n for bp in range(0, len(BP_order)):\n dist = abs(bp-triggered_BP_index)\n time_to_wait = dist*delay_time\n section = BP_order[bp]\n if dist!= 0:\n # the BP will do local moth/RS behaviour itself\n future_manager.add_function(time_to_wait, send_DO_BP_NEIGHBOUR_BEHAVIOUR, section)\n\ndef sweep_BP_RS(direction):\n BP_order = ['BP1-1', 'BP1-2','BP2-1', 'BP2-2','BP3-1', 'BP3-2', 'BP4-1', 'BP4-2','BP5-1', 'BP5-2', 'BP6-1', 'BP6-2']\n RS_list = ['RS1-1', 'RS1-2','RS2-1', 'RS2-2','RS3-1', 'RS3-2', 'RS4-1', 'RS4-2','RS5-1', 'RS5-2', 'RS6-1', 'RS6-2']\n if direction == 'backward':\n BP_order = [BP_order[-i] for i in range(1, len(BP_order)+1)]\n RS_list = [RS_list[-i] for i in range(1, len(RS_list)+1)]\n\n time_between_leds = 600\n ramp_up_time = 1500\n hold_time = 1000\n ramp_down_time = 2000\n PWM_value = 200\n for bp in range(0, len(BP_order)):\n dist = bp\n time_to_wait = dist*time_between_leds\n pi = device_locator.amatria[BP_order[bp]][RS_list[bp]]['pi_ip']\n teensy_bytes = device_locator.amatria[BP_order[bp]][RS_list[bp]]['teensy_id_bytes']\n pin = device_locator.amatria[BP_order[bp]][RS_list[bp]]['pin_number']\n future_manager.add_function(time_to_wait, send_fade_command, pi,teensy_bytes, [pin],[PWM_value],[ramp_up_time])\n future_manager.add_function(time_to_wait + hold_time, send_fade_command, pi,teensy_bytes, [pin],[0],[ramp_down_time])\n\ndef sweep_LC_auto(direction):\n num_LC = 6\n num_led_per_LC = 6\n index_start_auto_LED = 13\n index_end_auto_LED = 18\n section_list = ['LC' + str(i) for i in range(1,num_LC+1)]\n if direction == 'backward':\n section_list = [section_list[-i] for i in range(1, len(section_list)+1)]\n auto_led_list = ['RS' + str(i) for i in range(index_start_auto_LED, index_end_auto_LED + 1)]\n ramp_up_time = 1500\n hold_time = 1000\n ramp_down_time = 2000\n PWM_value = 200\n time_between_leds = 250\n\n for LC in section_list:\n for led in auto_led_list:\n dist = section_list.index(LC)*num_led_per_LC + auto_led_list.index(led)\n time_to_wait = dist*time_between_leds\n pi = device_locator.amatria[LC][led]['pi_ip']\n teensy_bytes = device_locator.amatria[LC][led]['teensy_id_bytes']\n pin = device_locator.amatria[LC][led]['pin_number']\n\n time_to_wait = dist*time_between_leds\n future_manager.add_function(time_to_wait, send_fade_command, pi,teensy_bytes, [pin],[PWM_value],[ramp_up_time])\n future_manager.add_function(time_to_wait + hold_time, send_fade_command, pi,teensy_bytes, [pin],[0],[ramp_down_time])\n \n \n \n \n \n \n \n \n \n\ndef print_and_write_to_file(string, filepath, arg):\n # string: string to print and write\n # filepath: path to file including filename\n # arg: argument for open() - 'w' or 'a'\n print(string)\n with open(filepath, arg) as f:\n f.write(string + \"\\n\")\n\n\ndef SHUT_OFF_ACTUATORS():\n\n # clear future (remove queued functions)\n future_manager.reset()\n\n # stop excitor\n excitor.force_RS = 0\n excitor.force_moth = 0\n send_excitor_properties_to_all(excitor)\n\n # turn off every actuator on every pi\n pi_ip_teensy_id_tuples = []\n pin_lists = []\n end_lists = []\n time_lists = []\n for section in device_locator.amatria.keys():\n for actuator in device_locator.amatria[section].keys():\n if device_locator.amatria[section][actuator]['type'] == 'actuator':\n pi_node = (device_locator.amatria[section][actuator]['pi_ip'], device_locator.amatria[section][actuator]['teensy_id_bytes'])\n if pi_node not in pi_ip_teensy_id_tuples:\n pi_ip_teensy_id_tuples.append(pi_node)\n pin_lists.append([])\n end_lists.append([])\n time_lists.append([])\n \n pin = device_locator.amatria[section][actuator]['pin_number']\n pos = device_locator.amatria[section][actuator]['position']\n time = 500\n end = 0\n\n index = pi_ip_teensy_id_tuples.index(pi_node)\n pin_lists[index].append(pin)\n end_lists[index].append(end)\n time_lists[index].append(time)\n\n for node in range(len(pi_ip_teensy_id_tuples)):\n pi = pi_ip_teensy_id_tuples[node][0]\n teensy_bytes = pi_ip_teensy_id_tuples[node][1]\n pin_list = pin_lists[node]\n end_list = end_lists[node]\n time_list = time_lists[node]\n #print(pin_list)\n send_fade_command(pi,teensy_bytes, pin_list,end_list,time_list)\n \n \n \n\n##################################### MAIN ######################################\ntools = Tools.Tools()\n\nsend_shot = False\n\n# for testing\ndebug = False\nsend_sampling_request = True\nsend_sampling_stop_request = False\nsend_set_ir_threshold = False\n\nlog_all_IR_samples = False\ntime_to_log_samples = 60*60*1 # seconds to log for\nsensor_logging_file = path_to_logs_folder + 'IR_samples_ROM_' + time.strftime(\"%B_%d_%Y_at_%H-%M-%S\") + '.txt'\n# initialize file\nif log_all_IR_samples:\n with open(sensor_logging_file, 'w') as f:\n f.write(\"---------------------------------------------------\\n\")\n f.write(\"----------------SENSOR VALUES----------------------\\n\")\n f.write(\"---------------------------------------------------\\n\")\n\n# don't remember why I paused for a second here but I don't think it's needed\n# keeping it anyway to give time for network sockets and background threads to start\ntime.sleep(1)\n \n\nnetwork_alive = False\nnetwork_alive_timeout = 10 # seconds to wait for Pi\nnetwork_alive_start_time = time.time()\nlistening_thread.start() # UDP\n# first check for reponses from each Pi\ntry:\n with open(path_to_logs_folder + 'registration_amatria_' + time.strftime(\"%B_%d_%Y_at_%H-%M-%S\") + '.txt', 'w') as logfile:\n request_connected_teensies(logfile) # asks each pi in pi_ip_addresses for a list of its connected teensies\n while (not network_alive) and (time.time() - network_alive_start_time < network_alive_timeout):\n\n # check each Pi for incoming response\n for pi in pi_ip_addresses:\n try:\n # try to get a packet from the queue\n # raises queue.Empty exception if no packets waiting in queue\n incoming_bytes = pi_incoming_bytes_queue[pi].get(block = False)\n code, data, tid = tools.decode_bytes(incoming_bytes)\n if code == REQUEST_TEENSY_IDS:\n # response from asking for Teensy IDs\n logfile.write(\"Received UDP - Address: \" + pi + \", Packet: \" + str(incoming_bytes) + \"\\n\")\n logfile.write(\"Decoded Message:\\n\")\n logfile.write(\"Teensies connected to pi at address \" + pi + \": \\n\")\n print(\"Received UDP - Address: \" + pi + \", Packet: \" + str(incoming_bytes))\n print(\"Decoded Message:\")\n print(\"Teensies connected to pi at address \" + pi + \": \")\n connected_teensies[pi] = get_connected_teensies_tofile(data,logfile)\n received_connected_teensies[pi] = True\n except queue.Empty:\n pass\n\n # check to see if we have received response from all Pi\n found_all_pi = True\n for pi in pi_ip_addresses:\n if received_connected_teensies[pi] == False:\n found_all_pi = False\n\n network_alive = found_all_pi\n print(\"-------------------------------------------------------------\")\n logfile.write(\"-------------------------------------------------------------\\n\")\n if network_alive:\n # if we get here we have received a response from each Pi\n print(\"All Raspberry Pi have responded with their connected Teensies\")\n logfile.write(\"All Raspberry Pi have responded with their connected Teensies\\n\")\n else:\n print(\"A Pi has not responded. Check log file.\")\n logfile.write(\"A Pi has not responded. Check log file.\\n\")\n print(\"-------------------------------------------------------------\")\n logfile.write(\"-------------------------------------------------------------\\n\")\n\n \n\n # Initialization (like start() on arduino)\n if send_set_ir_threshold == True:\n\n # SET ALL IR THRESHOLDS\n thresholds = [400,195,140,\n 375,170,155,\n 370,175,245,\n 260,190,280,\n 350,330,200,\n 415,140,200]\n\n temporary_thresholds = [400]*18\n\n # set all IR thresholds to 400 while sensor data is logged \n #thresholds = temporary_thresholds\n\n print(\"[\" + time.strftime(\"%B_%d_%Y_at_%H-%M-%S\") + \"] Setting IR thresholds\")\n for IR in range(1, 19):\n send_SET_IR_THRESHOLD_to_sensor(IR, thresholds[IR - 1])\n \n if send_sampling_request == True:\n print(\"[\" + time.strftime(\"%B_%d_%Y_at_%H-%M-%S\") + \"] Requesting IR sensor data stream\")\n \n send_IR_SAMPLING_command_to_all_nodes_with_sensors(1,100)\n \n if send_sampling_stop_request == True:\n send_IR_SAMPLING_command_to_all_nodes_with_sensors(0,100)\n \n\n tools.set_params(pi_ip_addresses,connected_teensies)\n\n OSC_listener_thread.start() #OSC\n start_time = time.time()\n \n # MAIN LOOP (like loop() on arduino)\n system.on = True # if system.on == False we still get OSC and UDP out of queue, but do not do anything with the data\n while True:\n #print(\"on: \" + str(system.on))\n\n if (int(time.time()) > system.next_random_sweep_time):\n r = random.randint(1,2)\n if r == 1:\n sweep_BP_RS('backward')\n sweep_LC_auto('backward')\n else:\n sweep_BP_RS('forward')\n sweep_LC_auto('forward')\n system.next_random_sweep_time = int(time.time() + random.randint(120,240))\n \n\n # first see if we need to do any waiting functions\n if system.on:\n future_manager.do_if_time_elapsed_and_remove()\n\n # check for OSC message from 4d laptop\n try:\n incoming_OSC = OSC_packet_queue.get(block = False)\n #print(\"[\" + time.strftime(\"%B_%d_%Y_at_%H-%M-%S\") + \"] Incoming OSC: \" + str(incoming_OSC))\n\n addr = incoming_OSC[0]\n if \"SHUT_OFF\" in addr:\n SHUT_OFF_ACTUATORS()\n system.on = False\n print(\"[\" + time.strftime(\"%B_%d_%Y_at_%H-%M-%S\") + \"] SHUT OFF\")\n \n elif \"TURN_ON\" in addr:\n system.on = True\n print(\"[\" + time.strftime(\"%B_%d_%Y_at_%H-%M-%S\") + \"] TURN ON\")\n elif system.on:\n #print(\"[\" + time.strftime(\"%B_%d_%Y_at_%H-%M-%S\") + \"] Incoming OSC: \" + str(incoming_OSC))\n parse_and_process_OSC(incoming_OSC)\n \n except queue.Empty:\n pass\n\n for pi in pi_ip_addresses:\n # check for waiting UDP message from a Pi\n try:\n # try to get a packet from the queue\n # raises queue.Empty exception if no packets waiting in queue\n incoming_bytes = pi_incoming_bytes_queue[pi].get(block = False)\n code, data, tid = tools.decode_bytes(incoming_bytes)\n if system.on and code == REQUEST_TEENSY_IDS:\n # response from asking for Teensy IDs\n print(\"Received UDP - Address: \" + pi + \", Packet: \" + str(incoming_bytes))\n print(\"Decoded Message:\")\n print(\"Teensies connected to pi at address \" + pi + \": \")\n connected_teensies[pi] = get_connected_teensies(data)\n received_connected_teensies[pi] = True\n\n elif system.on and code == TEST_LED_PIN_AND_RESPOND:\n print(\"Teensy response from \" + str(tid) + \" on \" + pi + \": \" + str(data))\n \n elif system.on and code == IR_TRIGGER:\n\n # get sensor index\n sensor_num = data[0]\n\n triggered_section = ''\n triggered_tid = 0\n\n for section in device_locator.amatria.keys():\n for actuator in device_locator.amatria[section].keys():\n if device_locator.amatria[section][actuator]['teensy_id_int'] == tid:\n triggered_section = section\n triggered_tid = tid\n if 'LC' in triggered_section:\n LC_neighbour_behaviour(triggered_section)\n if 'BP' in triggered_section:\n BP_neighbour_behaviour(triggered_section, sensor_num)\n #print(\"Sensor trigger on tid \" + str(tid) + '. Sensor index: ' + str(sensor_num))\n \n\n # ROM\n # enumerate IR sensor number\n## sensor_num = data[0]\n##\n## ##find which BPC this came from\n## BPC = -1\n## for i in range(1,13):\n## if tid == device_locator.amatria['BP' + str(i) + '-1']['IR' + str(i) + '-1']['teensy_id_int']:\n## BPC = i\n## \n## \n## BP_num = str(BPC) + '-' + str(sensor_num + 1)\n## #print(\"BP_num: \" + BP_num)\n## if (sensor_num < 2):\n## group_actions.SMA_ring(BP_num)\n##\n## IR_label = 'IR' + BP_num\n## \n## sensor_value = (data[1] << 8) + data[2]\n## send_OSC_to_4D(\"/4D/TRIGGER/IR\" + str(BP_num), [sensor_value])\n \n #print(\"sensor trigger\")\n\n #AMATRIA\n \n## IR_index = SSS*3 + sensor_num + 1\n##\n## sensor_value = (data[1] << 8) + data[2]\n##\n## # send to 4D\n## send_OSC_to_4D(\"/4D/TRIGGER/IR\" + str(IR_index), [sensor_value])\n## #if log_all_IR_samples and time.time() - start_time < time_to_log_samples:\n## # with open(sensor_logging_file, 'a') as f:\n## # f.write(\"[\" + time.strftime(\"%B_%d_%Y_at_%H-%M-%S\") + \"] IR\" + str(IR_index) + \" triggered: \" + str(sensor_value) + \"\\n\")\n## if time.time() - start_time > 10:\n## # otherwise trigger messages come in and block auto registration\n## #print(\"[\" + time.strftime(\"%B_%d_%Y_at_%H-%M-%S\") + \"] IR\" + str(IR_index) + \" triggered: RIPPLE away from SSS\" + str(SSS + 1))\n## RIPPLE_SSS_RING(SSS + 1)\n\n elif system.on and code == IR_SAMPLING:\n if time.time() - start_time > 15:\n\n sampled_section = ''\n\n for section in device_locator.amatria.keys():\n for actuator in device_locator.amatria[section].keys():\n if device_locator.amatria[section][actuator]['teensy_id_int'] == tid:\n sampled_section = section\n\n ir1 = (data[0] << 8) + data[1]\n ir2 = (data[2] << 8) + data[3]\n ir3 = (data[4] << 8) + data[5]\n #print(\"Sensor values on tid \" + str(tid) + ': ' + str([ir1,ir2,ir3]))\n\n # ROM\n # find which BPC this came from\n## BPC = - 1\n## for i in range(1,13):\n## if tid == device_locator.amatria['BP' + str(i) + '-1']['IR' + str(i) + '-1']['teensy_id_int']:\n## BPC = i\n## ir1 = (data[0] << 8) + data[1]\n## ir2 = (data[2] << 8) + data[3]\n## if log_all_IR_samples and time.time() - start_time < time_to_log_samples:\n## with open(sensor_logging_file, 'a') as f:\n## f.write(\"[\" + time.strftime(\"%B_%d_%Y_at_%H-%M-%S\") + \"] IR values on BPC \" + str(BPC) + \": \" + str([ir1,ir2]) + \"\\n\")\n \n\n # AMATRIA\n## # find which SSS this came from\n## SSS = -1\n## for i in range(6):\n## if tid == device_locator.amatria['SSS' + str(i+1)]['IR0']['teensy_id_int']:\n## SSS = i\n##\n## ir1 = (data[0] << 8) + data[1]\n## ir2 = (data[2] << 8) + data[3]\n## ir3 = (data[4] << 8) + data[5]\n## bytesToSend = bytes(\"TV/TRIGGER/SSS\" + str(SSS+1) + \"/\" + str(ir1) + \"/\" + str(ir2) + \"/\" + str(ir3),\"utf-8\")\n## send_UDP_to_TV(bytesToSend)\n## #print(\"[\" + time.strftime(\"%B_%d_%Y_at_%H-%M-%S\") + \"] IR values on SSS \" + str(SSS + 1) + \": \" + str([ir1,ir2,ir3]))\n## if log_all_IR_samples and time.time() - start_time < time_to_log_samples:\n## with open(sensor_logging_file, 'a') as f:\n## f.write(\"[\" + time.strftime(\"%B_%d_%Y_at_%H-%M-%S\") + \"] IR values on SSS \" + str(SSS + 1) + \": \" + str([ir1,ir2,ir3]) + \"\\n\")\n \n \n except queue.Empty:\n pass\n\n # these if statements are just for testing\n\n if debug and tested_teensies == False:\n tested_teensies = test_connected_teensies()\n \n if send_shot:\n print('sweep sent')\n send_shot = False\n #BP_neighbour_behaviour('BP1-2', 1)\n #teensy_int = 336632\n #teensy_bytes = bytes([(teensy_int >> 16) & 255,(teensy_int >> 8) & 255, (teensy_int) & 255])\n #send_GAUSSIAN_SHOT_to_node('192.168.2.91', teensy_bytes, 3000, 1000, 10)\n #send_SYSTEM_PROPERTIES_to_all()\n #sweep_BP_RS()\n #send_actuate_SMA('BP1-2', ['SMA1-2-1'])\n #send_DO_BP_NEIGHBOUR_BEHAVIOUR('BP1-1')\n sweep_BP_RS('forward')\n sweep_LC_auto('forward')\n \n\n \n\n #print(\"on: \" + str(system.on))\n # TODO on exit:\n # - stop IR sampling\nexcept KeyboardInterrupt:\n print(\"Shutting down\")\n SHUT_OFF_ACTUATORS()\n \n\n \n \n \n\n\n\n\n"
},
{
"alpha_fraction": 0.6003448367118835,
"alphanum_fraction": 0.6339687705039978,
"avg_line_length": 39.21772766113281,
"blob_id": "236a8297080f1fd8b260fafa2d5f29089455a917",
"content_id": "a6028740998acf61ecb02820ac9547795529b353",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 20878,
"license_type": "no_license",
"max_line_length": 162,
"num_lines": 519,
"path": "/Archive/Teensy/LuddyNode/LuddyNode.ino",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "// example code for sending password to Pi\n// for auto-registration\n\n// test node id 245744\n\n#include \"NodeSerial.h\"\n#include \"Behaviours.h\"\n#include \"DeviceLocator.h\"\n#include \"SMA.h\"\n#include <SoftPWM.h>\n\n// Message codes\n#define TEST_LED_PIN_AND_RESPOND 0x00\n#define AUDIO_START_RECORDING 0x02\n#define AUDIO_STOP_RECORDING 0x03\n#define AUDIO_START_PLAYING 0x04\n#define AUDIO_STOP_PLAYING 0x05\n#define FADE_ACTUATOR_GROUP 0x06\n#define IR_TRIGGER 0x07\n#define IR_SAMPLING 0x08\n#define SET_IR_THRESHOLD 0x09\n#define SET_SINE_FREQUENCY 0x0a\n#define SET_SINE_AMPLITUDE 0x0b\n#define SET_SINE_PHASE 0x0c\n#define ACTUATE_SMA 0x0d\n#define EXCITOR_POSITION 0x0e\n#define EXCITOR_PROPERTIES 0x0f\n#define GAUSSIAN_SHOT 0x10\n#define SYSTEM_PROPERTIES 0x11\n#define DO_NEIGHBOUR_BEHAVIOUR 0x12\n\n#define PASSWORD 0xaa\n\nint frame_duration = 5; //milliseconds\n\nint led_pin = 13;\n\nstatic uint8_t teensyID[8];\nuint8_t my_id_bytes[3] = {0x00,0x00,0x00};\nlong int my_id;\nuint8_t my_type = 99; // default value\nint my_index;\n\nconst uint8_t num_actuator_pins = 18;\n\nint ex_x = 0;\nint ex_y = 0;\nint ex_z = 0;\n\nbool serial_registered = false;\n\nlong millis_of_last_comm_or_trigger = millis();\nlong background_behaviour_time_threshold = 60000;\nlong background_behaviour_min_time = 45000;\nlong background_behaviour_max_time = 90000;\n\n\nNodeSerial serial_comm;\nBehaviours behaviours(frame_duration);\nDeviceLocator device_locator;\n\n//const int max_SMA = 12;\n//SMA SMA_list[max_SMA] = {SMA(13), SMA(13), SMA(13), SMA(13), SMA(13), SMA(13), \n// SMA(13), SMA(13), SMA(13), SMA(13), SMA(13), SMA(13)};\n\nvoid setup() {\n\n read_teensyID();\n\n get_my_type_and_index();\n\n behaviours.my_type = my_type;\n behaviours.my_index = my_index;\n\n behaviours.init_all_SMA();\n\n pinMode(led_pin, OUTPUT);\n set_pinMode_for_all_of_my_pins();\n\n // seed random number generator, we don't care whether anything is connected to pin A0 or not\n randomSeed(analogRead(A0));\n \n // flash LEDS\n SoftPWMBegin(SOFTPWM_NORMAL);\n\n if (my_type == device_locator.type_BP){\n behaviours._behaviour_on[behaviours._behaviour_EXCITOR] = false;\n }\n\n if (my_type == device_locator.type_SU){\n behaviours._behaviour_on[behaviours._behaviour_EXCITOR] = true;\n }\n\n /*\n for (uint8_t i = 0; i < 10; i++){\n SoftPWMSet(13, 100);\n SoftPWMSet(3, 75);\n SoftPWMSet(4, 75);\n delay(20);\n SoftPWMSet(13, 0);\n SoftPWMSet(3, 0);\n SoftPWMSet(4, 0);\n delay(20);\n }\n */\n if (my_type == device_locator.type_SSS || my_type == device_locator.type_BP || my_type == device_locator.type_LC){\n behaviours.start_IR_TRIGGER(400,400,400);\n\n // taken from device locator\n\n uint8_t prob = behaviours.prob_RANDOM_ACTUATOR;\n int ramp_up_time = behaviours.ramp_up_time_RANDOM_ACTUATOR;\n int hold_time = behaviours.hold_time_RANDOM_ACTUATOR;\n int ramp_down_time = behaviours.ramp_down_time_RANDOM_ACTUATOR;\n int cooldown_time = behaviours.cooldown_time_RANDOM_ACTUATOR;\n behaviours.start_RANDOM_ACTUATOR(prob,ramp_up_time,hold_time,ramp_down_time, cooldown_time);\n }\n\n // flash LEDS\n /*\n for (uint8_t i = 0; i < 3; i++){\n SoftPWMSet(13, 100);\n SoftPWMSet(3, 75);\n SoftPWMSet(4, 75);\n delay(500);\n SoftPWMSet(13, 0);\n SoftPWMSet(3, 0);\n SoftPWMSet(4, 0);\n delay(500);\n }\n */\n\n if (my_type == device_locator.type_SU){\n uint8_t start_freqs[num_actuator_pins] = {51,25,25,51,51,51,51,51,51,\n 51,51,51,51,51,51,51,51,51};\n uint8_t start_amps[num_actuator_pins] = {255,255,255,130,130,130,130,130,130,\n 130,130,130,130,130,130,130,130,130};\n uint8_t start_phases[num_actuator_pins] = {0,127,0,0,0,0,0,0,0,\n 0,0,0,0,0,0,0,0,0};\n //behaviours.start_SINE(actuator_pins, start_freqs, start_amps, start_phases, num_actuator_pins);\n }\n\n// if (my_type == device_locator.type_BP){\n// uint8_t SMA_count = 0;\n// for (int pin = 0; pin < device_locator.BP_pins_num; pin++){\n// if (device_locator.BP_pins_types[pin] == device_locator.type_SMA){\n// pinMode(device_locator.BP_pins[pin], OUTPUT);\n// SMA_list[SMA_count].init_SMA(device_locator.BP_pins[pin]);\n// SMA_count++;\n// }\n// }\n// }\n \n}\n\nvoid loop() {\n\n // this loops starts running after the node registers\n \n //digitalWrite(led_pin, HIGH);\n\n // ---------------\n // ----SENSORS----\n // ---------------\n // check for IR triggers, send message back to Pi when triggered\n for (uint8_t ir = 0; ir < behaviours.my_num_IR_sensors; ir++){\n if (behaviours.IR_triggered[ir]){\n millis_of_last_comm_or_trigger = millis(); \n uint8_t trigger_hi = (behaviours.IR_vals[ir] >> 8) & 0xff;\n uint8_t trigger_lo = behaviours.IR_vals[ir] & 0xff;\n uint8_t ir_trigger_packet[3] = {ir, trigger_hi, trigger_lo};\n serial_comm.SendMessage(IR_TRIGGER, ir_trigger_packet, 3);\n behaviours.IR_triggered[ir] = false;\n //behaviours.start_BP_IR_trigger();\n // ROM\n if (my_type == device_locator.type_BP){\n behaviours.start_BP_IR_trigger_reflex(ir);\n// behaviours.start_BP_IR_trigger_SMA(ir);\n }\n\n if (my_type == device_locator.type_LC){\n behaviours.start_IR_REACTION_LIGHT_COLUMN();\n //behaviours.start_DELAYED_FADE_ACTUATOR_GROUP_one_pin(0, 25, 200, 3000);\n //behaviours.start_DELAYED_FADE_ACTUATOR_GROUP_one_pin(1500, 32, 200, 3000);\n //behaviours.start_DELAYED_FADE_ACTUATOR_GROUP_one_pin(3000, 25, 0, 3000);\n //behaviours.start_DELAYED_FADE_ACTUATOR_GROUP_one_pin(4500, 32, 0, 3000);\n //uint8_t pin[1] = {32};\n //uint8_t endv[1] = {200};\n //int t[1] = {30000};\n //behaviours.start_FADE_ACTUATOR_GROUP(pin, endv, t,1);\n }\n \n }\n }\n if (behaviours.IR_new_sample){\n uint8_t sample_packet[6];\n for (uint8_t ir = 0; ir < behaviours.max_num_IR_sensors; ir++){\n int sample = behaviours.IR_sampled_vals[ir];\n uint8_t sample_hi = (sample >> 8) & 0xff;\n uint8_t sample_lo = sample & 0xff;\n sample_packet[ir*2] = sample_hi;\n sample_packet[ir*2 + 1] = sample_lo;\n }\n \n serial_comm.SendMessage(IR_SAMPLING, sample_packet, 6);\n behaviours.IR_new_sample = false; \n }\n\n // check for incoming serial messages and act upon them\n if (serial_comm.CheckMessage()){ // returns 1 if message found, 0 otherwise\n millis_of_last_comm_or_trigger = millis();\n if (serial_comm.last_code_received_ == PASSWORD){\n serial_comm.ID[0] = my_id_bytes[0];\n serial_comm.ID[1] = my_id_bytes[1];\n serial_comm.ID[2] = my_id_bytes[2];\n serial_comm.SendMessage(PASSWORD, my_id_bytes, 3);\n serial_registered = true;\n }\n if (serial_comm.last_code_received_ == TEST_LED_PIN_AND_RESPOND){\n uint8_t num_blinks = serial_comm.last_data_received_[0];\n uint8_t test_data[4] = {4,0,0,1};\n behaviours.start_TEST_LED_PIN(num_blinks);\n serial_comm.SendMessage(TEST_LED_PIN_AND_RESPOND, test_data, 4);\n }\n\n if (serial_comm.last_code_received_ == FADE_ACTUATOR_GROUP){\n // each actuator takes 5 bytes to control\n // <pin><end><time_hi><time_lo>\n\n uint8_t num_bytes_per_actuator = 4;\n uint8_t num_actuators = serial_comm.last_data_length_/num_bytes_per_actuator;\n\n uint8_t pins[num_actuators];\n uint8_t end_values[num_actuators]; \n int fade_times[num_actuators];\n for (int a = 0; a < num_actuators ; a++){\n pins[a] = serial_comm.last_data_received_[a*num_bytes_per_actuator]; // first byte is pin\n end_values[a] = serial_comm.last_data_received_[a*num_bytes_per_actuator+1]; // third byte is starting value\n fade_times[a] = (serial_comm.last_data_received_[a*num_bytes_per_actuator+2] << 8) + serial_comm.last_data_received_[a*num_bytes_per_actuator+3]; \n // fourth byte is time hi, fifth byte is time lo\n // fade time in milliseconds = (hi << 8) + lo\n }\n\n // doesn't feel right to access these class members outside of class\n // gotta do what you gotta do\n // handle incoming command while FADEing\n // set the next starting value to whatever the value is now\n for (uint8_t pin = 0; pin < behaviours.max_pin_number + 1; pin++){\n behaviours._previous_end_values_FADE_ACTUATOR_GROUP[pin] = behaviours.PWM_values_FADE_ACTUATOR_GROUP[pin];\n }\n behaviours.start_FADE_ACTUATOR_GROUP(pins, end_values, fade_times, num_actuators);\n \n }\n\n if (serial_comm.last_code_received_ == IR_SAMPLING){\n uint8_t on_or_off = serial_comm.last_data_received_[0];\n int sampling_interval = (serial_comm.last_data_received_[1] << 8) + serial_comm.last_data_received_[2]; \n behaviours.start_IR_SAMPLING(on_or_off, sampling_interval);\n }\n\n if (serial_comm.last_code_received_ == SET_IR_THRESHOLD){\n if (my_type == device_locator.type_SSS || my_type == device_locator.type_BP || my_type == device_locator.type_LC){\n uint8_t ir_num = serial_comm.last_data_received_[0];\n int threshold_value = (serial_comm.last_data_received_[1] << 8) + serial_comm.last_data_received_[2];\n if (ir_num == 0){\n behaviours.start_IR_TRIGGER(threshold_value, behaviours.IR_threshold[1],behaviours.IR_threshold[2]);\n } else if (ir_num == 1){\n behaviours.start_IR_TRIGGER(behaviours.IR_threshold[0], threshold_value,behaviours.IR_threshold[2]);\n } else if (ir_num == 2){\n behaviours.start_IR_TRIGGER(behaviours.IR_threshold[0], behaviours.IR_threshold[1], threshold_value);\n }\n }\n }\n\n if (serial_comm.last_code_received_ == SET_SINE_FREQUENCY){\n uint8_t num_bytes_per_actuator = 2;\n uint8_t num_actuators = serial_comm.last_data_length_/num_bytes_per_actuator;\n\n uint8_t pins[num_actuators];\n uint8_t freqs[num_actuators]; \n for (int a = 0; a < num_actuators ; a++){\n pins[a] = serial_comm.last_data_received_[a*num_bytes_per_actuator]; // first byte is pin\n freqs[a] = serial_comm.last_data_received_[a*num_bytes_per_actuator+1]; // third byte is starting value\n behaviours._frequencies_SINE[pins[a]] = 5*float(freqs[a])/255.0;\n }\n }\n if (serial_comm.last_code_received_ == SET_SINE_AMPLITUDE){\n uint8_t num_bytes_per_actuator = 2;\n uint8_t num_actuators = serial_comm.last_data_length_/num_bytes_per_actuator;\n uint8_t pins[num_actuators];\n uint8_t amps[num_actuators]; \n for (int a = 0; a < num_actuators ; a++){\n pins[a] = serial_comm.last_data_received_[a*num_bytes_per_actuator]; // first byte is pin\n amps[a] = serial_comm.last_data_received_[a*num_bytes_per_actuator+1]; // third byte is starting value\n behaviours._amplitudes_SINE[pins[a]] = 95.0*float(amps[a])/255.0;\n }\n }\n if (serial_comm.last_code_received_ == SET_SINE_PHASE){\n uint8_t num_bytes_per_actuator = 2;\n uint8_t num_actuators = serial_comm.last_data_length_/num_bytes_per_actuator;\n uint8_t pins[num_actuators];\n uint8_t pha[num_actuators]; \n for (int a = 0; a < num_actuators ; a++){\n pins[a] = serial_comm.last_data_received_[a*num_bytes_per_actuator]; // first byte is pin\n pha[a] = serial_comm.last_data_received_[a*num_bytes_per_actuator+1]; // third byte is starting value\n behaviours._phases_SINE[pins[a]] = 2*3.14*float(pha[a])/255.0; \n }\n }\n\n if (serial_comm.last_code_received_ == ACTUATE_SMA){\n \n if (my_type == device_locator.type_BP){\n uint8_t num_bytes_per_actuator = 1;\n uint8_t num_actuators = serial_comm.last_data_length_/num_bytes_per_actuator;\n uint8_t pins[num_actuators];\n for (int a = 0; a < num_actuators ; a++){\n pins[a] = serial_comm.last_data_received_[a*num_bytes_per_actuator]; // first byte is pin\n for (int sma_num = 0; sma_num < behaviours.max_SMA; sma_num++){\n if (pins[a] == behaviours.SMA_list[sma_num].SMA_pin){\n bool actuating = behaviours.SMA_list[sma_num].actuate_if_ready();\n }\n }\n }\n }\n }\n\n if (serial_comm.last_code_received_ == EXCITOR_POSITION){\n uint8_t sign_ex_x = serial_comm.last_data_received_[0];\n if (sign_ex_x == 0x00){\n ex_x = (serial_comm.last_data_received_[1] << 8) + serial_comm.last_data_received_[2];\n } else {\n ex_x = -((serial_comm.last_data_received_[1] << 8) + serial_comm.last_data_received_[2]);\n }\n\n uint8_t sign_ex_y = serial_comm.last_data_received_[3];\n if (sign_ex_y == 0x00){\n ex_y = (serial_comm.last_data_received_[4] << 8) + serial_comm.last_data_received_[5];\n } else {\n ex_y = -((serial_comm.last_data_received_[4] << 8) + serial_comm.last_data_received_[5]);\n }\n\n uint8_t sign_ex_z = serial_comm.last_data_received_[6];\n if (sign_ex_z == 0x00){\n ex_z = (serial_comm.last_data_received_[7] << 8) + serial_comm.last_data_received_[8];\n } else {\n ex_z = -((serial_comm.last_data_received_[7] << 8) + serial_comm.last_data_received_[8]);\n }\n\n behaviours._excitor_pos[0] = ex_x;\n behaviours._excitor_pos[1] = ex_y;\n behaviours._excitor_pos[2] = ex_z;\n \n }\n\n if (serial_comm.last_code_received_ == EXCITOR_PROPERTIES){\n behaviours._excitor_radius = (serial_comm.last_data_received_[0] << 8) + serial_comm.last_data_received_[1];\n behaviours._excitor_force_RS = serial_comm.last_data_received_[2];\n behaviours._excitor_force_moth = serial_comm.last_data_received_[3];\n }\n\n if (serial_comm.last_code_received_ == GAUSSIAN_SHOT){\n int act_time = (serial_comm.last_data_received_[0] << 8) + serial_comm.last_data_received_[1];\n float variance = 0.01;//((serial_comm.last_data_received_[2] << 8) + serial_comm.last_data_received_[3])/10000.0;\n float chain_width = float(serial_comm.last_data_received_[4]);\n behaviours.start_LIGHT_CHAIN(act_time, variance, chain_width);\n }\n\n if (serial_comm.last_code_received_ == DO_NEIGHBOUR_BEHAVIOUR){\n if (my_type == device_locator.type_BP){\n uint8_t BP_index = serial_comm.last_data_received_[0];\n if (BP_index == 1){\n behaviours.start_BP_IR_trigger_reflex(0);\n// behaviours.start_BP_IR_trigger_SMA(0);\n } else if (BP_index == 2){\n behaviours.start_BP_IR_trigger_reflex(1);\n// behaviours.start_BP_IR_trigger_SMA(1);\n }\n }\n }\n\n if (serial_comm.last_code_received_ == SYSTEM_PROPERTIES){\n background_behaviour_min_time = (serial_comm.last_data_received_[0] << 16) + (serial_comm.last_data_received_[1] << 8) + serial_comm.last_data_received_[2];\n background_behaviour_max_time = (serial_comm.last_data_received_[3] << 16) + (serial_comm.last_data_received_[4] << 8) + serial_comm.last_data_received_[5];\n behaviours.prob_RANDOM_ACTUATOR = serial_comm.last_data_received_[6];\n behaviours.ramp_up_time_RANDOM_ACTUATOR = (serial_comm.last_data_received_[7] << 8) + (serial_comm.last_data_received_[8]);\n behaviours.hold_time_RANDOM_ACTUATOR = (serial_comm.last_data_received_[9] << 8) + (serial_comm.last_data_received_[10]);\n behaviours.ramp_down_time_RANDOM_ACTUATOR = (serial_comm.last_data_received_[11] << 8) + (serial_comm.last_data_received_[12]);\n behaviours.cooldown_time_RANDOM_ACTUATOR = (serial_comm.last_data_received_[13] << 8) + (serial_comm.last_data_received_[14]);\n behaviours.max_brightness_RANDOM_ACTUATOR = serial_comm.last_data_received_[15];\n behaviours.local_trigger_act_time = (serial_comm.last_data_received_[16] << 8) + (serial_comm.last_data_received_[17]);\n behaviours.local_trigger_variance = 1.0*float(serial_comm.last_data_received_[18])/100.0;\n behaviours.local_trigger_chain_width = 10.0*float(serial_comm.last_data_received_[19])/100.0;\n behaviours.local_trigger_act_time_AUTO = (serial_comm.last_data_received_[20] << 8) + (serial_comm.last_data_received_[21]);\n behaviours.ramp_up_time_BP_moth = (serial_comm.last_data_received_[22] << 8) + (serial_comm.last_data_received_[23]);\n behaviours.ramp_up_time_BP_RS = (serial_comm.last_data_received_[24] << 8) + (serial_comm.last_data_received_[25]);\n\n behaviours.ramp_down_time_BP_moth = (serial_comm.last_data_received_[26] << 8) + (serial_comm.last_data_received_[27]);\n behaviours.ramp_down_time_BP_RS = (serial_comm.last_data_received_[28] << 8) + (serial_comm.last_data_received_[29]);\n behaviours.hold_time_BP_moth = (serial_comm.last_data_received_[30] << 8) + (serial_comm.last_data_received_[31]);\n behaviours.hold_time_BP_RS = (serial_comm.last_data_received_[32] << 8) + (serial_comm.last_data_received_[33]);\n behaviours.IR_min_time_between_triggers = (serial_comm.last_data_received_[34] << 8) + (serial_comm.last_data_received_[35]);\n }\n \n }\n\n //for (int sma_num = 0; sma_num < max_SMA; sma_num++){\n // SMA_list[sma_num].loop();\n //}\n\n // TEST code\n if (my_type == device_locator.type_LC){\n //behaviours.start_LIGHT_CHAIN(1,1,1,1);\n }\n \n // check to see if we passed idle state threshold\n if (millis() - millis_of_last_comm_or_trigger > background_behaviour_time_threshold){\n // do local trigger reaction\n if (my_type == device_locator.type_LC){\n behaviours.start_IR_REACTION_LIGHT_COLUMN();\n } else if (my_type == device_locator.type_BP){\n int temp = random(0,10);\n if (temp > 5){\n behaviours.start_BP_IR_trigger_reflex(0);\n } else if (temp <= 5) {\n behaviours.start_BP_IR_trigger_reflex(1);\n }\n }\n // record time\n millis_of_last_comm_or_trigger = millis();\n // choose a random time to wait until activating background again\n background_behaviour_time_threshold = random(background_behaviour_min_time, background_behaviour_max_time);\n }\n \n behaviours.loop();\n\n}\n\n\n// Code to read the Teensy ID\nvoid read_EE(uint8_t word, uint8_t *buf, uint8_t offset) {\n noInterrupts();\n FTFL_FCCOB0 = 0x41; // Selects the READONCE command\n FTFL_FCCOB1 = word; // read the given word of read once area\n\n // launch command and wait until complete\n FTFL_FSTAT = FTFL_FSTAT_CCIF;\n while (!(FTFL_FSTAT & FTFL_FSTAT_CCIF));\n *(buf + offset + 0) = FTFL_FCCOB4;\n *(buf + offset + 1) = FTFL_FCCOB5;\n *(buf + offset + 2) = FTFL_FCCOB6;\n *(buf + offset + 3) = FTFL_FCCOB7;\n interrupts();\n}\n\nlong int read_teensyID() {\n read_EE(0xe, teensyID, 0); // should be 04 E9 E5 xx, this being PJRC's registered OUI\n read_EE(0xf, teensyID, 4); // xx xx xx xx\n my_id = (teensyID[5] << 16) | (teensyID[6] << 8) | (teensyID[7]);\n my_id_bytes[0] = teensyID[5];\n my_id_bytes[1] = teensyID[6];\n my_id_bytes[2] = teensyID[7];\n return my_id;\n}\n\nuint8_t get_my_type_and_index(){\n \n for (int node = 0; node < device_locator.num_nodes; node++){\n if (my_id == device_locator.teensy_ids[node]){\n my_type = device_locator.teensy_types[node];\n my_index = node;\n }\n }\n\n if (my_type == device_locator.type_LC){\n behaviours.my_num_pins = device_locator.LC_pins_num;\n for (int pin_index = 0; pin_index < device_locator.LC_pins_num; pin_index++){\n behaviours.my_pins[pin_index] = device_locator.LC_pins[pin_index];\n behaviours.my_pins_types[pin_index] = device_locator.LC_pins_types[pin_index];\n }\n }\n if (my_type == device_locator.type_BP){\n behaviours.my_num_pins = device_locator.BP_pins_num;\n for (int pin_index = 0; pin_index < device_locator.BP_pins_num; pin_index++){\n behaviours.my_pins[pin_index] = device_locator.BP_pins[pin_index];\n behaviours.my_pins_types[pin_index] = device_locator.BP_pins_types[pin_index];\n }\n }\n\n if (my_type == device_locator.type_SU){\n behaviours.my_num_pins = device_locator.SU_pins_num;\n for (int pin_index = 0; pin_index < device_locator.SU_pins_num; pin_index++){\n behaviours.my_pins[pin_index] = device_locator.SU_pins[pin_index];\n behaviours.my_pins_types[pin_index] = device_locator.SU_pins_types[pin_index];\n }\n }\n\n if (my_type == device_locator.type_SSS){\n behaviours.my_num_pins = device_locator.SSS_pins_num;\n for (int pin_index = 0; pin_index < device_locator.SSS_pins_num; pin_index++){\n behaviours.my_pins[pin_index] = device_locator.SSS_pins[pin_index];\n behaviours.my_pins_types[pin_index] = device_locator.SSS_pins_types[pin_index];\n }\n }\n}\n\nuint8_t set_pinMode_for_all_of_my_pins(){\n uint8_t IR_count = 0;\n for (int pin_index = 0; pin_index < behaviours.my_num_pins; pin_index++){\n if (behaviours.my_pins_types[pin_index] == device_locator.type_IR){\n pinMode(behaviours.my_pins[pin_index], INPUT);\n behaviours.IR_pins[IR_count] = behaviours.my_pins[pin_index];\n IR_count += 1;\n } else {\n pinMode(behaviours.my_pins[pin_index], OUTPUT);\n }\n }\n\n behaviours.my_num_IR_sensors = IR_count;\n}\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.41742101311683655,
"alphanum_fraction": 0.4281810522079468,
"avg_line_length": 39.05882263183594,
"blob_id": "489319116a7c8f3ffe07e2e011e702135f991f6b",
"content_id": "af64e56c79cb26b6530e20aa989232c59d60fbd1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11710,
"license_type": "no_license",
"max_line_length": 163,
"num_lines": 289,
"path": "/Device Locator/device_locator_generator.py",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "# converts actuator locator.csv to device_locator.py\nimport time\n\n#with open('AMATRIA - Actuator Locator.csv','r') as al:\nwith open('Daejeon - Actuator Locator.csv','r') as al:\n\n with open(\"DeviceLocator.py\", 'w') as f:\n f.write('# DeviceLocator.py, autogenerated by device_locator_generator.py\\n')\n f.write(\"# Date: [\" + time.strftime(\"%B %d %Y at %H %M %S\") + \"]\\n\")\n f.write('# Defines the location of actuators in a sculpture.\\n')\n f.write('# DeviceLocator.sculpture[section][actuator] =')\n f.write(' (RPi IP, Teensy ID, pin number, x,y,z)\\n')\n f.write('# Example: DeviceLocator.amatria[\\'SPHERE1\\'][\\'RS11\\'][\\'pin_number\\'] =')\n f.write(' 3\\n\\n')\n f.write('class DeviceLocator():\\n')\n f.write('\\tdef __init__(self):\\n')\n\n lines = al.readlines()\n IP_MASTER = lines[0].strip().split(',')[1]\n IP_4D = lines[1].strip().split(',')[1]\n temp_IP_Pi_list = lines[2].strip().split(',')[1:]\n IP_Pi_list = []\n for pi in temp_IP_Pi_list:\n if pi != '':\n IP_Pi_list.append(pi)\n lines = lines[4:]\n \n f.write('\\t\\tself.IP_MASTER = \\'' + IP_MASTER + '\\'\\n')\n f.write('\\t\\tself.IP_4D_LAPTOP = \\'' + IP_4D + '\\'\\n')\n\n f.write('\\t\\tself.pi_ip_addresses = [')\n for i in range(len(IP_Pi_list)):\n ip = IP_Pi_list[i]\n f.write('\\'' + ip + '\\'')\n if i != len(IP_Pi_list) - 1:\n f.write(', ')\n f.write(']\\n')\n \n f.write('\\t\\tself.amatria = {\\n')\n\n current_section = 'null'\n\n for line in lines:\n switched = False\n section, actuator, pi_ip, teensy_id_int, pin_number, x, y, z, installed, peripheral_type = line.strip().split(',')\n #pi_ip = '10.14.4.155'\n #teensy_id_int = '245744'\n #pin_number = '13'\n if current_section != section:\n if current_section != 'null':\n f.write('},\\n')\n f.write('\\t\\t\\'' + section + '\\':{\\n')\n current_section = section\n switched = True\n else:\n f.write(',\\n')\n f.write('\\t\\t\\t\\'' + actuator + '\\':{')\n f.write('\\n\\t\\t\\t\\t\\'pi_ip\\':\\'' + pi_ip + '\\',')\n f.write('\\n\\t\\t\\t\\t\\'teensy_id_int\\':' + teensy_id_int + ',')\n f.write('\\n\\t\\t\\t\\t\\'teensy_id_bytes\\':bytes([' + str((int(teensy_id_int) >> 16) & 255) + ',' +\n str((int(teensy_id_int) >> 8) & 255) + ',' +\n str(int(teensy_id_int) & 255) + ']),')\n if 'IR' in actuator:\n f.write('\\n\\t\\t\\t\\t\\'pin_number\\':\\''+ pin_number + '\\',')\n else: \n f.write('\\n\\t\\t\\t\\t\\'pin_number\\':'+ pin_number + ',')\n f.write('\\n\\t\\t\\t\\t\\'type\\':\\'' + peripheral_type + '\\',')\n f.write('\\n\\t\\t\\t\\t\\'position\\':('+ x + ',' + y + ',' + z + ')}')\n \n f.write('}}')\n\n\nwith open('ROM - Actuator Locator.csv','r') as al:\n \n## with open(\"node_dl.txt\", 'w') as f:\n##\n## lines = al.readlines()\n## lines = lines[1:]\n##\n## current_section = 'null'\n##\n## f.write('{')\n## count = 0\n## for line in lines:\n## switched = False\n## section, actuator, pi_ip, teensy_id_int, pin_number, x, y, z, installed, peripheral_type = line.strip().split(',')\n## if 'SPHERE' in section:\n##\n## if count == 0:\n## f.write('{{' + str(int(float(x))) + ',' + str(int(float(y))) + ',' + str(int(float(z))) + '},')\n## elif count == 11:\n## f.write('{' + str(int(float(x))) + ',' + str(int(float(y))) + ',' + str(int(float(z))) + '}},\\n')\n## print(\"here\")\n##\n## else:\n## f.write('{' + str(int(float(x))) + ',' + str(int(float(y))) + ',' + str(int(float(z))) + '},')\n## \n## count +=1\n## print(count)\n##\n## if count == 12:\n## count = 0\n##\n## f.write('\\n')\n## f.write('{')\n## for line in lines:\n## section, actuator, pi_ip, teensy_id_int, pin_number, x, y, z, installed, peripheral_type = line.strip().split(',')\n## if 'SPHERE' in section:\n## if current_section != section:\n## f.write(str(teensy_id_int) + ',')\n## current_section = section\n \n with open(\"DeviceLocator.h\", 'w') as f:\n lines = al.readlines()\n lines = lines[4:]\n\n # first write headers and clas definition\n f.write('#include <Arduino.h>\\n#include <stdint.h>\\n#ifndef DEVICE_LOCATOR_H_\\n#define DEVICE_LOCATOR_H_\\n')\n f.write('class DeviceLocator{\\n')\n f.write(' public:\\n DeviceLocator();\\n ~DeviceLocator();\\n')\n f.write('\\n')\n \n # section types\n f.write('\\n // Node types\\n')\n f.write(' uint8_t type_SSS = 0; // Sound Sensor Scout: Amatria\\n uint8_t type_SU = 1; // SphereUnit: Astrocyte, Amatria, Noosphere\\n')\n f.write(' uint8_t type_BP = 2; // Breathing Pore (Cluster): Aegis, Daejeon\\n uint8_t type_LC = 3; // Light Column: Daejeon\\n')\n f.write(' uint8_t type_ERROR_UNKNOWN = 98;\\n uint8_t type_test = 99;\\n')\n f.write('\\n')\n \n id_type_tuples = []\n\n for line in lines:\n section, actuator, pi_ip, teensy_id_int, pin_number, x, y, z, installed, peripheral_type = line.strip().split(',')\n int_id = teensy_id_int\n if 'SPHERE' in section:\n ty = 'type_SU'\n elif 'SSS' in section:\n ty = 'type_SSS'\n elif 'BP' in section:\n ty = 'type_BP'\n elif 'LC' in section:\n ty = 'type_LC'\n elif 'TEST' in section:\n ty = 'type_test'\n else:\n ty = 'type_ERROR_UNKNOWN'\n\n if (int_id,ty) not in id_type_tuples:\n id_type_tuples.append((int_id, ty))\n \n\n num_nodes = len(id_type_tuples)\n\n f.write(' int num_nodes = ' + str(num_nodes) + ';\\n')\n\n f.write(' // The type of the node with id teensy_ids[i] is teensy_types[i]\\n')\n\n f.write(' long teensy_ids[' + str(num_nodes) + '] = {')\n for node in range(num_nodes):\n\n if node == 0:\n f.write(id_type_tuples[node][0] + ',\\n')\n elif node == num_nodes - 1:\n f.write(' '*28 + id_type_tuples[node][0] + '};\\n')\n else:\n f.write(' '*28 + id_type_tuples[node][0] + ',\\n')\n\n f.write(' int teensy_types[' + str(num_nodes) + '] = {')\n for node in range(num_nodes):\n\n if node == 0:\n f.write(id_type_tuples[node][1] + ',\\n')\n elif node == num_nodes - 1:\n f.write(' '*28 + id_type_tuples[node][1] + '};\\n')\n else:\n f.write(' '*28 + id_type_tuples[node][1] + ',\\n')\n\n # pins for each type\n\n f.write(' // Pins for each type of node. Assumes that actuators on nodes of the same type have identical pin locations\\n\\n')\n f.write(' // Actuator and Sensor types\\n uint8_t type_LED = 0;\\n uint8_t type_moth = 1;\\n uint8_t type_SMA = 2;\\n uint8_t type_IR = 10;\\n')\n f.write('\\n')\n\n # find nodes of each type\n SU_node_id = 0\n BP_node_id = 0\n SSS_node_id = 0\n LC_node_id = 0\n\n pins = [[],[],[],[]]\n types = [[],[],[],[]]\n for node in id_type_tuples:\n if node[1] == 'type_SU':\n SU_node_id = node[0]\n if node[1] == 'type_BP':\n BP_node_id = node[0]\n if node[1] == 'type_SSS':\n SSS_node_id = node[0]\n if node[1] == 'type_LC':\n LC_node_id = node[0]\n node_ids = [SU_node_id, BP_node_id, SSS_node_id, LC_node_id]\n \n for line in lines:\n section, actuator, pi_ip, teensy_id_int, pin_number, x, y, z, installed, peripheral_type = line.strip().split(',')\n for i in range(len(node_ids)):\n if teensy_id_int == node_ids[i]:\n pins[i].append(pin_number)\n if 'RS' in actuator:\n types[i].append('type_LED')\n if 'MOTH' in actuator:\n types[i].append('type_moth')\n if 'SMA' in actuator:\n types[i].append('type_SMA')\n if 'IR' in actuator:\n types[i].append('type_IR')\n\n pin_variable_names = ['SU_pins', 'BP_pins', 'SSS_pins', 'LC_pins']\n for i in range(len(pin_variable_names)):\n if len(pins[i]) != 0:\n\n f.write(' int ' + pin_variable_names[i] + '_num = ' + str(len(pins[i])) + ';\\n')\n f.write(' int ' + pin_variable_names[i] + '[' + str(len(pins[i])) + '] = {')\n for p in range(len(pins[i])):\n if p == len(pins[i]) - 1:\n f.write(pins[i][p] + '};\\n')\n else:\n f.write(pins[i][p] + ', ')\n \n f.write(' int ' + pin_variable_names[i] + '_types[' + str(len(types[i])) + '] = {')\n for p in range(len(types[i])):\n if p == len(types[i]) - 1:\n f.write(types[i][p] + '};\\n')\n else:\n f.write(types[i][p] + ', ')\n \n else:\n f.write(' int ' + pin_variable_names[i] + '_num = 0;\\n')\n f.write(' int ' + pin_variable_names[i] + '[0] = {};\\n')\n f.write(' int ' + pin_variable_names[i] + '_types[0] = {};\\n')\n \n f.write('\\n')\n\n # Coordinates\n teensy_ids = []\n pin_lists = []\n coordinate_lists = []\n node = -1\n for line in lines:\n section, actuator, pi_ip, teensy_id_int, pin_number, x, y, z, installed, peripheral_type = line.strip().split(',')\n\n if teensy_id_int not in teensy_ids:\n teensy_ids.append(teensy_id_int)\n pin_lists.append([])\n coordinate_lists.append([])\n node += 1\n pin_lists[node].append(pin_number)\n coordinate_lists[node].append([x,y,z])\n\n # find max pin amount\n m = 0\n for l in pin_lists:\n if len(l) > m:\n m = len(l)\n \n\n f.write(' int coordinates[' + str(num_nodes) + '][' + str(m) + '][3] = {\\n')\n\n for node in range(len(teensy_ids)):\n node_coords_list = coordinate_lists[node]\n f.write(' '*8 + '{')\n for i in range(m):\n if i < len(node_coords_list):\n coords = node_coords_list[i]\n f.write('{' + str(int(float(coords[0]))) + ',' + str(int(float(coords[1]))) + ',' + str(int(float(coords[2]))) + '}')\n else:\n f.write('{0,0,0}')\n if i != m -1:\n f.write(',')\n f.write('}')\n if node != len(teensy_ids) -1:\n f.write(',')\n\n f.write('\\n')\n f.write(' '*4 + '};\\n')\n \n \n \n\n f.write('};\\n#endif //DEVICE_LOCATOR_H_')\n \n \n \n \n \n \n \n\n\n\n"
},
{
"alpha_fraction": 0.5757030248641968,
"alphanum_fraction": 0.5948256254196167,
"avg_line_length": 24.693641662597656,
"blob_id": "d67f28f8c83f131f3dfb932227a91620150df80c",
"content_id": "89786e61348875ef4033f538688f2095aa1ea969",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 4445,
"license_type": "no_license",
"max_line_length": 116,
"num_lines": 173,
"path": "/Teensy/DaejeonNode/NodeSerial.cpp",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "/*\n* NodeSerial.cpp - Library for Communication Protocol between Raspberry Pi and Node\n* created By Adam Francey March 13, 2018\n* Modified from usb_serial_comm.cpp created By Adam Francey, Kevin Lam, July 5, 2017\n* Released for Luddy Hall 2018\n* Philip Beesley Architect Inc. / Living Architecture Systems Group\n*\n* Message Format (see related doc [WIP] for details)\n* where <value> is the value represented as a byte:\n* <SOM1><SOM2><TeensyId1><TeensyId2><TeensyId3><total number of bytes in message><code><data1>...<dataN><EOM1><EOM2>\n*/\n\n#include <Arduino.h>\n#include <stdint.h>\n#include \"NodeSerial.h\"\n\nNodeSerial::NodeSerial(){\n Serial.begin(57600);\n}\n\nNodeSerial::NodeSerial(int baud_rate){\n Serial.begin(baud_rate);\n}\n\nNodeSerial::~NodeSerial(){}\n\nvoid NodeSerial::SendMessage(uint8_t code){\n // Send SOM\n for (int i = 0; i < NUM_SOM; i++){\n Serial.write(SOM[i]);\n }\n\n // Send TeensyID\n for (int i = 0; i < NUM_ID; i++){\n Serial.write(ID[i]);\n }\n\n // Send message length\n // SOM ID length code EOM\n uint8_t message_length = NUM_SOM + NUM_ID + 1 + 1 + NUM_EOM;\n Serial.write(message_length);\n\n // Send code\n Serial.write(code);\n\n // Send EOM\n for (int i = 0; i < NUM_EOM; i++){\n Serial.write(EOM[i]);\n }\n\n}\n\n\nvoid NodeSerial::SendMessage(uint8_t code, uint8_t data[], uint8_t data_length){\n\n // Send SOM\n for (int i = 0; i < NUM_SOM; i++){\n Serial.write(SOM[i]);\n }\n\n // Send TeensyID\n for (int i = 0; i < NUM_ID; i++){\n Serial.write(ID[i]);\n }\n\n // Send data length\n Serial.write(data_length);\n\n // Send code\n Serial.write(code);\n \n // Send data\n for (uint8_t i = 0; i < data_length; i++){\n Serial.write(data[i]);\n }\n\n // Send EOM\n for (int i = 0; i < NUM_EOM; i++){\n Serial.write(EOM[i]);\n }\n\n}\n\n\n// CheckMessage\n// Reads the serial port for an incoming sequence of bytes\n// if sequence follows requirements of a message defined in docs, returns 1 and\n// updates the following NodeSerial members:\n// last_data_length, last_code_received, last_data_received, message_waiting\n// if requirements fail, returns 0\nbool NodeSerial::CheckMessage(){\n\n message_waiting_ = 0;\n\n //if (Serial.available()>=MESSAGE_LENGTH){\n if (Serial.available()>NUM_SOM + 4){ // at least 7 bytes for SOM, ID, length, code\n\n // Teensy ID\n uint8_t t1;\n uint8_t t2;\n uint8_t t3;\n\n // modifiers\n uint8_t data_length;\n uint8_t code;\n\n // check for SOM (bytes 0-1)\n // we are expecting SOM bytes in sequence (currently: {0xff,0xff})\n for (int s = 0; s < NUM_SOM; s++){\n if (Serial.read() != SOM[s]){\n // Fail: SOM byte missing\n // So CheckMessage fails (no message found) and we stop reading serial port\n return 0;\n }\n }\n // if we make it here, we have found all SOM bytes\n\n // Teensy ID (bytes 2-4)\n t1 = Serial.read();\n t2 = Serial.read();\n t3 = Serial.read();\n\n // data_length (byte 5)\n data_length = Serial.read();\n\n // command/code (byte 6)\n code = Serial.read();\n\n // SOM (2 bytes), Teensy ID (3 bytes), message length (1 byte), code (1 byte) should take up 7 bytes\n // we are now expecting num_bytes_to_receive more bytes (including EOM)\n uint8_t data[data_length];\n\n if (Serial.available()>data_length+1){ // at least enough bytes for data and EOM\n\n for (uint8_t i = 0; i < data_length; i++){\n // read in data bytes\n data[i] = Serial.read();\n }\n \n // check for EOM\n for (int e = 0; e < NUM_EOM; e++){\n if (Serial.read() != EOM[e]){\n // Fail: EOM byte missing\n // something went wrong: num_bytes_in_message tells us to expect EOM here but we didn't find it\n // CheckMessage fails, stop reading serial port\n // bytes read up until this point will be discarded\n return 0;\n }\n }\n // If we make it here, we have found all EOM bytes\n \n // Success: Full message found\n // update class members\n // note: this will be overwritten on the next message successfully recieved\n last_data_length_ = data_length;\n last_code_received_ = code;\n for (int i = 0; i < data_length; i++){\n last_data_received_[i] = data[i];\n }\n message_waiting_ = 1;\n return 1;\n } else {\n //Fail: not enough bytes\n return 0;\n }\n\n\n\n } else {\n // Fail: not enough bytes\n return 0;\n }\n}\n"
},
{
"alpha_fraction": 0.6385542154312134,
"alphanum_fraction": 0.6807228922843933,
"avg_line_length": 22.714284896850586,
"blob_id": "6f792c30f7671c24221938dcfa71b96d071df35d",
"content_id": "d304e24f0b4c75a18f3cdbbef4b732cecbfc9eb1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1162,
"license_type": "no_license",
"max_line_length": 89,
"num_lines": 49,
"path": "/Archive/Teensy/LuddyNode/NodeSerial.h",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "/*\n* usb_serial_comm.cpp - Library for Communication Protocol between Raspberry Pi and Node\n* Created By Adam Francey, Kevin Lam, July 5, 2017\n* Released for Desktop Kit\n* Philip Beesley Architect Inc. / Living Architecture Systems Group\n*/\n\n#ifndef NODE_SERIAL_H_\n#define NODE_SERIAL_H_\n\n// Delimiters\n#define SOM1 0xff\n#define SOM2 0xff\n#define EOM1 0xfe\n#define EOM2 0xfe\n#define NUM_SOM 2\n#define NUM_EOM 2\n#define NUM_ID 3\n#define PADDING_BYTE 0xfd\n\n#define MAX_DATA_LENGTH 255\n\nclass NodeSerial{\n\n public:\n NodeSerial();\n NodeSerial(int baud_rate);\n ~NodeSerial();\n\n bool initialized = false;\n byte password[8] = {0xff,0xff,0x04,0x00,0x00,0x01,0xfe,0xfe};\n int password_length = 8;\n\n void SendMessage(uint8_t code);\n void SendMessage(uint8_t msg, uint8_t data[], uint8_t data_length);\n bool CheckMessage();\n\n uint8_t last_data_received_[MAX_DATA_LENGTH] = { 0 };\n int last_data_length_;\n uint8_t last_code_received_;\n bool message_waiting_ = 0; // whether or not a received message needs to be processed\n\n uint8_t SOM[2] = {SOM1,SOM2};\n uint8_t EOM[2] = {EOM1,EOM2};\n uint8_t ID[3] = {0x00,0x00,0x00}; //placeholder\n\n};\n\n#endif //NODE_SERIAL_H_\n"
},
{
"alpha_fraction": 0.5666247606277466,
"alphanum_fraction": 0.5807667970657349,
"avg_line_length": 32.61701965332031,
"blob_id": "229969f81d26bb00d5e0df8a8c92420f0a8b46ea",
"content_id": "785d95cd1b1e3e715d076ef4d18e66b317cd6b5a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3182,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 94,
"path": "/Raspberry Pi/PiUDP.py",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "# PiUDP.py - LASG/PBAI\n# Created by Adam France, March 16 2018\n# Handles UDP communication between Raspberry Pi and master laptop\n\nimport socket\nimport threading\nimport queue\n\nclass PiUDP():\n def __init__(self, ip_laptop, port_receive, port_send):\n\n # received data in bytes in queue\n self.data_bytes_queue = queue.Queue()\n\n # received data as a utf-8 string\n self.data_string = ''\n\n # address we receive from\n self.addr = ''\n\n self.ip_laptop = ip_laptop # master laptop\n self.port_receive = port_receive\n self.port_send = port_send\n\n self.sock_transmit = socket.socket(socket.AF_INET, # Internet\n socket.SOCK_DGRAM) # UDP\n\n self.sock_receive = socket.socket(socket.AF_INET, # Internet\n socket.SOCK_DGRAM) # UDP\n self.sock_receive.bind(('0.0.0.0', port_receive))\n\n \n # set to False when we close the sockets\n self.running = True\n\n # we listen for incoming bytes continuously on a separate thread\n self.listening_thread = threading.Thread(target = self.receive_bytes)\n self.listening_thread.start()\n print(\"Starting UDP receiver - Port: \" + str(port_receive))\n print(\"Starting UDP sender - Address: \" + ip_laptop + \" , Port: \" + str(port_send))\n\n def send_bytes(self, raw_bytes):\n #print(\"Sending UDP: \" + str(raw_bytes))\n self.sock_transmit.sendto(raw_bytes, (self.ip_laptop, self.port_send))\n\n def receive_bytes(self):\n while self.running:\n # recvfrom blocks until it receives a UDP packet\n data_bytes, self.addr = self.sock_receive.recvfrom(1024) # buffer size is 1024 bytes\n\n # store the packet in the queue\n self.data_bytes_queue.put(data_bytes)\n #print(\"Received UDP - Address: \" + self.addr[0] + \", Data: \" + str(data_bytes))\n \n\n def send_string(self, string):\n self.sock_transmit.sendto(bytes(string, 'utf-8'), (self.ip_laptop, self.port_send))\n\n def receive_string(self):\n while self.running:\n self.data_string, addr = self.sock_receive.recvfrom(1024) # buffer size is 1024 bytes\n print(\"Received string: \" + str(self.data_string, 'utf-8'))\n\n def decode_bytes(self, raw_bytes):\n\n # teensy id\n tid_bytes = raw_bytes[2:5]\n tid =((tid_bytes[0] << 16) | (tid_bytes[1] << 8)) | tid_bytes[2]\n\n # number of data bytes\n length = raw_bytes[5:6][0]\n\n # instruction code\n code = raw_bytes[6:7]\n\n # data in bytes\n data_bytes = raw_bytes[7:7+length]\n\n #convert data to list of ints\n data = []\n for d in range(length):\n data.append(data_bytes[d])\n\n return code, data, tid\n\n def close(self):\n # NEEDS WORK -------------------------------------\n print(\"Closing UDP sockets\")\n self.running = False\n #self.sock_transmit.shutdown(socket.SHUT_WR)\n #self.sock_receive.shutdown(socket.SHUT_RD)\n self.sock_transmit.close()\n self.sock_receive.close()\n #self.listening_thread.join()\n \n \n"
},
{
"alpha_fraction": 0.7225661277770996,
"alphanum_fraction": 0.7743387818336487,
"avg_line_length": 26.33846092224121,
"blob_id": "363f9ec867f783790304820d1c7c8d1e6226688c",
"content_id": "381c5824a80113d4ead3b60d21339c4df329ff53",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1777,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 65,
"path": "/Utilities/OSC_Script_System_Properties_Control.py",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "import random\nimport time\nimport threading\n\nfrom pythonosc import osc_message_builder\nfrom pythonosc import udp_client\n\n##IP_MASTER = '10.14.4.199'\nIP_MASTER = '192.168.2.33'\n\nclient = udp_client.UDPClient(IP_MASTER, 3001)\n\n\n#Background Behaviour Timing Parameters\nbackground_behaviour_min_time = 15000\nbackground_behaviour_max_time = 30000\n\n#Lone Actuator Selection\nprob_RANDOM_ACTUATOR = 20\nramp_up_time_RANDOM_ACTUATOR = 1500\nhold_time_RANDOM_ACTUATOR =1500\nramp_down_time_RANDOM_ACTUATOR = 1500\ncooldown_time_RANDOM_ACTUATOR = 1500\nmax_brightness_RANDOM_ACTUATOR = 240\n\n#Light Column Timing Parameters\nlocal_trigger_act_time = 1500\nlocal_trigger_variance = 0.001\nlocal_trigger_chain_width = 8.0\nlocal_trigger_act_time_AUTO = 0.5\n\n#BP reflex behaviour\nramp_up_time_BP_moth=1500;\nramp_up_time_BP_RS=1500;\nramp_down_time_BP_moth=1500;\nramp_down_time_BP_RS=1500;\nhold_time_BP_moth=1500;\nhold_time_BP_RS=1500;\n\n#IR cool down time between triggers\nIR_min_time_between_triggers=1000\n\nprint(\"Sending Values\")\nmsg = osc_message_builder.OscMessageBuilder(address = \"/ML/SYSTEM_PROPERTIES\")\nmsg.add_arg(prob_RANDOM_ACTUATOR)\nmsg.add_arg(ramp_up_time_RANDOM_ACTUATOR)\nmsg.add_arg(hold_time_RANDOM_ACTUATOR)\nmsg.add_arg(ramp_down_time_RANDOM_ACTUATOR)\nmsg.add_arg(cooldown_time_RANDOM_ACTUATOR)\nmsg.add_arg(max_brightness_RANDOM_ACTUATOR)\nmsg.add_arg(local_trigger_act_time)\nmsg.add_arg(local_trigger_variance)\nmsg.add_arg(local_trigger_chain_width)\nmsg.add_arg(local_trigger_act_time_AUTO)\nmsg.add_arg(ramp_up_time_BP_moth)\nmsg.add_arg(ramp_up_time_BP_RS)\nmsg.add_arg(ramp_down_time_BP_moth)\nmsg.add_arg(ramp_down_time_BP_RS)\nmsg.add_arg(hold_time_BP_moth)\nmsg.add_arg(hold_time_BP_RS)\nmsg.add_arg(IR_min_time_between_triggers)\nmsg = msg.build()\nclient.send(msg)\n\nprint(\"Sent Values\")\n"
},
{
"alpha_fraction": 0.5752426981925964,
"alphanum_fraction": 0.6650485396385193,
"avg_line_length": 20.526315689086914,
"blob_id": "654375835ad54beb480a049f486669bbe595c63c",
"content_id": "6781c3086e7dec56cf29e3325823c936a57d8c78",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 412,
"license_type": "no_license",
"max_line_length": 73,
"num_lines": 19,
"path": "/Utilities/SHUT_OFF.py",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "import random\nimport time\n\nfrom pythonosc import osc_message_builder\nfrom pythonosc import udp_client\n\nIP_MASTER = \"192.168.1.8\"\n#IP_MASTER = \"192.168.2.24\"\n#IP_MASTER = '10.14.4.198'\nIP_MASTER = '10.14.4.178'\n\n\n\nif __name__ == \"__main__\":\n\n client = udp_client.UDPClient(IP_MASTER, 3001)\n msg = osc_message_builder.OscMessageBuilder(address = \"/ML/SHUT_OFF\")\n msg = msg.build()\n client.send(msg)\n\n\n\n"
},
{
"alpha_fraction": 0.5334057807922363,
"alphanum_fraction": 0.5442694425582886,
"avg_line_length": 29.824562072753906,
"blob_id": "d8948a398a5b8e3eb45b3fdca3beef3657958b47",
"content_id": "2fa23fbc329f198333e6a097815e7473a406f403",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1841,
"license_type": "no_license",
"max_line_length": 85,
"num_lines": 57,
"path": "/Master Laptop/FutureActions.py",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "import time\n\nclass FutureActions():\n\n def __init__(self):\n\n # list of functions to do in the future\n self.future_functions = []\n \n # list of times since function was added\n self.elapsed_time = []\n\n def add_function(self, time_to_wait, function, *args):\n # time_to_wait: ms\n self.future_functions.append([function, args])\n self.elapsed_time.append([time.time(),time_to_wait/1000])\n\n def do_if_time_elapsed_and_remove(self):\n items_to_remove = []\n for i in range(len(self.elapsed_time)):\n time_added = self.elapsed_time[i][0]\n time_to_wait = self.elapsed_time[i][1]\n if time.time() - time_added >= time_to_wait:\n function = self.future_functions[i][0]\n args = self.future_functions[i][1]\n function(*args)\n items_to_remove.append(i)\n\n self.remove_functions(items_to_remove)\n\n def remove_functions(self, items_to_remove):\n offset = 0\n for i in items_to_remove:\n item = i - offset\n del(self.future_functions[item])\n del(self.elapsed_time[item])\n offset += 1\n \n def reset(self):\n # list of functions to do in the future\n self.future_functions = []\n \n # list of times since function was added\n self.elapsed_time = []\n\nif __name__ == \"__main__\":\n # example usage\n future_manager = FutureActions()\n\n def print_two(a,b):\n print(a + b)\n\n future_manager.add_function(2000,print,\"hello world 2 seconds\")\n future_manager.add_function(3000,print_two,\"hello world 3 seconds\", \" plus more\")\n\n while True:\n future_manager.do_if_time_elapsed_and_remove()\n\n \n \n \n \n \n \n \n"
},
{
"alpha_fraction": 0.625,
"alphanum_fraction": 0.8333333134651184,
"avg_line_length": 24,
"blob_id": "52ca611e9b37f8325896102ab8bf22084cea21b9",
"content_id": "ab64dc0c33c403735e140b6079649b029d740d7f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 24,
"license_type": "no_license",
"max_line_length": 24,
"num_lines": 1,
"path": "/Archive/README.md",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "# 18534-Daejeon-Biennale"
},
{
"alpha_fraction": 0.6229507923126221,
"alphanum_fraction": 0.6775956153869629,
"avg_line_length": 19.16666603088379,
"blob_id": "54be8ccd6cab4f36c27377294c21aa7d8f9669c2",
"content_id": "385c3a4a9c8857540f697a80680a7b585d6aaacd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 366,
"license_type": "no_license",
"max_line_length": 81,
"num_lines": 18,
"path": "/Utilities/STOP_IR_SAMPLING.py",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "import random\nimport time\n\nfrom pythonosc import osc_message_builder\nfrom pythonosc import udp_client\n\nIP_MASTER = '10.14.4.198'\nIP_MASTER = \"10.14.4.178\"\n\n\n\nif __name__ == \"__main__\":\n\n client = udp_client.UDPClient(IP_MASTER, 3001)\n\n msg = osc_message_builder.OscMessageBuilder(address = \"/TV/IR_SAMPLING/STOP\")\n msg = msg.build()\n client.send(msg)\n\n\n\n"
},
{
"alpha_fraction": 0.48477157950401306,
"alphanum_fraction": 0.510152280330658,
"avg_line_length": 21.882352828979492,
"blob_id": "4dff2598e52348f75dab2d92c19f185011a05a80",
"content_id": "d9bb42bf0672b1452de4df3289053d8344bbf46b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 788,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 34,
"path": "/Master Laptop/Excitor.py",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "class Excitor():\n\n def __init__(self):\n\n self.position = [0,0,0]\n self.radius = 100\n self.force_RS = 0\n self.force_moth = 0\n \n self.intensity = 0\n self.attack = 0\n self.release = 0\n\n self.max_intensity = 190\n\n\n def distance(self,position):\n\n norm = (sum([(c[0] - c[1])**2 for c in zip(self.position,position)]))**(1/2)\n \n return norm\n\n def get_PWM_properties(self, position):\n\n dist = self.distance(position)\n #print(\"dist: \" + str(dist))\n #print(\"pos: \" + str(position))\n #print(\"self.pos: \" + str(self.position))\n\n if dist > self.radius:\n return 0\n\n else:\n return int(self.max_intensity*(self.radius-dist)/self.radius)\n\n \n"
},
{
"alpha_fraction": 0.6223984360694885,
"alphanum_fraction": 0.6313181519508362,
"avg_line_length": 18.764705657958984,
"blob_id": "12c0b9508c5072ab9abea8c03fe3d8cb580e2a20",
"content_id": "a3ece6fef2168ca08ed7f65d0faec4669b69fb8f",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1009,
"license_type": "no_license",
"max_line_length": 82,
"num_lines": 51,
"path": "/Teensy/DaejeonNode/SMA.cpp",
"repo_name": "pbarch/18534-Daejeon-Biennale",
"src_encoding": "UTF-8",
"text": "#include <Arduino.h>\n#include <stdint.h>\n#include \"SMA.h\"\n#include <SoftPWM.h>\n\n\n\nSMA::SMA(int pin){\n //SoftPWMBegin(SOFTPWM_NORMAL);\n SMA_pin = pin;\n}\n\nvoid SMA::init_SMA(int pin){\n //SoftPWMBegin(SOFTPWM_NORMAL);\n SMA_pin = pin;\n}\n\nSMA::~SMA(){\n}\n\nvoid SMA::loop(){\n elapsed_time_since_actuation = abs(millis() - actuation_start_time);\n if (actuating){\n if (elapsed_time_since_actuation >= max_actuation_time){\n SoftPWMSet(SMA_pin, 0);\n\n actuating = false;\n cooling_down = true;\n }\n } else {\n if (elapsed_time_since_actuation >= max_actuation_time + cooldown_time){\n ready_to_actuate = true;\n cooling_down = false;\n }\n }\n}\n\n//Function called to actuate SMA. \n//If called and elapsed time is greater than 20 sec, actuate the SMA for 2 seconds\nbool SMA::actuate_if_ready(){\n\n if (ready_to_actuate){\n SoftPWMSet(SMA_pin,190);\n actuating = true;\n actuation_start_time = millis();\n ready_to_actuate = false;\n return 1;\n } else {\n return 0;\n }\n}\n\n"
}
] | 29 |
arish-ahmad/Project-S | https://github.com/arish-ahmad/Project-S | a8e7804964f745977f07b4a353cdf4f29aa7ae51 | 00d4ebb68d79fef6953450d39e2df3dc0de9f310 | 08e4e83e70fe5ff888c2bb6eb2b3626e5658127f | refs/heads/main | 2023-04-16T20:54:47.487320 | 2021-04-15T09:40:22 | 2021-04-15T09:40:22 | 323,088,301 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.4977973699569702,
"alphanum_fraction": 0.5726872086524963,
"avg_line_length": 20.700000762939453,
"blob_id": "008265ae4545a119b50f2a3fa53f43bf308d5862",
"content_id": "250889a6d182a31ef42be64d56c9736dbbb72aa0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 227,
"license_type": "no_license",
"max_line_length": 37,
"num_lines": 10,
"path": "/client.py",
"repo_name": "arish-ahmad/Project-S",
"src_encoding": "UTF-8",
"text": "import socket\r\ns=socket.socket()\r\ns.connect(('192.168.214.174',8584))\r\nconn=True\r\nwhile conn:\r\n msg=input('Enter your message: ')\r\n s.send(msg.encode('utf-8'))\r\n if msg == 'no':\r\n conn=False\r\n s.close()\r\n"
},
{
"alpha_fraction": 0.6204013228416443,
"alphanum_fraction": 0.6505016684532166,
"avg_line_length": 22.91666603088379,
"blob_id": "4d6afb49e870d5bd23373d9d59d17477356bf6d8",
"content_id": "5fb282f2f0ba0991f474454a02bf518928155b66",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 598,
"license_type": "no_license",
"max_line_length": 56,
"num_lines": 24,
"path": "/server.py",
"repo_name": "arish-ahmad/Project-S",
"src_encoding": "UTF-8",
"text": "import socket\r\ndef get_ip():\r\n ip= socket.socket(socket.AF_INET, socket.SOCK_DGRAM)\r\n ip.connect((\"8.8.8.8\", 80))\r\n return ip.getsockname()[0]\r\n s.close()\r\ns=socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\nhost = str(get_ip())\r\nprint(host)\r\nport = 8584\r\ns.bind((host,port))\r\ns.listen(4)\r\nprint(host)\r\nprint('server is ready to accept connection')\r\nclientobject,add=s.accept()\r\nprint('connected with this address',add)\r\nconn=True\r\nwhile conn:\r\n gotmsg=clientobject.recv(1024)\r\n gotmsg.decode('utf-8')\r\n print(gotmsg)\r\n if len(gotmsg) == 0:\r\n conn=False\r\n s.close()\r\n"
},
{
"alpha_fraction": 0.5381381511688232,
"alphanum_fraction": 0.5510510802268982,
"avg_line_length": 27.73214340209961,
"blob_id": "8dfcca1a9df03f16eaae24617cf9ac0a78802ec8",
"content_id": "ed45ff3413a03ed95faa29a0548258d18628b50a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3330,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 112,
"path": "/lserver.py",
"repo_name": "arish-ahmad/Project-S",
"src_encoding": "UTF-8",
"text": "# -*- encoding: utf-8 -*-\r\nimport sys\r\nimport struct\r\nimport getopt\r\nimport socket\r\nimport hashlib\r\nfrom datetime import datetime\r\n\r\nFILE_BUFFER_SIZE = 524288\r\n\r\ndef usage():\r\n print('Usage: bigfile_server.py <SERVER_PORT>')\r\n print('SERVER_PORT: Port to which server will listen.')\r\n\r\ndef random_filename():\r\n dt_now = datetime.now()\r\n return dt_now.strftime('%Y%m%d%H%M%S%f')\r\n\r\ndef readn(sock, count):\r\n data = b''\r\n while len(data) < count:\r\n packet = sock.recv(count - len(data))\r\n if packet == '':\r\n return ''\r\n data += packet\r\n return data\r\n\r\nif __name__ == '__main__':\r\n\r\n server_port = '2525'\r\n opts, args = getopt.gnu_getopt(sys.argv[1:], 'p:', ['port='])\r\n for opt, arg in opts:\r\n if opt in ('-p', '--port'):\r\n server_port = arg\r\n\r\n if server_port == '':\r\n print('Server port missing.', file=sys.stderr)\r\n usage()\r\n sys.exit(1)\r\n\r\n if not server_port.isdecimal():\r\n print('Server port contains invalid characters.', file=sys.stderr)\r\n sys.exit(2)\r\n\r\n print('Launching bigfile server.')\r\n serv_sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)\r\n ip=socket.gethostbyname(socket.gethostname())\r\n print(ip)\r\n try:\r\n serv_sock.bind(('192.168.43.104', int(server_port)))\r\n serv_sock.listen(5)\r\n except socket.error as e:\r\n print('Failed to launch server:', e)\r\n sys.exit(3)\r\n else:\r\n print('Server launched, waiting for new connection.')\r\n\r\n try:\r\n clnt_sock, clnt_addr = serv_sock.accept()\r\n except socket.error as e:\r\n print ('Failed to accept new connection:', e)\r\n sys.exit(3)\r\n else:\r\n print('New connection from:', clnt_addr)\r\n\r\n size_buff = readn(clnt_sock, 4)\r\n if size_buff == '':\r\n print('Failed to receive file size.', file=sys.stderr)\r\n clnt_sock.close()\r\n serv_sock.close()\r\n sys.exit(3)\r\n\r\n size_unpacked = struct.unpack('!I', size_buff)\r\n file_size = size_unpacked[0]\r\n print('Will receive file of size', file_size, 'bytes.')\r\n\r\n hash_algo = hashlib.sha256()\r\n\r\n filename = random_filename()\r\n try:\r\n with open(f'{filename}.mp4', 'wb') as file_handle:\r\n while file_size > 0:\r\n buffer = clnt_sock.recv(FILE_BUFFER_SIZE)\r\n print(len(buffer), 'bytes received.')\r\n if buffer == '':\r\n print('End of transmission.')\r\n break\r\n hash_algo.update(buffer)\r\n file_handle.write(buffer)\r\n file_size -= len(buffer)\r\n if file_size > 0:\r\n print('Failed to receive file,', file_size, 'more bytes to go.')\r\n except socket.error as e:\r\n print('Failed to receive data:', e, file=sys.stderr)\r\n clnt_sock.close()\r\n serv_sock.close()\r\n sys.exit(3)\r\n except IOError as e:\r\n print('Failed to write file:', e, file=sys.stderr)\r\n clnt_sock.close()\r\n serv_sock.close()\r\n sys.exit(3)\r\n else:\r\n print('File transmission completed.')\r\n\r\n clnt_sock.shutdown(socket.SHUT_RD)\r\n clnt_sock.close()\r\n serv_sock.close()\r\n print('Server shutdown.')\r\n print('SHA256 digest:', hash_algo.hexdigest())\r\n\r\n sys.exit(0)\r\n"
}
] | 3 |
Eromosele/multi-layer-net | https://github.com/Eromosele/multi-layer-net | e33626d4a05e90eb3b428149000eabbe8198718b | 8a3a907f210b2a9d64e260ed3e679d14947b3352 | 6620353816d811ed9aa5ad37ca1e6a25a1a38e33 | refs/heads/master | 2022-02-03T12:14:18.217851 | 2019-07-23T18:53:13 | 2019-07-23T18:53:13 | 198,126,088 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.800000011920929,
"alphanum_fraction": 0.8105263113975525,
"avg_line_length": 46.5,
"blob_id": "a8b6762b97c545c2c75cf75a3af427af34147382",
"content_id": "b246400598d5ee6058aa1878fc88d78991e4daf1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 95,
"license_type": "no_license",
"max_line_length": 76,
"num_lines": 2,
"path": "/README.md",
"repo_name": "Eromosele/multi-layer-net",
"src_encoding": "UTF-8",
"text": "# multi-layer-net\nA simple implementation of a multi layer neural network with 2 hidden layers\n"
},
{
"alpha_fraction": 0.582944393157959,
"alphanum_fraction": 0.6213406920433044,
"avg_line_length": 31.06802749633789,
"blob_id": "af36505899adba62768563d0ba794acde991fe69",
"content_id": "1201f92d717ef0d3bdf630e7e44e0d0e2348df21",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4714,
"license_type": "no_license",
"max_line_length": 167,
"num_lines": 147,
"path": "/multilayernet.py",
"repo_name": "Eromosele/multi-layer-net",
"src_encoding": "UTF-8",
"text": "\"\"\"\nmultilayernet.py\n~~~~~~~~~~~~~~~~\n---example network---\n |o|-->|o|\n|o|--> | |\n |o|-->|o|-->|o| (2 features, 2 hidden layers, 1 output node)\n|o|--> | |\n |o|-->|o|\n\nA simple python implementation of a multi layer neural net(2 hidden).\nThis implementation of the neural net is able to accept an arbitiary\nnumber of features and examples.\n\n---data structure---\nthe inputs are structured with the features being the row and examples shared in columns\nexample: if there is are 3 pieces of data (1, 2), (3, 4), (5, 6)\nfrom the data provided there are 2 features and 3 examples\nthe data will be structures as so:\n5 3 1 --> o\n| | |\n6 4 2 --> o\nx = np.array([[1, 3, 5], [2, 4, 6]])\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\n\nx = np.array([[1]]) (1 example with 1 feature)\nx = np.array([[1, 2]]) (2 examples with 1 feature)\n\nx = np.array([[1], [1]) (1 example with 2 features)\nx = np.array([[1, 1], [1, 1]) (2 examples with 2 features)\nx = np.array([[1, 1, 1], [1, 1, 1]) (3 examples with 2 features)\n~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~\ny = np.array([[1]]) (output for 1 example)\ny = np.array([[1, 2]]) (output for 2 examples)\n\n\"\"\"\nimport numpy as np\nfrom progress.bar import ShadyBar\n\nITERATIONS = 5000\n\ndef sigmoid(x, der=False):\n if der is True:\n return sigmoid(x)*(1-sigmoid(x))\n else:\n return 1 / (1 + np.exp(-x))\n\n\ndef getshapeof(x):\n print(np.shape(x))\n\ncolumn1_ = []\ncolumn2_ = []\ncolumn3_ = []\ncolumn4_ = []\ncolumn5_ = []\n\n# comment out this section for custom examples\nwith open('train_data.txt', 'r') as reader:\n lines = [line.rstrip('\\n') for line in reader]\n for line in lines:\n column1, column2, column3, column4, column5 = line.split(',')\n column1_.append(float(column1))\n column2_.append(float(column2))\n column3_.append(float(column3))\n column4_.append(float(column4))\n column5_.append(float(column5))\n\n x = np.array([(column1_), (column2_), (column3_), (column4_)]).T\n y = np.array([(column5_)])\n\nreader.close()\n\n\n# custom examples\n# x = np.array([[0, 1, 1, 0], [1, 1, 0, 0]]).T # input examples\n# y = np.array([[1, 1, 1, 0]])\n\nweight1 = np.random.random((x.shape[1], 8)) # weight between input and hidden layer 1\nweight2 = np.random.random((8, 8)) # weight between hidden layer 1 and 2\nweight3 = np.random.random((8, 1)) # weight between hidden layer 2 and output\n\nbar = ShadyBar('Processing', max=ITERATIONS, suffix=\"%(percent)d%%\")\n\n# iterations\nfor i in range(ITERATIONS):\n\n derived_hidden_layer = sigmoid(np.dot(x, weight1))\n derived_hidden_layer2 = sigmoid(np.dot(derived_hidden_layer, weight2))\n\n output = sigmoid(np.dot(derived_hidden_layer2, weight3))\n# end of forward propagate\n error = np.square(np.mean(y.T - output))\n derived_error = y.T - output\n\n error_percent = (np.mean(output)-np.mean(y.T)) * 100\n\n scalar = derived_error * sigmoid(np.dot(derived_hidden_layer2, weight3), True) # this remains static throught the calculations\n\n weight3 += np.dot(scalar.T,derived_hidden_layer2).T * 0.01\n weight2 += np.dot(np.dot(scalar,weight3.T).T, sigmoid(np.dot(derived_hidden_layer, weight2),True) * sigmoid(np.dot(x, weight1),True)) * 0.01\n weight1 += np.dot((np.dot(scalar,weight3.T) * np.dot(sigmoid(np.dot(derived_hidden_layer, weight2),True),weight2) * sigmoid(np.dot(x, weight1),True)).T,x).T * 0.01\n\n # if i % 500 == 0:\n # print()\n # print(\"Error (%s'th iteration): %s\" % (i,error))\n # print()\n bar.next()\n\nbar.finish()\nprint('%s error difference (<1 is better)' % np.abs(error_percent))\nprint(output)\n\ncolumn1_ = []\ncolumn2_ = []\ncolumn3_ = []\ncolumn4_ = []\ncolumn5_ = []\n# test data\nwith open('test_data.txt', 'r') as testreader:\n lines = [line.rstrip('\\n') for line in testreader]\n for line in lines:\n column1, column2, column3, column4, column5 = line.split(',')\n column1_.append(float(column1))\n column2_.append(float(column2))\n column3_.append(float(column3))\n column4_.append(float(column4))\n column5_.append(float(column5))\n\n test_x = np.array([(column1_), (column2_), (column3_), (column4_)]).T\n test_y = np.array([(column5_)])\n\ntestreader.close()\n\nderived_hidden_layer_test = sigmoid(np.dot(test_x, weight1))\nderived_hidden_layer2_test = sigmoid(np.dot(derived_hidden_layer_test, weight2))\n\ntest_output = sigmoid(np.dot(derived_hidden_layer2_test, weight3))\n\ntest_error = np.square(np.mean(test_y.T - test_output))\ntest_derived_error = test_y.T - test_output\n\ntest_error_percent = (np.mean(test_output)-np.mean(test_y.T)) * 100\n\nprint()\nprint('%s test error difference (<1 is better)' % np.abs(test_error_percent))\nprint(test_output)\n"
}
] | 2 |
213151623/seu-jwc-fker | https://github.com/213151623/seu-jwc-fker | 8dff7484111ce6e7f6b4867b9b543e9bbdca9c75 | 388eaec74c5e868ad579356717ea6539c6426728 | 0c08c450fb9acbef82840588c279dce62817c64a | refs/heads/master | 2021-06-24T05:33:30.760447 | 2017-08-31T06:48:36 | 2017-08-31T06:48:36 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6619718074798584,
"alphanum_fraction": 0.7323943376541138,
"avg_line_length": 16.875,
"blob_id": "5924c5ec0c263fcdd4cdb699c5e5ffe3edfb2f15",
"content_id": "78153ead03bcc169737dcb9f607d065d9f55b158",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 294,
"license_type": "no_license",
"max_line_length": 53,
"num_lines": 8,
"path": "/README.md",
"repo_name": "213151623/seu-jwc-fker",
"src_encoding": "UTF-8",
"text": "SeuJwcFker\n============\n\n## 2017/5/25 变态版\n\n1. 取消了选课未开放会退出程序的设定,能力更加变态;\n2. 使用小猴的验证码识别训练集代替原来的tesseract,不再需要各种依赖包,装一个Pillow即可;\n3. 改成单文件版本,更方便使用;"
},
{
"alpha_fraction": 0.3856073021888733,
"alphanum_fraction": 0.5598869323730469,
"avg_line_length": 40.57319641113281,
"blob_id": "55747801b7a033ed21d39ad967f344d119249925",
"content_id": "34109bfaa759172e55651267c2a75d3cab05d112",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 21581,
"license_type": "no_license",
"max_line_length": 269,
"num_lines": 485,
"path": "/main.py",
"repo_name": "213151623/seu-jwc-fker",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport HTMLParser \nimport urlparse \nimport urllib \nimport urllib2 \nimport cookielib \nimport string \nimport io\nimport re\nimport time\nimport sys\nimport PIL\nfrom PIL import Image\n\nreload(sys)\nsys.setdefaultencoding(\"utf-8\")\n\n\nSTANDARD = [\n [18.714286, 27.142857, 32.857143, 36.714286, 38.285714, 41.571429, 43.000000, 44.714286, 46.285714, 48.285714,\n 48.285714, 36.428571, 27.714286, 24.714286, 23.285714, 22.285714, 21.428571, 19.428571, 19.285714, 19.000000,\n 18.857143, 18.714286, 19.714286, 20.571429, 20.714286, 22.714286, 26.571429, 28.000000, 35.571429, 46.714286,\n 46.714286, 44.857143, 43.000000, 41.285714, 39.571429, 36.142857, 34.428571, 31.000000, 26.000000, 18.714286],\n [0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000,\n 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000,\n 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000,\n 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000, 0.000000],\n [8.333333, 8.333333, 16.166667, 23.166667, 24.166667, 26.000000, 27.000000, 27.833333, 27.500000, 29.000000,\n 29.500000, 30.333333, 30.000000, 30.000000, 28.666667, 27.666667, 27.333333, 27.833333, 28.000000, 28.333333,\n 29.833333, 31.333333, 33.333333, 35.166667, 38.000000, 43.000000, 41.833333, 40.833333, 39.666667, 37.666667,\n 36.833333, 34.500000, 32.333333, 29.500000, 26.500000, 21.500000, 7.333333, 7.166667, 7.166667, 7.333333],\n [8.200000, 8.400000, 8.400000, 8.200000, 13.200000, 18.800000, 19.000000, 19.400000, 19.000000, 26.000000,\n 26.200000, 26.400000, 25.400000, 26.200000, 26.000000, 26.400000, 27.400000, 27.200000, 28.400000, 29.200000,\n 31.200000, 33.200000, 36.400000, 41.400000, 46.800000, 48.800000, 52.600000, 51.200000, 49.200000, 48.200000,\n 45.200000, 40.600000, 37.600000, 33.600000, 25.800000, 18.000000, 13.800000, 7.000000, 7.000000, 7.200000],\n [17.250000, 19.000000, 20.500000, 21.875000, 24.125000, 25.375000, 26.375000, 28.250000, 28.500000, 28.125000,\n 28.000000, 27.750000, 25.875000, 25.250000, 25.125000, 26.250000, 25.000000, 24.625000, 25.625000, 24.750000,\n 24.500000, 24.500000, 25.375000, 24.500000, 52.000000, 52.250000, 52.750000, 52.875000, 53.750000, 55.375000,\n 55.125000, 55.000000, 54.625000, 18.625000, 18.375000, 18.375000, 18.250000, 17.750000, 17.375000, 9.875000],\n [8.428571, 8.285714, 8.142857, 8.285714, 8.428571, 8.285714, 14.000000, 36.285714, 36.142857, 35.857143, 36.000000,\n 36.000000, 36.142857, 31.714286, 27.000000, 26.857143, 27.714286, 27.571429, 27.714286, 28.714286, 27.857143,\n 29.142857, 29.714286, 31.000000, 34.142857, 41.000000, 40.142857, 39.285714, 38.000000, 37.857143, 36.428571,\n 35.000000, 33.571429, 32.000000, 28.428571, 15.714286, 8.285714, 8.285714, 8.285714, 8.142857],\n [8.142857, 20.571429, 27.857143, 32.285714, 35.857143, 38.428571, 40.857143, 44.000000, 46.000000, 46.857143,\n 47.571429, 49.142857, 37.000000, 32.857143, 29.857143, 27.428571, 25.714286, 26.285714, 25.571429, 24.714286,\n 25.428571, 24.285714, 24.714286, 24.285714, 26.142857, 27.428571, 28.571429, 31.142857, 34.285714, 41.142857,\n 40.857143, 39.142857, 37.571429, 36.571429, 34.571429, 32.857143, 24.000000, 21.714286, 16.428571, 8.000000],\n [8.428571, 8.285714, 8.142857, 8.285714, 8.285714, 8.285714, 16.285714, 16.285714, 19.000000, 21.857143, 24.000000,\n 25.285714, 25.857143, 27.714286, 29.857143, 31.000000, 32.857143, 34.571429, 35.285714, 32.714286, 30.142857,\n 29.571429, 29.142857, 28.142857, 27.285714, 27.000000, 26.000000, 26.857143, 26.428571, 26.285714, 26.428571,\n 26.714286, 25.142857, 24.571429, 23.571429, 21.571429, 20.857143, 18.714286, 17.571429, 17.000000],\n [7.500000, 7.500000, 13.833333, 18.833333, 21.333333, 29.666667, 36.500000, 40.333333, 43.333333, 47.166667,\n 49.833333, 52.833333, 48.666667, 45.833333, 37.500000, 33.500000, 30.833333, 30.000000, 28.000000, 27.500000,\n 28.666667, 27.666667, 28.500000, 29.166667, 32.833333, 33.833333, 36.000000, 40.333333, 47.666667, 52.166667,\n 49.166667, 47.166667, 44.166667, 40.666667, 37.166667, 32.500000, 27.000000, 18.833333, 14.833333, 8.000000],\n [8.142857, 15.857143, 20.285714, 24.142857, 30.428571, 32.571429, 34.142857, 36.285714, 38.142857, 38.000000,\n 39.571429, 32.428571, 29.571429, 27.571429, 26.571429, 25.714286, 25.714286, 23.714286, 23.857143, 23.428571,\n 24.428571, 23.142857, 23.000000, 26.285714, 26.285714, 26.428571, 30.000000, 33.857143, 39.000000, 50.142857,\n 49.285714, 47.857143, 47.428571, 45.571429, 44.285714, 41.142857, 38.714286, 34.142857, 29.428571, 20.714286]\n]\n\n\ndef getCheckCode():\n for i in range(10):\n try:\n image = urllib2.urlopen('http://xk.urp.seu.edu.cn/jw_css/getCheckCode', timeout = 10)\n break\n except Exception, e:\n print e\n continue\n else:\n print u'网络连接失败,请重试'\n return\n\n img = Image.open(io.BytesIO(image.read()))\n start = [13, 59, 105, 151]\n result = ''\n for i in start:\n sample = []\n for i in xrange(i, i + 40):\n temp = 0\n for j in xrange(0, 100):\n temp += (img.getpixel((i, j))[1] < 40)\n sample.append(temp)\n min_score = 1000\n max_match = 0\n for idx, val in enumerate(STANDARD):\n diff = []\n for i in xrange(len(sample)):\n diff.append(sample[i] - val[i])\n avg = float(sum(diff)) / len(diff)\n\n for i in xrange(len(sample)):\n diff[i] = abs(diff[i] - avg)\n score = sum(diff)\n if score < min_score:\n min_score = score\n max_match = idx\n\n result = result + str(max_match)\n return (result, img)\n\n\ndef loginIn(userName, passWord):\n #设置cookie处理器\n cj = cookielib.LWPCookieJar()\n cookie_support = urllib2.HTTPCookieProcessor(cj)\n opener = urllib2.build_opener(cookie_support, urllib2.HTTPHandler) \n urllib2.install_opener(opener)\n \n (code, img) = getCheckCode()\n while len(code) != 4:\n (code, img) = getCheckCode()\n print u\"验证码识别为: \" + code\n\n #构造post数据\n posturl = 'http://xk.urp.seu.edu.cn/jw_css/system/login.action' \n header ={ \n 'Host' : 'xk.urp.seu.edu.cn', \n 'Proxy-Connection' : 'keep-alive',\n 'Origin' : 'http://xk.urp.seu.edu.cn',\n 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1',\n 'Referer' : 'http://xk.urp.seu.edu.cn/jw_css/system/login.action'\n }\n data = {\n 'userId' : userName,\n 'userPassword' : passWord, #你的密码, \n 'checkCode' : code, #验证码 \n 'x' : '33', #别管\n 'y' : '5' #别管2\n }\n \n #post登录数据\n (state, text) = postData(posturl,header,data)\n url = ''\n if state == True:\n if (text.find('选课批次') != -1): # a bad label; the url returned should be the best\n print u\"登录成功\"\n function = re.search(r'onclick=\"changeXnXq.*\\)\"', text); # find the function whose parameter are desired\n function = function.group() \n parameters = re.search(r\"'(.*)','(.*)','(.*)'\\)\", function) # fetch url parameters\n url = \"http://xk.urp.seu.edu.cn/jw_css/xk/runXnXqmainSelectClassAction.action?Wv3opdZQ89ghgdSSg9FsgG49koguSd2fRVsfweSUj=Q89ghgdSSg9FsgG49koguSd2fRVs&selectXn=\" + parameters.group(1) + \"&selectXq=\" + parameters.group(2) + \"&selectTime=\" + parameters.group(3)\n else:\n state = False\n errorMessage = re.search(r'id=\"errorReason\".*?value=\"(.*?)\"', text)\n text = errorMessage.group(1)\n else:\n text = \"网络错误,登录失败\" \n return (state, text, url)\n\ndef selectSemester(semesterNum, url):\n print u\"切换学期菜单中......\"\n time.sleep(5)\n\n geturl = re.sub('selectXq=.', 'selectXq='+str(semesterNum), url)\n \n header = { 'Host' : 'xk.urp.seu.edu.cn',\n 'Proxy-Connection' : 'keep-alive',\n 'Accept' : 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',\n 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1', \n }\n data = {}\n #get获取学期课程\n (state, text) = getData(geturl,header,data)\n if state == True:\n if text.find(\"数据异常\") != -1: # switched to an unavailable semester\n state = False\n text = \"目前无法选择学期\" + str(semesterNum)\n return (state, text)\n\ndef postData(posturl,headers,postData):\n postData = urllib.urlencode(postData) #Post数据编码 \n request = urllib2.Request(posturl, postData, headers)#通过urllib2提供的request方法来向指定Url发送我们构造的数据,并完成登录过程 \n text = ''\n for i in range(10):\n try:\n response = urllib2.urlopen(request, timeout = 5)\n text = response.read()\n break\n except Exception, e:\n print 'fail to get response'\n print 'trying to open agian...'\n continue\n else:\n return (False, \"数据发送失败\")\n return (True, text)\n\ndef getData(geturl,header,getData, returnUrl = False):\n getData = urllib.urlencode(getData)\n request = urllib2.Request(geturl, getData, header)\n text = ''\n url = ''\n for i in range(10):\n try:\n response = urllib2.urlopen(request, timeout = 5)\n text = response.read()\n url = response.geturl()\n break\n except Exception, e:\n print e\n print 'trying to open agian...'\n continue\n else:\n if returnUrl == False:\n return (False, \"获取数据失败\")\n else:\n return (False, \"获取数据失败\", '')\n\n if returnUrl == False:\n return (True, text)\n else:\n return(True, text, url)\n\ndef stateCheck(textValue): \n text = textValue\n if (text.find('成功选择') != -1)or(text.find('服从推荐') != -1):\n return 0\n if text.find('已满') != -1:\n return 1\n if text.find('失败') != -1:\n return 2\n\ndef Mode1(semesterNum, url):\n (state, text) = selectSemester(semesterNum, url)\n if state == False:\n print text.decode('utf-8')\n print u'切换到学期' + str(semesterNum) + u\"失败\"\n return\n else:\n print u'切换到学期' + str(semesterNum) + u\"成功\"\n #寻找可以“服从推荐”的课程\n print u\"==============\\n模式1,开始选课\\n==============\"\n courseList = []\n pattern = re.compile(r'\\\" onclick=\\\"selectThis\\(\\'.*\\'')\n pos = 0\n m = pattern.search(text,pos)\n while m:\n pos = m.end()\n tempText = m.group()\n parameters = re.search(r\"selectThis\\('(.*?)','(.*?)','(.*?)'\", tempText)\n course = [parameters.group(1),parameters.group(2),parameters.group(3),1]\n courseList.append(course)\n m=pattern.search(text,pos) #寻找下一个\n times = 0\n success = 0\n total = len(courseList)\n while True:\n if total == 0:\n print u\"目前没有课可以选择\"\n break\n time.sleep(3)#sleep\n times = times +1\n print u\"\\n第\"+str(times)+u\"次选课,已经成功选择\"+str(success)+u\"门\"\n for course in courseList:\n if course[3] == 1:\n #构造选课post\n posturl = 'http://xk.urp.seu.edu.cn/jw_css/xk/runSelectclassSelectionAction.action?select_jxbbh='+course[1]+'&select_xkkclx='+course[2]+'&select_jhkcdm='+course[0]\n headers = { 'Host' : 'xk.urp.seu.edu.cn',\n 'Proxy-Connection' : 'keep-alive',\n 'Content-Length' : '2',\n 'Accept' : 'application/json, text/javascript, */*',\n 'Origin':'http://xk.urp.seu.edu.cn',\n 'X-Requested-With': 'XMLHttpRequest',\n 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1',\n }\n data = {'{}':''\n }\n #post选课包,并获取返回状态\n (state, text) = postData(posturl,headers,data)\n if state == False:\n text = '网络错误'\n else:\n if text.find('isSuccess\":\"false') != -1:\n state = False\n text = re.search(r'errorStr\":\"(.*?)\"', text).group(1)\n if state == True:\n course[3] = 0\n success += 1\n total -= 1\n print u\"Nice, 课程\"+str(course[0])+u\" 选择成功\"\n else:\n print u\"课程\"+str(course[0])+u\" 选课失败,\" + text.decode('utf-8')\n \ndef Mode2(semesterNum,courseName, url):\n (state, text) = selectSemester(semesterNum, url)\n if state == False:\n print text.decode('utf-8')\n print u'切换到学期' + str(semesterNum) + u\"失败\"\n return\n else:\n print u'切换到学期' + str(semesterNum) + u\"成功\"\n print u\"==============\\n模式2,开始选课\\n==============\"\n #获取人文课页面\n geturl1 = 'http://xk.urp.seu.edu.cn/jw_css/xk/runViewsecondSelectClassAction.action?select_jhkcdm=00034&select_mkbh=rwskl&select_xkkclx=45&select_dxdbz=0'\n header1 = {\n 'Host' : 'xk.urp.seu.edu.cn',\n 'Proxy-Connection' : 'keep-alive',\n 'Accept' : 'application/json, text/javascript, */*',\n 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1',\n } \n data1 = {}\n (state, text) = getData(geturl1,header1,data1)\n if state == False:\n print u\"打开课程列表页面失败\"\n return\n #构造RE \n #print text\n\n pattern = (courseName + '.*?(\\\"8%\\\" id=\\\"(.{0,20})\\\" align)') # possible problem here??\n #获取课程编号\n courseNo = re.findall(pattern,text,re.S)[0][1]\n #构造数据包\n posturl = 'http://xk.urp.seu.edu.cn/jw_css/xk/runSelectclassSelectionAction.action?select_jxbbh='+courseNo+'&select_xkkclx=45&select_jhkcdm=00034&select_mkbh=rwskl'\n headers = { \n 'Host' : 'xk.urp.seu.edu.cn',\n 'Proxy-Connection' : 'keep-alive',\n 'Content-Length' : '2',\n 'Accept' : 'application/json, text/javascript, */*',\n 'Origin':'http://xk.urp.seu.edu.cn',\n 'X-Requested-With': 'XMLHttpRequest',\n 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1',\n }\n data = {\n '{}':''\n }\n print u\"我开始选课了,课程编号:\"+courseNo\n times = 0\n while True :\n #判断是否选到课\n times = times+1\n (state, text) = getData(geturl1,header1,data1)\n if state == False:\n print \"打开课程列表页面失败\"\n return\n pattern2 = ('已选(.{0,200})align=\\\"')\n result = re.findall(pattern2,text,re.S)\n #print result\n success = len(result) #为0为不成功 继续\n if (success != 0)and(result[0].find(courseNo)!=-1):\n print u\"Nice,已经选到课程:\"+courseNo\n break\n #发送选课包\n print u\"第\"+str(times)+\"次尝试选择课程\"+courseNo+u\",但是没选到!\"\n (state, text) = postData(posturl,headers,data)\n time.sleep(3)#sleep\n return \ndef postRw(courseNo):\n posturl = 'http://xk.urp.seu.edu.cn/jw_css/xk/runSelectclassSelectionAction.action?select_jxbbh='+courseNo+'&select_xkkclx=45&select_jhkcdm=00034&select_mkbh=rwskl'\n headers = { \n 'Host' : 'xk.urp.seu.edu.cn',\n 'Proxy-Connection' : 'keep-alive',\n 'Content-Length' : '2',\n 'Accept' : 'application/json, text/javascript, */*',\n 'Origin':'http://xk.urp.seu.edu.cn',\n 'X-Requested-With': 'XMLHttpRequest',\n 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1',\n }\n data = {\n '{}':''\n }\n (state, text) = postData(posturl,headers,data)\n return (state, text)\ndef checkRwState(text):\n if text.find('true') != -1: #选课成功\n return 0\n if text.find('名额已满') != -1:\n return 1\n if text.find('冲突') != -1:\n return 2\n return -1\ndef Mode3(semesterNum, url): \n (state, text) = selectSemester(semesterNum, url)\n if state == False:\n print text.decode('utf-8')\n print u'切换到学期' + str(semesterNum) + u\"失败\"\n return\n else:\n print u'切换到学期' + str(semesterNum) + u\"成功\"\n print u\"==============\\n模式3,开始选课\\n==============\"\n #获取人文课页面\n geturl1 = 'http://xk.urp.seu.edu.cn/jw_css/xk/runViewsecondSelectClassAction.action?select_jhkcdm=00034&select_mkbh=rwskl&select_xkkclx=45&select_dxdbz=0'\n header1 = {\n 'Host' : 'xk.urp.seu.edu.cn',\n 'Proxy-Connection' : 'keep-alive',\n 'Accept' : 'application/json, text/javascript, */*',\n 'User-Agent' : 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:14.0) Gecko/20100101 Firefox/14.0.1',\n } \n data1 = {}\n (state, text) = getData(geturl1,header1,data1)\n if state == False:\n print u\"打开课程列表页面失败\"\n return\n\n #获取所有的课程编号\n pattern = ('\\\"8%\\\" id=\\\"(.{0,20})\\\" align')\n courseList = re.findall(pattern,text,re.S)\n #print courseList \n courseCtList =[]\n #找出并去掉冲突的课程\n for course in courseList:\n (state, backText) = postRw(course)\n if state == True: # ewww bad name here\n state = checkRwState(backText)\n else:\n state = -1 # network error or something else\n if state == 2:\n courseCtList.append(course)\n if state == 0:\n print u\"Nice 选到了一门课:\"+course\n return #成功了\n #print courseCtList\n courseTemp = [i for i in courseList if (i not in courseCtList)]\n #print courseTemp\n times = 0\n while True:\n times = times + 1\n #找出已满的课程\n pattern = ('已满.+?(\\\"8%\\\" id=\\\")(.{0,20})\\\" align')\n courseYmList = [i[1] for i in re.findall(pattern,text,re.S)]\n #print courseYmList\n #找出可以选的课程编号\n courseAva = [i for i in courseTemp if (i not in courseYmList) ]\n #选课了\n if len(courseAva) == 0:\n print u\"第\"+str(times)+u\"次刷新,每门课都选不了..\"\n else:\n for course in courseAva:\n (state, text) = postRw(course)\n if state == True:\n state = checkRwState(text)\n else:\n state = -1\n if state == 0:\n print u\"Nice 选到了一门课:\"+course\n return\n if state == 1:\n print u\"人品不好 眼皮子底下的课被抢了\"\n #刷新人文选课界面\n (state, text) = getData(geturl1,header1,data1)\n if text.count('已选') == 3: # in case of multi-instances\n print u\"已经选到一门课了\"\n break\n\n if state == False:\n print u\"打开课程列表页面失败\"\n return\n\n\nif __name__ == \"__main__\":\n print u\"\\n\\n\\n\\n\"\n print u\"===================================================================== \"\n print u\" Seu_Jwc_Fker 东南大学选课助手变态版\"\n print u\"===================================================================== \"\n print u\"请选择模式:\"\n print u\"1. 同院竞争臭表脸模式:只值守主界面本院的所有“服从推荐”课程\"\n print u\"2. 孤注一掷模式:只值守子界面“人文社科类”中你指定一门课程\"\n print u\"3. 暴力模式:值守子界面“人文社科类”任意一门课程,有剩余就选上\"\n \n mode = input(u'\\n请输入模式编号(如:1):')\n userId = raw_input(u'请输入一卡通号(如:213111111):')\n passWord = raw_input(u'请输入密码(如:65535):')\n semester = input(u'请输入学期编号(短学期为1,秋季学期为2,春季学期为3):')\n\n (state, text, url) = loginIn(userId,passWord)\n while state == False:\n print text.decode('utf-8')\n (state, text, url) = loginIn(userId, passWord)\n\n if state == True:\n if 1 == mode:\n Mode1(semester, url)\n if 2 == mode:\n courseName = raw_input(u'请输入你想值守的人文课名称或者其关键词(如:音乐鉴赏):')\n try:\n courseName.decode('utf-8')\n except:\n courseName.decode('gbk').encode('utf-8')\n Mode2(semester,courseName, url)\n if 3 == mode:\n Mode3(semester, url)\n else:\n print u\"要不试试退出后重启一下本程序?\"\n raw_input(u'按任意键退出')\n"
}
] | 2 |
RahulRanjan7201/Covid19WebScrapingData | https://github.com/RahulRanjan7201/Covid19WebScrapingData | 11462f2e599124f08f1039b66700da85aa2e2fea | 932721a995e57b92dd99b3070de88c4868f2bd9e | 9370f84047bc0831cfda67d1e3b2c4ca68db1d3b | refs/heads/master | 2022-11-08T02:59:38.110358 | 2020-06-06T08:21:50 | 2020-06-06T08:21:50 | 269,912,792 | 1 | 1 | null | null | null | null | null | [
{
"alpha_fraction": 0.7190966606140137,
"alphanum_fraction": 0.7290015816688538,
"avg_line_length": 38.66666793823242,
"blob_id": "4480f4846e7c62d1ce85f3e29f27d5c75a891a6d",
"content_id": "b0512dc891f14b5c00620f97c3ff3c18c87c426c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2524,
"license_type": "no_license",
"max_line_length": 151,
"num_lines": 63,
"path": "/covid19MyGov.in.py",
"repo_name": "RahulRanjan7201/Covid19WebScrapingData",
"src_encoding": "UTF-8",
"text": "import pandas\nimport requests\n\nfrom bs4 import BeautifulSoup \n\n#Getting the webpage \nwebpage = requests.get(\"https://www.mygov.in/corona-data/covid19-statewise-status/\")\n\n#Loading the content \ncontent = webpage.content\n\n#Parsing the content\nresult = BeautifulSoup(content,'html.parser')\n\n#Identifying the products on the page by the div tag and the class name \ncovid19StatesAffected = result.find_all(\"div\", {\"class\": \"field field-name-field-select-state field-type-list-text field-label-above\"})\ncovid19totalConfirmed = result.find_all(\"div\", {\"class\": \"field field-name-field-total-confirmed-indians field-type-number-integer field-label-above\"})\ncovid19curedDischarged = result.find_all(\"div\", {\"class\":\"field field-name-field-cured field-type-number-integer field-label-above\"})\ncovid19totalDeath = result.find_all(\"div\", {\"class\":\"field field-name-field-deaths field-type-number-integer field-label-above\"})\ncovid19epassLink = result.find_all(\"div\", {\"class\": \"field field-name-field-e-pass-url field-type-text field-label-above\"})\nstate_Name =[] \ntotal_confirmed = []\ntotal_cured_discharged_migrated = []\ntotal_death =[]\ne_pass = []\n#Iterating over the list of products and extracting the necessary info\nfor item in covid19StatesAffected:\n stateName = item.find(\"div\", { \"class\" : \"field-items\"}).string\n state_Name.append(stateName)\n\nfor item in covid19totalConfirmed : \n totalConfirmed = item.find(\"div\", { \"class\" : \"field-items\"}).string\n total_confirmed.append(totalConfirmed)\n\nfor item in covid19curedDischarged :\n totalDischarged = item.find(\"div\", {\"class\" : \"field-items\"}).string\n total_cured_discharged_migrated.append(totalDischarged)\n\nfor item in covid19totalDeath :\n totalDeath = item.find(\"div\", {\"class\" : \"field-items\"}).string\n total_death.append(totalDeath)\n\nfor item in covid19epassLink : \n epass = item.find(\"div\", {\"class\" : \"field-items\"}).string\n e_pass.append(epass);\n\ndata = list(zip(state_Name,total_confirmed,total_cured_discharged_migrated, total_death,e_pass))\n\n#creating the pandas dataframe\n\nd= pandas.DataFrame(data, columns= [\"State Name\", \"Total Confirmed\", \"Cured/ Discharged/ Migrated\", \"Death\", \"E-Pass Links\"])\n\n# Writing the data frame to a new Excel File \ntry: \n d.to_excel(\"Covid19IndiaData.xlsx\")\nexcept:\n print(\"\\nSomething went wrong ! Please check code / Internet Connection\")\nelse:\n print(\"\\ncovid data successfully written to Excel.\")\nfinally:\n print(\"\\nQuitting the program. Bye !\")\n\n#End of program\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n"
},
{
"alpha_fraction": 0.7610062956809998,
"alphanum_fraction": 0.7704402804374695,
"avg_line_length": 28,
"blob_id": "3a41cc338b488cdbf5f82939344952abc98db465",
"content_id": "b1b88319d4db5accc1cffa90c083b10aa6d2be10",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 318,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 11,
"path": "/Readme.md",
"repo_name": "RahulRanjan7201/Covid19WebScrapingData",
"src_encoding": "UTF-8",
"text": "This project is based on web scraping where the data is fetch from mygov.in web site and extract it using web scraping technique. \nAfter extracting the data it create excel and dump the data in Excel. \n\nInstall \n1. pandas \n2. request \n3. BeautifulSoup\n\nRun \npython <Name of File>\nNote:- For any concern reach out to me"
}
] | 2 |
shumutang/wmsdjango | https://github.com/shumutang/wmsdjango | f35eb46cea83369750c9f910634cc9164f524a6d | 97070c86a0b976483ab412f935bb33f66474ea68 | 5f70af51ab77538cb67086d84b0baf9ed40412f4 | refs/heads/master | 2021-01-18T03:29:39.667122 | 2017-04-13T14:51:13 | 2017-04-13T14:51:13 | 85,819,742 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.7494553327560425,
"alphanum_fraction": 0.7494553327560425,
"avg_line_length": 19.909090042114258,
"blob_id": "375e0f801763fa796d8b2a1532b9baa4d0f7b517",
"content_id": "99b70058eed52b4b998b40701a2d4622f711fc44",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 459,
"license_type": "no_license",
"max_line_length": 54,
"num_lines": 22,
"path": "/report/admin.py",
"repo_name": "shumutang/wmsdjango",
"src_encoding": "UTF-8",
"text": "from django.contrib import admin\n\nfrom import_export.admin import ImportExportModelAdmin\nfrom import_export import resources\n\n# Register your models here.\n\nfrom .models import Store\n\nclass StoreResource(resources.ModelResource):\n class Meta:\n model = Store\n\nclass StoreAdmin(ImportExportModelAdmin):\n resource_class = StoreResource\n list_display = ['product_id'\n ]\n search_fields = ['product' ]\n\n\n\nadmin.site.register(Store , StoreAdmin)"
},
{
"alpha_fraction": 0.614774763584137,
"alphanum_fraction": 0.6205405592918396,
"avg_line_length": 33.89937210083008,
"blob_id": "eb0b783af9672b0874a02af6cd6d4f14d11830df",
"content_id": "fd907b4c2a0991a0c2cb2cb7f3bc834159636855",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6024,
"license_type": "no_license",
"max_line_length": 110,
"num_lines": 159,
"path": "/order/models.py",
"repo_name": "shumutang/wmsdjango",
"src_encoding": "UTF-8",
"text": "# -*-coding:utf-8-*-\n\nfrom __future__ import unicode_literals\n\nfrom django.db import models\nfrom django.utils.encoding import python_2_unicode_compatible\n\nfrom django.utils import timezone\nfrom datetime import date\n\nfrom django.core.exceptions import ValidationError\n\nfrom wms.models import Customer , Product , Location , Warehouse\n\n# Create your models here.\n\nclass CommonOrder(models.Model):\n customer = models.ForeignKey(Customer, verbose_name='所属客户')\n warehouse = models.ForeignKey(Warehouse, verbose_name='操作仓库')\n serial_number = models.CharField('订单流水(系统自动生成)', max_length=16, null=True, blank=True)\n invoice = models.IntegerField('发票号', null=True,blank=True)\n pcs = models.IntegerField('订单pcs', null=True, blank=True)\n boxes = models.IntegerField('合计箱数', null=True, blank=True)\n order_comment = models.CharField('订单备注', max_length=60, null=True, blank=True)\n operate_date = models.DateTimeField('操作日期', null=True, blank=True,default=timezone.now)\n\n class Meta:\n abstract = True\n\n\n@python_2_unicode_compatible\nclass OrderIn(CommonOrder):\n order_type_choices = (\n ('zc', u'正常入库'),\n ('bl', u'不良品入库'),\n ('zp', u'赠品入库'),\n ('qt', u'其他'),\n )\n\n in_store_choices = (\n (u'y', u'已完成'),\n (u'n', u'未完成'),\n )\n in_number = models.CharField('入库编号',primary_key=True, help_text=u'留空系统会自动生成', max_length=20, blank=True)\n sender = models.CharField('结算单位', max_length=30, blank=True, null=True)\n receiver = models.CharField('送货单位', max_length=30, blank=True, null=True)\n plan_in_time = models.DateField('计划入库日期', default=date.today)\n fact_in_time = models.DateField('实际入库日期', default=date.today)\n operator = models.CharField('制单人', max_length=60 , null=True , blank=True)\n in_store = models.CharField('入库', max_length=4, choices=in_store_choices, default='n')\n order_type = models.CharField('订单类型', max_length=10, choices=order_type_choices, default='zc')\n product = models.ManyToManyField(Product, verbose_name='商品名称', through='OrderInProductship')\n\n class Meta:\n verbose_name = u'订单(入库)'\n verbose_name_plural = u'订单(入库)'\n ordering = ['-in_number']\n\n def __str__(self):\n return self.in_number\n\n # def save(self, *args, **kwargs):\n # if self.in_store == \"y\":\n # Msg = u'Order(%s) is completed,do not modified.' % self.in_number\n # raise ValidationError(Msg)\n # else:\n # super(OrderIn, self).save(*args, **kwargs)\n\n\n@python_2_unicode_compatible\nclass OrderOut(CommonOrder):\n order_type_choices = (\n ('zc', u'正常出库'),\n ('bl', u'不良品出库'),\n ('zp', u'赠品出库'),\n ('qt', u'其他'),\n )\n\n out_store_choices = (\n (u'y', u'已完成'),\n (u'n', u'未完成'),\n )\n\n out_number = models.CharField('出库编号', primary_key=True, help_text=u'留空系统会自动生成', max_length=20, blank=True)\n fact_out_time = models.DateField('出库日期', default=date.today)\n receiver = models.CharField('收货人', max_length=10, blank=True, null=True)\n receiver_addr = models.CharField('送货地址', max_length=30, blank=True, null=True)\n receiver_phone = models.IntegerField('收货人电话',blank=True, null=True)\n operator = models.CharField('出库人', max_length=60, null=True, blank=True)\n out_store = models.CharField('出库', max_length=4, choices=out_store_choices,default='n')\n order_type = models.CharField('订单类型', max_length=10, choices=order_type_choices, default='zc')\n product = models.ManyToManyField(Product, verbose_name='商品名称', through='OrderOutProductship')\n\n class Meta:\n verbose_name = u'订单(出库)'\n verbose_name_plural = u'订单(出库)'\n ordering = ['-out_number']\n\n def __str__(self):\n return self.out_number\n\n # def save(self, *args, **kwargs):\n # if self.out_store == \"y\":\n # Msg = u'Order(%s) is completed,do not modified.' % self.out_number\n # raise ValidationError(Msg)\n # else:\n # super(OrderOut, self).save(*args, **kwargs)\n\n\nclass OrderInProductship(models.Model):\n orderin = models.ForeignKey(\n OrderIn,\n verbose_name='入库编号',\n on_delete=models.CASCADE\n )\n product = models.ForeignKey(\n Product,\n verbose_name='商品名称',\n on_delete=models.CASCADE,\n parent_link=True\n )\n orderin_pcs = models.IntegerField('入库数量', default=0)\n\n def save(self, *args, **kwargs):\n if self.orderin.in_store == \"y\":\n Msg = u'Order(%s) is completed,do not modified.' % self.orderin.in_number\n raise ValidationError(Msg)\n else:\n super(OrderInProductship, self).save(*args, **kwargs)\n\n class Meta:\n verbose_name = u'入库订单-商品明细'\n verbose_name_plural = u'入库订单-商品明细'\n ordering = ['-id']\n\nclass OrderOutProductship(models.Model):\n orderout = models.ForeignKey(\n OrderOut,\n verbose_name='出库编号',\n on_delete=models.CASCADE\n )\n product = models.ForeignKey(\n Product,\n verbose_name='商品名称',\n on_delete=models.CASCADE\n )\n orderout_pcs = models.IntegerField('出库数量', default=0)\n\n def save(self, *args, **kwargs):\n if self.orderout.out_store == \"y\":\n Msg = u'Order(%s) is completed,do not modified.' % self.orderout.out_number\n raise ValidationError(Msg)\n else:\n super(OrderOutProductship, self).save(*args, **kwargs)\n\n class Meta:\n verbose_name = u'出库订单-商品明细'\n verbose_name_plural = u'出库订单-商品明细'\n ordering = ['-id']\n\n"
},
{
"alpha_fraction": 0.5452380776405334,
"alphanum_fraction": 0.6154761910438538,
"avg_line_length": 31.30769157409668,
"blob_id": "6d26f0a082a12c46a61b2179135a989d438db9f8",
"content_id": "02d851631f70e1f35ee2875d0c305aa96fe9eb50",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 840,
"license_type": "no_license",
"max_line_length": 154,
"num_lines": 26,
"path": "/report/migrations/0001_initial.py",
"repo_name": "shumutang/wmsdjango",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.6 on 2017-04-05 18:37\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('wms', '0005_auto_20170404_1226'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Store',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('check_store', models.IntegerField(blank=True, null=True, verbose_name='\\u76d8\\u70b9\\u5e93\\u5b58')),\n ('product_id', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wms.Product', verbose_name='\\u5546\\u54c1\\u7f16\\u7801')),\n ],\n ),\n ]\n"
},
{
"alpha_fraction": 0.5096275806427002,
"alphanum_fraction": 0.613743782043457,
"avg_line_length": 71.2750015258789,
"blob_id": "52050b362501205e76be22b95967f3b5a2f2e8f6",
"content_id": "16bef0ea6f2f4dc43c28e0e123612afdaf19e321",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 8673,
"license_type": "no_license",
"max_line_length": 267,
"num_lines": 120,
"path": "/order/migrations/0001_initial.py",
"repo_name": "shumutang/wmsdjango",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.10.6 on 2017-04-04 04:26\nfrom __future__ import unicode_literals\n\nimport datetime\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport django.utils.timezone\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ('wms', '0005_auto_20170404_1226'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='OrderIn',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('serial_number', models.CharField(blank=True, max_length=16, null=True, verbose_name='\\u8ba2\\u5355\\u6d41\\u6c34(\\u7cfb\\u7edf\\u81ea\\u52a8\\u751f\\u6210)')),\n ('invoice', models.IntegerField(blank=True, null=True, verbose_name='\\u53d1\\u7968\\u53f7')),\n ('pcs', models.IntegerField(blank=True, null=True, verbose_name='\\u8ba2\\u5355pcs')),\n ('boxes', models.IntegerField(blank=True, null=True, verbose_name='\\u5408\\u8ba1\\u7bb1\\u6570')),\n ('order_comment', models.CharField(blank=True, max_length=60, null=True, verbose_name='\\u8ba2\\u5355\\u5907\\u6ce8')),\n ('operate_date', models.DateTimeField(blank=True, default=django.utils.timezone.now, null=True, verbose_name='\\u64cd\\u4f5c\\u65e5\\u671f')),\n ('in_number', models.CharField(blank=True, help_text='\\u7559\\u7a7a\\u7cfb\\u7edf\\u4f1a\\u81ea\\u52a8\\u751f\\u6210', max_length=20, verbose_name='\\u5165\\u5e93\\u7f16\\u53f7')),\n ('sender', models.CharField(blank=True, max_length=30, null=True, verbose_name='\\u7ed3\\u7b97\\u5355\\u4f4d')),\n ('receiver', models.CharField(blank=True, max_length=30, null=True, verbose_name='\\u9001\\u8d27\\u5355\\u4f4d')),\n ('plan_in_time', models.DateField(default=datetime.date.today, verbose_name='\\u8ba1\\u5212\\u5165\\u5e93\\u65e5\\u671f')),\n ('fact_in_time', models.DateField(default=datetime.date.today, verbose_name='\\u5b9e\\u9645\\u5165\\u5e93\\u65e5\\u671f')),\n ('operator', models.CharField(blank=True, max_length=60, null=True, verbose_name='\\u5236\\u5355\\u4eba')),\n ('in_store', models.CharField(choices=[('1', '\\u662f'), ('2', '\\u5426')], default='2', max_length=4, verbose_name='\\u5165\\u5e93')),\n ('order_type', models.CharField(choices=[('zc', '\\u6b63\\u5e38\\u5165\\u5e93'), ('bl', '\\u4e0d\\u826f\\u54c1\\u5165\\u5e93'), ('zp', '\\u8d60\\u54c1\\u5165\\u5e93'), ('qt', '\\u5176\\u4ed6')], default='zc', max_length=10, verbose_name='\\u8ba2\\u5355\\u7c7b\\u578b')),\n ('order_state', models.CharField(choices=[('1', '\\u63a5\\u5355'), ('2', '\\u5df2\\u5165\\u5e93')], default='1', max_length=10, verbose_name='\\u8ba2\\u5355\\u72b6\\u6001')),\n ('customer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wms.Customer', verbose_name='\\u6240\\u5c5e\\u5ba2\\u6237')),\n ],\n options={\n 'ordering': ['plan_in_time'],\n 'verbose_name': '\\u8ba2\\u5355(\\u5165\\u5e93)',\n 'verbose_name_plural': '\\u8ba2\\u5355(\\u5165\\u5e93)',\n },\n ),\n migrations.CreateModel(\n name='OrderInProductship',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('orderin_pcs', models.IntegerField(default=0, verbose_name='\\u5165\\u5e93\\u6570\\u91cf')),\n ('orderin', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='order.OrderIn', verbose_name='\\u5165\\u5e93\\u7f16\\u53f7')),\n ('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wms.Product', verbose_name='\\u5546\\u54c1\\u540d\\u79f0')),\n ],\n options={\n 'verbose_name': '\\u5165\\u5e93\\u8ba2\\u5355-\\u5546\\u54c1\\u660e\\u7ec6',\n 'verbose_name_plural': '\\u5165\\u5e93\\u8ba2\\u5355-\\u5546\\u54c1\\u660e\\u7ec6',\n },\n ),\n migrations.CreateModel(\n name='OrderOut',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('serial_number', models.CharField(blank=True, max_length=16, null=True, verbose_name='\\u8ba2\\u5355\\u6d41\\u6c34(\\u7cfb\\u7edf\\u81ea\\u52a8\\u751f\\u6210)')),\n ('invoice', models.IntegerField(blank=True, null=True, verbose_name='\\u53d1\\u7968\\u53f7')),\n ('pcs', models.IntegerField(blank=True, null=True, verbose_name='\\u8ba2\\u5355pcs')),\n ('boxes', models.IntegerField(blank=True, null=True, verbose_name='\\u5408\\u8ba1\\u7bb1\\u6570')),\n ('order_comment', models.CharField(blank=True, max_length=60, null=True, verbose_name='\\u8ba2\\u5355\\u5907\\u6ce8')),\n ('operate_date', models.DateTimeField(blank=True, default=django.utils.timezone.now, null=True, verbose_name='\\u64cd\\u4f5c\\u65e5\\u671f')),\n ('out_number', models.CharField(blank=True, help_text='\\u7559\\u7a7a\\u7cfb\\u7edf\\u4f1a\\u81ea\\u52a8\\u751f\\u6210', max_length=20, unique=True, verbose_name='\\u51fa\\u5e93\\u7f16\\u53f7')),\n ('fact_out_time', models.DateField(default=datetime.date.today, verbose_name='\\u51fa\\u5e93\\u65e5\\u671f')),\n ('receiver', models.CharField(blank=True, max_length=10, null=True, verbose_name='\\u6536\\u8d27\\u4eba')),\n ('receiver_addr', models.CharField(blank=True, max_length=30, null=True, verbose_name='\\u9001\\u8d27\\u5730\\u5740')),\n ('receiver_phone', models.IntegerField(blank=True, null=True, verbose_name='\\u6536\\u8d27\\u4eba\\u7535\\u8bdd')),\n ('operator', models.CharField(blank=True, max_length=60, null=True, verbose_name='\\u51fa\\u5e93\\u4eba')),\n ('out_store', models.CharField(choices=[('1', '\\u662f'), ('2', '\\u5426')], default='2', max_length=4, verbose_name='\\u51fa\\u5e93')),\n ('order_type', models.CharField(choices=[('zc', '\\u6b63\\u5e38\\u51fa\\u5e93'), ('bl', '\\u4e0d\\u826f\\u54c1\\u51fa\\u5e93'), ('zp', '\\u8d60\\u54c1\\u51fa\\u5e93'), ('qt', '\\u5176\\u4ed6')], default='zc', max_length=10, verbose_name='\\u8ba2\\u5355\\u7c7b\\u578b')),\n ('order_state', models.CharField(choices=[('1', '\\u63a5\\u5355'), ('2', '\\u5df2\\u51fa\\u5e93')], default='1', max_length=10, verbose_name='\\u8ba2\\u5355\\u72b6\\u6001')),\n ('customer', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wms.Customer', verbose_name='\\u6240\\u5c5e\\u5ba2\\u6237')),\n ],\n options={\n 'ordering': ['fact_out_time'],\n 'verbose_name': '\\u8ba2\\u5355(\\u51fa\\u5e93)',\n 'verbose_name_plural': '\\u8ba2\\u5355(\\u51fa\\u5e93)',\n },\n ),\n migrations.CreateModel(\n name='OrderOutProductship',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('orderout_pcs', models.IntegerField(default=0, verbose_name='\\u51fa\\u5e93\\u6570\\u91cf')),\n ('orderout', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='order.OrderOut', verbose_name='\\u51fa\\u5e93\\u7f16\\u53f7')),\n ('product', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wms.Product', verbose_name='\\u5546\\u54c1\\u540d\\u79f0')),\n ],\n options={\n 'verbose_name': '\\u51fa\\u5e93\\u8ba2\\u5355-\\u5546\\u54c1\\u660e\\u7ec6',\n 'verbose_name_plural': '\\u51fa\\u5e93\\u8ba2\\u5355-\\u5546\\u54c1\\u660e\\u7ec6',\n },\n ),\n migrations.AddField(\n model_name='orderout',\n name='product',\n field=models.ManyToManyField(through='order.OrderOutProductship', to='wms.Product', verbose_name='\\u5546\\u54c1\\u540d\\u79f0'),\n ),\n migrations.AddField(\n model_name='orderout',\n name='warehouse',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wms.Warehouse', verbose_name='\\u64cd\\u4f5c\\u4ed3\\u5e93'),\n ),\n migrations.AddField(\n model_name='orderin',\n name='product',\n field=models.ManyToManyField(through='order.OrderInProductship', to='wms.Product', verbose_name='\\u5546\\u54c1\\u540d\\u79f0'),\n ),\n migrations.AddField(\n model_name='orderin',\n name='warehouse',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='wms.Warehouse', verbose_name='\\u64cd\\u4f5c\\u4ed3\\u5e93'),\n ),\n ]\n"
},
{
"alpha_fraction": 0.440828412771225,
"alphanum_fraction": 0.44138312339782715,
"avg_line_length": 24.63033103942871,
"blob_id": "845ecfa8cc0890cdec9768aac77266f107602dcf",
"content_id": "4c913e426ab45d2250f4e12abb68580f376f8dfd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5424,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 211,
"path": "/wms/admin.py",
"repo_name": "shumutang/wmsdjango",
"src_encoding": "UTF-8",
"text": "# -*-coding:utf-8-*-\n\nfrom __future__ import unicode_literals\n\nfrom django.contrib import admin\n\n# Register your models here.\n\nfrom import_export.admin import ImportExportModelAdmin\nfrom import_export import resources\n\nfrom .models import Customer , Product , Location , Warehouse\n\nclass ProductResource(resources.ModelResource):\n class Meta:\n model = Product\n import_id_fields = ('barcode' ,)\n fields = ['customer'\n , 'name'\n , 'ename'\n , 'help_name'\n , 'batch_num'\n , 'type'\n , 'categories'\n , 'base_unit'\n , 'pcs_perunit'\n , 'Logistics_unit'\n , 'pcs_Logistics'\n , 'life_day'\n , 'price'\n , 'width'\n , 'height'\n , 'length'\n , 'weight'\n , 'net_weight'\n , 'valid_flag'\n , 'barcode'\n , 'specs'\n , 'brand'\n , 'ordinal'\n ]\n\n\nclass ProductAdmin(ImportExportModelAdmin):\n resource_class = ProductResource\n list_per_page = 20\n list_display = ['barcode'\n , 'product_id'\n , 'name'\n , 'ename'\n , 'customer'\n , 'help_name'\n , 'batch_num'\n , 'type'\n , 'categories'\n , 'base_unit'\n , 'pcs_perunit'\n , 'Logistics_unit'\n , 'pcs_Logistics'\n , 'life_day'\n , 'price'\n , 'width' , 'height' , 'length' , 'weight' , 'volume' , 'net_weight' , 'valid_flag' ]\n list_display_links = ['barcode']\n fieldsets = [\n (None , {'fields': ['barcode'\n , 'product_id'\n , 'name'\n , 'ename'\n , 'customer'\n , 'help_name'\n , 'pcs_Logistics'\n , 'batch_num' , 'type' , 'categories' , 'base_unit' , 'pcs_perunit' ,]}) ,\n\n (u'包装信息' , {'fields': ['life_day'\n , 'price'\n , 'width'\n , 'height'\n , 'length'\n , 'weight'\n , 'net_weight'\n , 'valid_flag'\n , 'Logistics_unit'\n , 'specs'\n , 'brand'\n , 'ordinal'] ,\n 'classes': ['collapse']}) ,\n ]\n search_fields = ['product_id'\n , 'help_name'\n , 'name'\n , 'ename'\n , 'batch_num'\n , 'customer__name'\n , 'type'\n , 'barcode'\n , 'categories']\nadmin.site.register(Product , ProductAdmin)\n\n\nclass CustomerResource(resources.ModelResource):\n class Meta:\n model = Customer\n import_id_fields = ('name' ,)\n fields = ('name' , 'address' , 'city' , 'tel' , 'phone' , 'email')\n\nclass CustomerAdmin(ImportExportModelAdmin):\n resource_class = CustomerResource\n list_display = ['customer_id' , 'name' , 'address' , 'city' , 'tel' , 'phone' , 'email']\n search_fields = ['name' , 'address' , 'city' , 'tel' , 'phone' , 'email']\n\nadmin.site.register(Customer , CustomerAdmin)\n\n\nclass WarehouseResource(resources.ModelResource):\n class Meta:\n model = Warehouse\n\nclass WarehouseAdmin(ImportExportModelAdmin):\n resource_class = WarehouseResource\n list_display = ['wh_id' , 'name' , 'ename' , 'address' , 'type']\n search_fields = ['wh_id' , 'name' , 'ename' , 'address' , 'type' , ]\nadmin.site.register(Warehouse , WarehouseAdmin)\n\nclass LocationResource(resources.ModelResource):\n class Meta:\n model = Location\n fields = ['location_id'\n , 'state'\n , 'type'\n , 'category'\n , 'freeze_flag'\n , 'area'\n , 'mixstore'\n , 'mixbatch'\n , 'repeate'\n , 'x'\n , 'y'\n , 'z'\n , 'valid_flag'\n , 'standcode'\n , 'up'\n , 'left'\n , 'length'\n , 'width'\n , 'volume'\n , 'comment'\n , 'help_tag'\n , 'name'\n , 'customer'\n , 'warehouse']\n\n import_id_fields = ('location_id' ,)\n\n\nclass LocationAdmin(ImportExportModelAdmin):\n resource_class = LocationResource\n list_display = ['location_id'\n , 'state'\n , 'type'\n , 'category'\n , 'freeze_flag'\n , 'area'\n , 'mixstore'\n , 'mixbatch'\n , 'repeate'\n , 'x'\n , 'y'\n , 'z'\n , 'valid_flag'\n , 'standcode'\n , 'up'\n , 'left'\n , 'length'\n , 'width'\n , 'volume'\n , 'comment'\n , 'help_tag'\n , 'name'\n , 'customer'\n , 'warehouse']\n search_fields = ['location_id' , 'state' , 'type' , 'category' , 'name']\n\n fieldsets = [\n (None , {'fields': ['location_id'\n , 'state'\n , 'type'\n , 'category'\n , 'freeze_flag'\n , 'area'\n , 'mixstore'\n , 'mixbatch'\n , 'repeate'\n , 'warehouse'\n , 'customer']}) ,\n\n (u'扩展信息' , dict(fields=[('x'\n , 'y'\n , 'z')\n , 'valid_flag'\n , 'standcode'\n , 'up'\n , 'left'\n , 'length'\n , 'width'\n , 'volume'\n , 'comment'\n , 'help_tag'\n , 'name'] , classes=['collapse'])) ,\n ]\n\nadmin.site.register(Location , LocationAdmin)\n"
},
{
"alpha_fraction": 0.8181818127632141,
"alphanum_fraction": 0.8181818127632141,
"avg_line_length": 10,
"blob_id": "a5ebf9e243fb2cbebb59b5484ba66e2b9969cf61",
"content_id": "336623fee0ad0f08724634670592c41c59dddaa3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 22,
"license_type": "no_license",
"max_line_length": 11,
"num_lines": 2,
"path": "/README.md",
"repo_name": "shumutang/wmsdjango",
"src_encoding": "UTF-8",
"text": "# wmsdjango\nwmsdjango\n"
},
{
"alpha_fraction": 0.6745561957359314,
"alphanum_fraction": 0.6804733872413635,
"avg_line_length": 17.77777862548828,
"blob_id": "321064a9dda1d49ce98ca5183ee9dabfafa83f9c",
"content_id": "a3a88ff73b7c379df10726c5fca80cb325bcc3b9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 177,
"license_type": "no_license",
"max_line_length": 39,
"num_lines": 9,
"path": "/wms/apps.py",
"repo_name": "shumutang/wmsdjango",
"src_encoding": "UTF-8",
"text": "# -*-coding:utf-8-*-\n\nfrom __future__ import unicode_literals\n\nfrom django.apps import AppConfig\n\nclass WmsConfig(AppConfig):\n name = 'wms'\n verbose_name = \"信息维护\"\n"
},
{
"alpha_fraction": 0.5868346691131592,
"alphanum_fraction": 0.5885708332061768,
"avg_line_length": 33.75689697265625,
"blob_id": "c41c8e79371d937303b3ac82f93c68739812b031",
"content_id": "8ce51837421905a84d73c99fe7154235978c6a45",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 20779,
"license_type": "no_license",
"max_line_length": 111,
"num_lines": 580,
"path": "/order/admin.py",
"repo_name": "shumutang/wmsdjango",
"src_encoding": "UTF-8",
"text": "# -*-coding:utf-8-*-\n\nfrom __future__ import unicode_literals\n\nfrom django.contrib import admin\nfrom django import forms\nfrom django.forms import ModelForm\nfrom django.contrib.admin.widgets import ForeignKeyRawIdWidget\nfrom django.contrib.admin.widgets import ManyToManyRawIdWidget\n\nfrom django.contrib.admin.templatetags.admin_urls import add_preserved_filters\nfrom django.http import HttpResponseRedirect\n\nfrom django.db.models import Count, Sum\n\nfrom time import time\nfrom datetime import datetime\n\nfrom django.urls import reverse\nfrom django.shortcuts import render\n\nfrom import_export.admin import ImportExportModelAdmin\nfrom import_export import resources\n\nfrom .models import OrderInProductship, OrderOutProductship, OrderOut, OrderIn\n\nadmin.site.disable_action('delete_selected')\n\n\nclass OrderInProductshipForm(forms.ModelForm):\n class Meta:\n model = OrderInProductship\n fields = '__all__'\n widgets = {\n 'product': ForeignKeyRawIdWidget(OrderInProductship._meta.get_field(\"product\").rel,\n admin.site,\n attrs={'size': '40', 'width': '15em'}),\n 'orderin_pcs': forms.TextInput(attrs={'size': '10'}),\n }\n\nclass OrderInProductshipInline(admin.TabularInline):\n fields = ['product', 'barcode', 'specs', 'productid', 'orderin_pcs', ]\n readonly_fields = ['specs', 'barcode', 'productid', ]\n\n def barcode(self, obj):\n return obj.product.barcode\n\n barcode.short_description = u\"条形码\"\n\n def productid(self, obj):\n return obj.product.product_id\n\n productid.short_description = u'商品编码'\n\n def specs(self, obj):\n return obj.product.specs\n\n specs.short_description = u'规格'\n\n model = OrderInProductship\n extra = 5\n fk_name = 'orderin'\n #raw_id_fields = ['product']\n form = OrderInProductshipForm\n\nclass OrderOutProductshipInline(admin.TabularInline):\n fields = ['product', 'barcode', 'specs', 'productid', 'store', 'orderout_pcs', ]\n readonly_fields = ['specs', 'barcode', 'productid', 'store']\n\n def barcode(self, obj):\n return obj.product.barcode\n\n barcode.short_description = u\"条形码\"\n\n def productid(self, obj):\n return obj.product.product_id\n\n productid.short_description = u'商品编码'\n\n def specs(self, obj):\n return obj.product.specs\n\n specs.short_description = u'规格'\n\n def store(self, obj):\n barcode = obj.product.barcode\n instore = OrderInProductship.objects.filter(\n product=barcode\n , orderin__in_store='y').aggregate(Sum('orderin_pcs'))\n outstore = OrderOutProductship.objects.filter(\n product=barcode\n , orderout__out_store='y').aggregate(Sum('orderout_pcs'))\n instore_pcs = 0 if instore['orderin_pcs__sum'] == None else instore['orderin_pcs__sum']\n outstore_pcs = 0 if outstore['orderout_pcs__sum'] == None else outstore['orderout_pcs__sum']\n return instore_pcs - outstore_pcs\n store.short_description = u'库存'\n\n model = OrderOutProductship\n extra = 5\n fk_name = 'orderout'\n raw_id_fields = ['product']\n\nclass OrderInResource(resources.ModelResource):\n class Meta:\n model = OrderIn\n import_id_fields = ('in_number' ,)\n fields = ('in_number', 'customer', 'warehouse', 'plan_in_time')\n\nclass OrderInAdmin(ImportExportModelAdmin):\n resource_class = OrderInResource\n readonly_fields = ['in_store', ]\n list_display = ['in_number'\n , 'customer'\n , 'warehouse'\n , 'order_type'\n , 'order_comment'\n , 'serial_number'\n , 'in_store'\n , 'plan_in_time'\n , 'fact_in_time'\n , 'operator'\n , 'operate_date']\n search_fields = ['in_number', 'customer__name', 'in_store', 'product__name']\n list_display_links = ['in_number']\n inlines = [OrderInProductshipInline]\n fieldsets = [\n (None, {'fields': ['in_number'\n , 'warehouse'\n , 'customer'\n , 'order_type'\n , 'in_store'\n , 'plan_in_time'\n , 'fact_in_time'\n , 'order_comment']}),\n\n (u'扩展信息', {'fields': ['serial_number'\n , 'invoice'\n , 'sender'\n , 'pcs'\n , 'boxes'\n , 'receiver'\n , 'operator'],\n 'classes': ['collapse']}),\n ]\n\n actions = ['make_instore', 'print_instore_detail']\n\n\n def make_instore(self, request, queryset):\n for order in queryset:\n if order.in_store == 'n':\n order.in_store = 'y'\n order.save()\n msg = u'订单(%s) 完成入库确认' % order.in_number\n elif order.in_store == 'y':\n msg = u'订单(%s) 已入库完成,不需重复确认入库' % order.in_number\n else:\n msg = u'订单(%s) 确认入库异常' % order.in_number\n self.message_user(request, msg)\n make_instore.short_description = u\"确认入库\"\n\n def print_instore_detail(self, request, queryset):\n for order in queryset:\n in_number = order.in_number\n context = {'order_product_list': OrderInProductship.objects.filter(orderin=in_number)}\n return render(request, 'order/indetail.html', context)\n print_instore_detail.short_description = u\"打印入库单\"\n\n def save_model(self, request, obj, form, change):\n if change:\n obj_old = self.model.objects.get(pk=obj.pk)\n if obj_old.in_store == 'y':\n Msg = u'已完成订单\"%s\",不能被修改' % obj.in_number\n self.message_user(request, Msg, 40)\n else:\n super(OrderInAdmin, self).save_model(request, obj, form, change)\n else:\n ts = int(time())\n now = datetime.now()\n nowstr = now.strftime('%Y%m%d%H%M%S')\n if not obj.in_number:\n obj.in_number = \"in%s\" % ts\n obj.serial_number = \"%s%s\" % (obj.order_type, nowstr)\n obj.operator = request.user.username\n super(OrderInAdmin, self).save_model(request, obj, form, change)\n\n def save_formset(self, request, form, formset, change):\n orderin = form.instance\n instances = formset.save(commit=False)\n for instance in instances:\n if change and orderin.in_store == 'y':\n Msg = u'已完成订单\"%s\",不能被修改' % orderin.in_number\n self.message_user(request, Msg, 40)\n else:\n super(OrderInAdmin, self).save_formset(request, form, formset, change)\n\n def delete_model(self, request, obj):\n if obj.in_store == 'y':\n Msg = u'已完成订单\"%s\",不能被删除' % obj.in_number\n self.message_user(request, Msg, 40)\n else:\n super(OrderInAdmin, self).delete_model(request, obj)\n\n def response_change(self, request, obj):\n if obj.in_store == 'y':\n return self.response_post_save_change(request, obj)\n else:\n super(OrderInAdmin, self).response_change(request, obj)\n return self.response_post_save_change(request, obj)\n\n def response_delete(self, request, obj_display, obj_id):\n opts = self.model._meta\n if self.has_change_permission(request, None):\n post_url = reverse(\n 'admin:%s_%s_changelist' % (opts.app_label, opts.model_name),\n current_app=self.admin_site.name,\n )\n preserved_filters = self.get_preserved_filters(request)\n post_url = add_preserved_filters(\n {'preserved_filters': preserved_filters, 'opts': opts}, post_url\n )\n else:\n post_url = reverse('admin:index', current_app=self.admin_site.name)\n try:\n self.model.objects.get(pk=obj_id)\n return HttpResponseRedirect(post_url)\n except:\n super(OrderInAdmin, self).response_delete(request, obj_display, obj_id)\n return HttpResponseRedirect(post_url)\n\nadmin.site.register(OrderIn, OrderInAdmin)\n\n\nclass OrderOutResource(resources.ModelResource):\n class Meta:\n model = OrderOut\n\nclass OrderOutAdmin(ImportExportModelAdmin):\n resource_class = OrderOutResource\n readonly_fields = ['out_store', ]\n list_display = ['out_number'\n , 'customer'\n , 'warehouse'\n , 'order_type'\n , 'order_comment'\n , 'operator'\n , 'out_store'\n , 'fact_out_time'\n , 'serial_number'\n , 'operator'\n , 'operate_date']\n search_fields = ['out_number', 'customer__name', 'warehouse__ename', ]\n inlines = [OrderOutProductshipInline]\n fieldsets = [\n (None, {'fields': ['out_number'\n , 'warehouse'\n , 'customer'\n , 'order_type'\n , 'out_store'\n , 'fact_out_time'\n , 'order_comment'\n , ]}),\n\n (u'扩展信息', {'fields': ['serial_number'\n , 'invoice'\n , 'pcs'\n , 'boxes'\n , ('receiver', 'receiver_addr', 'receiver_phone')\n , 'operator'],\n 'classes': ['collapse']}),\n ]\n radio_fields = {\"out_store\": admin.VERTICAL}\n actions = ['make_outstore','print_outstore_detail']\n\n def make_outstore(self, request, queryset):\n for order in queryset:\n if order.out_store == 'n':\n order.out_store = 'y'\n order.save()\n msg = u'订单(%s) 完成出库确认' % order.out_number\n elif order.out_store == 'y':\n msg = u'订单(%s) 已出库完成,不需重复确认出库' % order.out_number\n else:\n msg = u'订单(%s) 确认出库异常' % order.out_number\n self.message_user(request, msg)\n make_outstore.short_description = u\"确认出库\"\n\n def print_outstore_detail(self, request, queryset):\n for order in queryset:\n out_number = order.out_number\n context = {'order_product_list': OrderOutProductship.objects.filter(orderout=out_number)}\n return render(request, 'order/outdetail.html', context)\n print_outstore_detail.short_description = u\"打印出库单\"\n\n def save_model(self, request, obj, form, change):\n if change:\n obj_old = self.model.objects.get(pk=obj.pk)\n if obj_old.out_store == 'y':\n Msg = u'已完成订单\"%s\",不能被修改' % obj.out_number\n self.message_user(request, Msg, 40)\n else:\n super(OrderOutAdmin, self).save_model(request, obj, form, change)\n else:\n ts = int(time())\n now = datetime.now()\n nowstr = now.strftime('%Y%m%d%H%M%S')\n if not obj.out_number:\n obj.out_number = \"out%s\" % ts\n obj.serial_number = \"%s%s\" % (obj.order_type, nowstr)\n obj.operator = request.user.username\n super(OrderOutAdmin, self).save_model(request, obj, form, change)\n\n def save_formset(self, request, form, formset, change):\n orderout = form.instance\n instances = formset.save(commit=False)\n for instance in instances:\n if change and orderout.out_store == 'y':\n Msg = u'已完成订单\"%s\",不能被修改' % orderout.out_number\n self.message_user(request, Msg, 40)\n else:\n super(OrderOutAdmin, self).save_formset(request, form, formset, change)\n\n def delete_model(self, request, obj):\n if obj.out_store == 'y':\n Msg = u'已完成订单\"%s\",不能被删除' % obj.out_number\n self.message_user(request, Msg, 40)\n # messages.add_message(request, messages.ERROR, Msg)\n else:\n super(OrderOutAdmin, self).delete_model(request, obj)\n\n def response_change(self, request, obj):\n if obj.out_store == 'y':\n return self.response_post_save_change(request, obj)\n else:\n super(OrderOutAdmin, self).response_change(request, obj)\n return self.response_post_save_change(request, obj)\n\n def response_delete(self, request, obj_display, obj_id):\n opts = self.model._meta\n if self.has_change_permission(request, None):\n post_url = reverse(\n 'admin:%s_%s_changelist' % (opts.app_label, opts.model_name),\n current_app=self.admin_site.name,\n )\n preserved_filters = self.get_preserved_filters(request)\n post_url = add_preserved_filters(\n {'preserved_filters': preserved_filters, 'opts': opts}, post_url\n )\n else:\n post_url = reverse('admin:index', current_app=self.admin_site.name)\n try:\n self.model.objects.get(pk=obj_id)\n return HttpResponseRedirect(post_url)\n except:\n super(OrderOutAdmin, self).response_delete(request, obj_display, obj_id)\n return HttpResponseRedirect(post_url)\n\nadmin.site.register(OrderOut, OrderOutAdmin)\n\n\nclass OrderInProductshipResource(resources.ModelResource):\n class Meta:\n model = OrderInProductship\n\nclass OrderInProductshipAdmin(ImportExportModelAdmin):\n resource_class = OrderInProductshipResource\n list_per_page = 20\n list_display = ['id'\n , 'innumber'\n , 'productcode'\n , 'product'\n , 'specs'\n , 'barcode'\n , 'instore'\n , 'orderin_pcs'\n , 'plan_intime'\n , 'fact_intime'\n , 'operate_time'\n ]\n search_fields = ['orderin__in_number'\n , 'product__product_id'\n , 'product__barcode'\n , 'product__specs'\n ]\n list_filter = ['orderin__in_store'\n , 'orderin__fact_in_time'\n ]\n actions = None\n # raw_id_fields = ['product']\n view_on_site = False\n list_display_links = ['id','barcode',]\n\n def barcode(self, obj):\n result = '<a href=\"%s%s\">%s</a> ' % ('../../wms/product/', obj.product.barcode, obj.product.barcode)\n return result\n barcode.allow_tags = True\n barcode.short_description = u\"条形码\"\n\n def innumber(self, obj):\n result = '<a href=\"%s%s\">%s</a> ' % ('../orderin/', obj.orderin.in_number, obj.orderin.in_number,)\n return result\n innumber.allow_tags = True\n innumber.short_description = u\"入库编号\"\n\n def productcode(self, obj):\n return obj.product.product_id\n\n productcode.short_description = u'商品编码'\n\n def specs(self, obj):\n return obj.product.specs\n\n specs.short_description = u'规格'\n\n def plan_intime(self, obj):\n return obj.orderin.plan_in_time\n\n plan_intime.short_description = u'计划入库日期'\n\n def fact_intime(self, obj):\n return obj.orderin.fact_in_time\n\n fact_intime.short_description = u'实际入库日期'\n\n def operate_time(self, obj):\n return obj.orderin.operate_date\n\n operate_time.short_description = u'操作日期'\n\n def instore(self, obj):\n return u'已完成' if obj.orderin.in_store == 'y' else u'未完成'\n\n instore.short_description = u'入库'\n\n def save_model(self, request, obj, form, change):\n if change:\n obj_old = self.model.objects.get(pk=obj.pk)\n if obj_old.orderin.in_store == 'y':\n Msg = u'已完成订单,不能被修改'\n self.message_user(request, Msg, 40)\n else:\n super(OrderInProductshipAdmin, self).save_model(request, obj, form, change)\n else:\n super(OrderInProductshipAdmin, self).save_model(request, obj, form, change)\n\n def delete_model(self, request, obj):\n if obj.orderin.in_store == 'y':\n Msg = u'已完成订单,不能被删除'\n self.message_user(request, Msg, 40)\n else:\n super(OrderInProductshipAdmin, self).delete_model(request, obj)\n\n def response_change(self, request, obj):\n if obj.orderin.in_store == 'y':\n Msg = u'已完成订单,不能被删除'\n # messages.add_message(request, messages.ERROR, Msg)\n return self.response_post_save_change(request, obj)\n else:\n super(OrderInProductshipAdmin, self).response_change(request, obj)\n return self.response_post_save_change(request, obj)\n\n def response_delete(self, request, obj_display, obj_id):\n obj_old = self.model.objects.get(pk=obj_id)\n post_url = reverse('admin:index', current_app=self.admin_site.name)\n if obj_old.orderin.in_store == 'y':\n return self.response_post_save_change(request, obj_old)\n else:\n super(OrderInProductshipAdmin, self).response_delete(request, obj_display, obj_id)\n return self.response_post_save_change(request, obj_old)\n\nadmin.site.register(OrderInProductship, OrderInProductshipAdmin)\n\n\nclass OrderOutProductshipResource(resources.ModelResource):\n class Meta:\n model = OrderOutProductship\n\n\nclass OrderOutProductshipAdmin(ImportExportModelAdmin):\n resource_class = OrderOutProductshipResource\n list_per_page = 20\n list_display = ['id'\n , 'outnumber'\n , 'productcode'\n , 'product'\n , 'specs'\n , 'barcode'\n , 'orderout_pcs'\n , 'outstore'\n , 'fact_outtime'\n , 'operate_time'\n ]\n search_fields = ['orderout__out_number'\n , 'product__product_id'\n , 'product__barcode'\n , 'product__specs'\n ]\n list_filter = ['orderout__out_store'\n , 'orderout__operate_date'\n ]\n actions = None\n # raw_id_fields = ['product']\n view_on_site = False\n list_display_links = ['id', 'barcode', 'outnumber']\n\n def barcode(self, obj):\n result = '<a href=\"%s%s\">%s</a> ' % ('../../wms/product/', obj.product.barcode, obj.product.barcode)\n return result\n barcode.allow_tags = True\n barcode.short_description = u\"条形码\"\n\n def outnumber(self, obj):\n result = '<a href=\"%s%s\">%s</a> ' % ('../orderout/', obj.orderout.out_number, obj.orderout.out_number,)\n return result\n outnumber.allow_tags = True\n outnumber.short_description = u\"出库编号\"\n\n def productcode(self, obj):\n return obj.product.product_id\n\n productcode.short_description = u'商品编码'\n\n def specs(self, obj):\n return obj.product.specs\n\n specs.short_description = u'规格'\n\n def fact_outtime(self, obj):\n return obj.orderout.fact_out_time\n\n fact_outtime.short_description = u'实际出库日期'\n\n def operate_time(self, obj):\n return obj.orderout.operate_date\n\n operate_time.short_description = u'操作日期'\n\n def outstore(self, obj):\n return u'已完成' if obj.orderout.out_store == 'y' else u'未完成'\n\n outstore.short_description = u'出库'\n\n def save_model(self, request, obj, form, change):\n if change:\n obj_old = self.model.objects.get(pk=obj.pk)\n if obj_old.orderout.out_store == 'y':\n Msg = u'已完成订单,不能被修改'\n self.message_user(request, Msg, 40)\n else:\n super(OrderOutProductshipAdmin, self).save_model(request, obj, form, change)\n else:\n super(OrderOutProductshipAdmin, self).save_model(request, obj, form, change)\n\n def delete_model(self, request, obj):\n if obj.orderout.out_store == 'y':\n Msg = u'已完成订单,不能被删除'\n self.message_user(request, Msg, 40)\n else:\n super(OrderOutProductshipAdmin, self).delete_model(request, obj)\n\n def response_change(self, request, obj):\n if obj.orderout.out_store == 'y':\n return self.response_post_save_change(request, obj)\n else:\n super(OrderOutProductshipAdmin, self).response_change(request, obj)\n return self.response_post_save_change(request, obj)\n\n def response_delete(self, request, obj_display, obj_id):\n obj_old = self.model.objects.get(pk=obj_id)\n post_url = reverse('admin:index', current_app=self.admin_site.name)\n if obj_old.orderout.out_store == 'y':\n # Msg = u'已完成订单,不能被删除'\n # messages.add_message(request, messages.ERROR, Msg)\n # return HttpResponseRedirect(post_url)\n return self.response_post_save_change(request, obj_old)\n else:\n super(OrderOutProductshipAdmin, self).response_delete(request, obj_display, obj_id)\n return self.response_post_save_change(request, obj_old)\n\nadmin.site.register(OrderOutProductship, OrderOutProductshipAdmin)\n"
},
{
"alpha_fraction": 0.7182795405387878,
"alphanum_fraction": 0.7204301357269287,
"avg_line_length": 24.83333396911621,
"blob_id": "b7c2a7a5c184c0d11b6778be694243684d4035e6",
"content_id": "05a78326c84777c69d5f701c096a68e4e2a4b72b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 497,
"license_type": "no_license",
"max_line_length": 67,
"num_lines": 18,
"path": "/report/models.py",
"repo_name": "shumutang/wmsdjango",
"src_encoding": "UTF-8",
"text": "# -*-coding:utf-8-*-\n\nfrom __future__ import unicode_literals\n\nfrom django.db import models\n\nfrom order.models import OrderInProductship, OrderOutProductship\nfrom wms.models import Product\n\n# Create your models here.\n\nclass Store(models.Model):\n product_id = models.ForeignKey(Product, verbose_name=u'商品编码')\n check_store = models.IntegerField(u'盘点库存',null=True,blank=True)\n\n class Meta:\n verbose_name = u'库存报表'\n verbose_name_plural = u'库存报表'\n"
},
{
"alpha_fraction": 0.6001989841461182,
"alphanum_fraction": 0.6173962354660034,
"avg_line_length": 36.22222137451172,
"blob_id": "71caeb3e9e1f2d8c09b0d883ab2e0f9f4270f940",
"content_id": "22294a035be0203d0f9f8bf53ad1c1d62c69c7c2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7600,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 189,
"path": "/wms/models.py",
"repo_name": "shumutang/wmsdjango",
"src_encoding": "UTF-8",
"text": "# -*-coding:utf-8-*-\n\nfrom __future__ import unicode_literals\n\n\nfrom django.db import models\nfrom django.utils.encoding import python_2_unicode_compatible\n\n\n# Create your models here.\n\n@python_2_unicode_compatible\nclass Customer(models.Model):\n customer_id = models.IntegerField('客户编码',help_text=u'留空系统自动生成',unique=True, blank=True)\n name = models.CharField('客户名称', max_length=60)\n address = models.CharField('地址', max_length=80)\n city = models.CharField('城市', max_length=20)\n tel = models.CharField('电话', max_length=15)\n phone = models.CharField('手机', max_length=11)\n email = models.EmailField('邮箱', max_length=75, blank=True)\n\n class Meta:\n verbose_name = u'客户'\n verbose_name_plural = u'客户'\n\n def __str__(self):\n return self.name\n\n\n def save(self, *args, **kwargs):\n if self.customer_id is None:\n self.customer_id = -1\n super (Customer, self).save (*args, **kwargs)\n self.customer_id = 100000 + self.id\n super (Customer, self).save (*args, **kwargs)\n super(Customer , self).save(*args , **kwargs)\n\n\n@python_2_unicode_compatible\nclass Product(models.Model):\n categories_choices = (\n (u'1', u'有条码'),\n (u'2', u'无条码'),\n (u'3', u'其他'),\n )\n base_unit_choices = (\n (u'1', u'箱'),\n (u'2', u'桶'),\n (u'3', u'包'),\n (u'4', u'台'),\n (u'5', u'瓶'),\n (u'6', u'件'),\n (u'9', u'其他'),\n )\n valid_flag_choices = (\n (u'Y', u'Y'),\n (u'N', u'N'),\n )\n barcode = models.BigIntegerField('条形码', primary_key=True,)\n product_id = models.IntegerField('商品编码',help_text=u'留空系统会自动生成', unique=True, blank=True)\n customer = models.ForeignKey(Customer, verbose_name='所属客户')\n name = models.CharField('中文名称', max_length=40)\n ename = models.CharField('英文名称', max_length=20, blank=True, null=True)\n help_name = models.CharField('助记码', max_length=20, blank=True)\n batch_num = models.CharField('货物批号', max_length=20, blank=True)\n type = models.CharField('型号', max_length=20, blank=True, null=True)\n categories = models.CharField('商品分类', max_length=20,choices=categories_choices,default='1')\n base_unit = models.CharField('基本单位', max_length=6,choices=base_unit_choices,default='1')\n pcs_perunit = models.IntegerField('PCS/箱', default=1)\n Logistics_unit = models.CharField('物流单位', max_length=10, choices=base_unit_choices,blank=True, null=True)\n pcs_Logistics = models.IntegerField('PCS/标准板', default=1)\n life_day = models.IntegerField('保质期(天)', default=0)\n price = models.DecimalField('单价', max_digits=10, decimal_places=2, null=True, blank=True)\n width = models.IntegerField('宽度(CM)', default=0)\n height = models.IntegerField('高度(CM)', default=0)\n length = models.IntegerField('长度(CM)', default=0)\n weight = models.IntegerField('重量(KG)', default=0)\n net_weight = models.IntegerField('净重(KG)', default=0)\n valid_flag = models.CharField('有效标志', max_length=6, default='Y')\n specs = models.CharField('规格', max_length=60, blank=True, null=True)\n brand = models.CharField('品牌', max_length=20, blank=True, null=True)\n ordinal = models.IntegerField('序号', blank=True, null=True, default=0)\n\n class Meta:\n verbose_name = u'商品'\n verbose_name_plural = u'商品'\n\n def __str__(self):\n return \"%s , %s , %s , %s\" % (self.name, self.ename, self.help_name, self.specs)\n\n def volume(self):\n return self.width * self.height * self.length\n volume.short_description = u'体积'\n\n def save(self, *args, **kwargs):\n if self.product_id is None:\n self.product_id = -1\n super(Product, self).save(*args, **kwargs)\n self.product_id = 10000000 + Product.objects.count()\n super(Product, self).save(*args, **kwargs)\n super(Product, self).save(*args, **kwargs)\n\n\n@python_2_unicode_compatible\nclass Warehouse(models.Model):\n type_choices = (\n (u'normal', u'全品类仓库'),\n (u'blp', u'不良品仓库'),\n (u'zp', u'赠品仓库'),\n )\n wh_id = models.IntegerField('仓库编号',unique=True, help_text=u'留空系统会自动生成', blank=True)\n name = models.CharField('仓库名称', max_length=80)\n ename = models.CharField('仓库简码', max_length=4, blank=True, null=True)\n address = models.CharField('仓库地址', max_length=75, blank=True)\n type = models.CharField('仓库类型', max_length=8, choices=type_choices, default='normal')\n\n class Meta:\n verbose_name = u'仓库'\n verbose_name_plural = u'仓库'\n\n def __str__(self):\n return self.name\n\n def save(self , *args , **kwargs):\n if self.wh_id is None:\n self.wh_id = -1\n super(Warehouse , self).save(*args , **kwargs)\n self.wh_id = 10000 + self.id\n super(Warehouse , self).save(*args , **kwargs)\n super(Warehouse , self).save(*args , **kwargs)\n\n\nclass Location(models.Model):\n loca_state_choice = (\n (u'1', u'可用库位'),\n (u'2', u'已用库位'),\n )\n\n loca_type_choices = (\n (u'1', u'平面仓'),\n (u'2', u'立体仓'),\n )\n\n loca_category_choices = (\n (u'1', u'全功能'),\n (u'2', u'其他'),\n )\n\n freeze_flag_choices = (\n (u'Y', u'Y'),\n (u'N', u'N'),\n )\n\n flag_choices = (\n (u'Y', u'Y'),\n (u'N', u'N'),\n )\n\n customer = models.ForeignKey(Customer,verbose_name='所属客户')\n warehouse = models.ForeignKey(Warehouse,verbose_name='所属仓库')\n location_id = models.CharField('库位条码', max_length=8)\n state = models.CharField('库位状态', max_length=8,choices=loca_state_choice)\n type = models.CharField('库位类型', max_length=8,choices=loca_type_choices,default=1)\n category = models.CharField('库位类别', max_length=8,choices=loca_category_choices,default=1)\n freeze_flag = models.CharField('冻结标志', max_length=2,choices=freeze_flag_choices,default='N')\n area = models.CharField('仓库区域', max_length=8,null=True,blank=True)\n mixstore = models.CharField('是否混储', max_length=2,choices=flag_choices,default='Y')\n mixbatch = models.CharField('是否混批', max_length=2,choices=flag_choices,default='Y')\n repeate = models.CharField('重复装托', max_length=2,choices=flag_choices,default='Y')\n x = models.IntegerField('X坐标',default=0)\n y = models.IntegerField('Y坐标',default=0)\n z = models.IntegerField('Z坐标',default=0)\n valid_flag = models.CharField('有效标志',max_length=2,choices=flag_choices,default='Y')\n standcode = models.CharField('标准代码', max_length=8)\n up = models.IntegerField('上坐标', default=0)\n left = models.IntegerField('左坐标', default=0)\n length = models.IntegerField('长度', default=0)\n width = models.IntegerField('宽度', default=0)\n volume = models.IntegerField('货物容积', default=0)\n comment = models.CharField('备注', max_length= 80,null=True,blank=True)\n help_tag = models.CharField('助记符',max_length=8,null=True,blank=True)\n name = models.CharField('中文名称', max_length= 16,null=True,blank=True)\n\n class Meta:\n verbose_name = u'库位'\n verbose_name_plural = u'库位'\n\n def __str__(self):\n return self.location_id\n\n"
}
] | 10 |
brymut/ElasticSearch_Django_Prototype | https://github.com/brymut/ElasticSearch_Django_Prototype | cbe5e505ffbf3091c0c632700ee3cbeb7a5901df | cb68c37ad40cbfa8657c9634a4424dc1b1002505 | b89dc932ed3dc95dd74eb9fe3c45b0fe2ad28e44 | refs/heads/master | 2023-01-04T01:57:53.281135 | 2016-11-16T13:09:34 | 2016-11-16T13:09:34 | 73,836,057 | 0 | 0 | null | 2016-11-15T17:01:58 | 2016-11-16T13:09:50 | 2022-12-26T20:02:10 | Python | [
{
"alpha_fraction": 0.8287671208381653,
"alphanum_fraction": 0.8287671208381653,
"avg_line_length": 72,
"blob_id": "614eb1c57ce94af63bd191a155329ee52961b7dc",
"content_id": "f681cdd364671c6c9a550976883c11480fc1ef51",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 146,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 2,
"path": "/README.md",
"repo_name": "brymut/ElasticSearch_Django_Prototype",
"src_encoding": "UTF-8",
"text": "# ElasticSearch_Django_Prototype\nA Prototype file search django application that utilises Elastic Search. Just wanted to see where this would go.\n"
},
{
"alpha_fraction": 0.5598323345184326,
"alphanum_fraction": 0.5724085569381714,
"avg_line_length": 48.50943374633789,
"blob_id": "7c37564129f7326d8020a6c35522feef69e84b5e",
"content_id": "4043a93cf4187a97fc45f428ccb7f39a3632d7a5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2624,
"license_type": "no_license",
"max_line_length": 580,
"num_lines": 53,
"path": "/project/apps/core/migrations/0001_initial.py",
"repo_name": "brymut/ElasticSearch_Django_Prototype",
"src_encoding": "UTF-8",
"text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.9.3 on 2016-11-16 12:06\nfrom __future__ import unicode_literals\n\nimport django.core.validators\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='Course',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=255, unique=True)),\n ],\n ),\n migrations.CreateModel(\n name='Student',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('year_in_school', models.CharField(choices=[(b'FR', b'Freshman'), (b'SO', b'Sophomore'), (b'JR', b'Junior'), (b'SR', b'Senior')], max_length=2)),\n ('age', models.SmallIntegerField(validators=[django.core.validators.MinValueValidator(1), django.core.validators.MaxValueValidator(100)])),\n ('first_name', models.CharField(max_length=50)),\n ('last_name', models.CharField(max_length=50)),\n ('courses', models.ManyToManyField(blank=True, null=True, to='core.Course')),\n ],\n options={\n 'es_mapping': {'properties': {'age': {'type': 'short'}, 'course_names': {'index': 'not_analyzed', 'store': 'yes', 'type': 'string'}, 'first_name': {'index': 'not_analyzed', 'type': 'string'}, 'last_name': {'index': 'not_analyzed', 'type': 'string'}, 'name_complete': {'analyzer': 'simple', 'max_input_length': 50, 'payloads': True, 'preserve_position_increments': True, 'preserve_separators': True, 'type': 'completion'}, 'university': {'properties': {'name': {'index': 'not_analyzed', 'type': 'string'}}, 'type': 'object'}, 'year_in_school': {'type': 'string'}}},\n 'es_index_name': 'django',\n 'es_type_name': 'student',\n },\n ),\n migrations.CreateModel(\n name='University',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=255, unique=True)),\n ],\n ),\n migrations.AddField(\n model_name='student',\n name='university',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='core.University'),\n ),\n ]\n"
}
] | 2 |
sscruz/L1Menu | https://github.com/sscruz/L1Menu | 7c4306045e26e1ae599be2626ef25434f83f57ce | bc7025f5714dad68aa85dca941476ec2d2e97b2b | 2a994c1e8b4b68641d41d373fe4b8a4024bc2940 | refs/heads/master | 2021-01-23T01:41:26.698753 | 2017-03-30T08:07:43 | 2017-03-30T08:07:43 | 85,927,124 | 0 | 1 | null | 2017-03-23T08:49:52 | 2016-11-11T14:19:03 | 2017-03-17T23:40:58 | null | [
{
"alpha_fraction": 0.5039215683937073,
"alphanum_fraction": 0.5263305306434631,
"avg_line_length": 23.452054977416992,
"blob_id": "95f23a4e9995b7bea20532226c11f65dd31a9d92",
"content_id": "12a2ea04895496232715051d5e37cc464c32bf36",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3570,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 146,
"path": "/macros/plot/compareEff.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "from ROOT import *\nimport ROOT\nfrom sys import argv\nimport os\nimport copy\nfrom Config import DualMap\nimport re\nimport matplotlib.pyplot as plt\n\nNORM=False\nLOG=True\n# obj = \"SingleJet\"\n# obj = \"HTT\"\n# obj = \"ETM22\"\n# obj = \"ETM50\"\n# obj = \"HTM\"\nobj = \"SingleMu\"\ndump =[]\n\ngStyle.SetOptStat(False)\nfileNames=[\"../results/r259721_tsgv4plusLayer1_ETM.root\"]\n# gROOT.SetBatch(True)\n\nclass EFFFIT:\n def __call__( self, x, par ):\n value=par[0]/2.+par[0]/2.*ROOT.TMath.Erf((x[0]-par[1])/par[2]);\n return value\n\ndef getall(d, basepath=\"\"):\n \"Generator function to recurse into a ROOT file/dir and yield (path, obj) pairs\"\n for key in d.GetListOfKeys():\n kname = key.GetName()\n if key.IsFolder():\n # TODO: -> \"yield from\" in Py3\n for i in getall(d.Get(kname), basepath+kname+\"/\"):\n yield i\n else:\n yield basepath+kname, d.Get(kname)\n\n\ndef LineInterp(lowbin, highbin, y):\n x0, y0 = lowbin\n x1, y1 = highbin\n return x0 + (y - y0) * (x1 - x0) / (y1-y0)\n\n\ndef Get95Eff(g):\n\n ########## Beginning of LA ############################ \n g.Draw();\n\n gx = [g.GetX()[i] for i in range(g.GetN())]\n gy = [g.GetY()[i] for i in range(g.GetN())]\n # xminf=0.\n # xminf=100.\n for x,y in zip(gx, gy):\n if y >= 0.1:\n xminf = x\n break\n # xminf=40\n xmaxf= gx[-1]\n width=20.\n mean=200.\n\n fitter = TF1(\"fitf\",EFFFIT(),xminf,xmaxf,3);\n fitter.SetParameters(1,mean,width);\n fitter.FixParameter(0,1.0);\n\n fitter.SetLineColor(ROOT.kRed)\n fitter.SetLineStyle(1)\n g.Fit(fitter,\"0RQ\");\n dump.append(fitter)\n\n # print \"Turnon is at 95% for pT = \",fitter.GetX(0.95)\n\n fitter.Draw(\"sames\")\n\n c.Update();\n return fitter.GetX(0.95), fitter\n # raw_input('\\npress return to continue...')\n\n ########## End of LA ############################\n lowbin = None\n highbin = None\n per = 0.8\n gx = [g.GetX()[i] for i in range(g.GetN())]\n gy = [g.GetY()[i] for i in range(g.GetN())]\n # gy = list(g.GetY())\n for x, y in zip(gx, gy):\n if y < per:\n lowbin = (x, y)\n if y >= per and highbin is None:\n highbin = (x, y)\n return LineInterp(lowbin, highbin, per)\n\nif __name__ == \"__main__\":\n try: fileNames=argv[1:]\n except:\n print \"No files specified\"\n exit()\n\n if not os.path.exists(\"plots\"):\n os.mkdir(\"plots\")\n\n files=[]\n for fileName in fileNames:\n files.append(TFile(fileName))\n\n\n c=TCanvas()\n\n l = 0\n x =[]\n y = []\n mg = TMultiGraph()\n\n for k, o in getall(files[0]):\n if \"Eff\" in k and obj in k and type(o)==type(TGraphAsymmErrors()):\n l = l +1\n o.SetLineColor(l)\n o.GetXaxis().SetTitle(\"offline %s [GeV]\" % obj)\n o.GetYaxis().SetTitle(\"Efficiency\")\n # mg.Add(o)\n # continue\n m = re.match(\"Eff/L1_%s(\\d+)_Pt\" % obj, k)\n f95, fit = Get95Eff(o)\n print l, k, f95\n fit.SetLineColor(l)\n if m is not None:\n x.append(m.group(1))\n y.append(f95)\n # fit.Draw()\n\n c.Update()\n # mg.Draw(\"AP\")\n # mg.GetXaxis().SetTitle(\"offline %s [GeV]\" % obj)\n # mg.GetYaxis().SetTitle(\"Efficiency\")\n raw_input('\\npress return to continue...')\n c.SaveAs(\"turnon.png\")\n c.SaveAs(\"turnon.root\")\n\n plt.scatter(x, y)\n plt.xlabel(\"Online %s\" % obj)\n plt.ylabel(\"offline %s with 95%% eff\" % \"ETM\")\n plt.show()\n plt.savefig(\"dia.png\")\n"
},
{
"alpha_fraction": 0.6076045632362366,
"alphanum_fraction": 0.6258555054664612,
"avg_line_length": 18.696969985961914,
"blob_id": "927319cbc13994613aea7d05e45206d77a3d31e7",
"content_id": "78da6368bc6afb987f55ed605db96957397acabe",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 1315,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 66,
"path": "/data/pile_up_rw/genPUReweightinFile.C",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "#include<string>\n#include<iostream>\n\n#include\"TF1.h\"\n#include\"TH1F.h\"\n#include\"TMath.h\"\n#include\"TFile.h\"\n\nTH1F * getPoissonTH1F(double avPU, std::string histoName)\n{\n\n TH1F * histo = new TH1F(histoName.c_str(),histoName.c_str(),101,-0.5,100.5);\n \n int nBins = histo->GetNbinsX();\n \n for (int iBin=1; iBin<nBins; ++iBin) \n {\n float binCenter = histo->GetBinCenter(iBin);\n histo->SetBinContent(iBin,TMath::PoissonI(binCenter,avPU));\n }\n \n return histo;\n\n}\n\nvoid printHisto(TH1F *histo)\n{\n\n std::string hName = histo->GetName();\n float mean = histo->GetMean();\n float rms = histo->GetRMS();\n \n std::cout << \"Histo : \" << hName\n\t << \"\\tmean : \" << mean\n\t << \"\\tRMS^2 : \" << rms*rms\n\t << std::endl;\n\n} \n\nvoid genPUReweightinFile(double origAvPU, double targetAvPU, \n\t\t\t std::string fileName)\n{\n \n TFile * outputFile = new TFile(fileName.c_str(),\"RECREATE\");\n \n outputFile->cd();\n \n TH1F *orig = getPoissonTH1F(origAvPU,\"productionPileUpHisto\"); \n TH1F *target = getPoissonTH1F(targetAvPU,\"targetPileUpHisto\");\n\n printHisto(orig);\n printHisto(target);\n\n TH1F *ratio = static_cast<TH1F*>(orig->Clone(\"ratio\"));\n ratio->Divide(target,orig);\n \n orig->Write();\n target->Write(); \n\n ratio->Write(); \n\n outputFile->Close();\n \n delete outputFile;\n\n}\n\n \n\n \n \n"
},
{
"alpha_fraction": 0.7080191969871521,
"alphanum_fraction": 0.7532556653022766,
"avg_line_length": 34.585365295410156,
"blob_id": "8f59f6f0e22ce222e07037af0a5e3b1c585b5c49",
"content_id": "73ececee9eaf168db90be4462fee0bf8901b7058",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1459,
"license_type": "no_license",
"max_line_length": 141,
"num_lines": 41,
"path": "/test/crab/crab_RECO.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "from WMCore.Configuration import Configuration\n\nconfig = Configuration()\n\nRunOnMC = True\n\nrequestName = 'RECO_Run2015D-v3'\npyCfg = ['runOnMC=False', 'globalTag=74X_dataRun2_Prompt_v1']\ndataset = '/SingleMuon/Run2015D-PromptReco-v3/RECO'\nsplitting = 'LumiBased'\noutput = '/store/group/dpg_trigger/comm_trigger/L1Trigger/Data/Collisions/'\n\nif RunOnMC :\n requestName = 'DY_25ns'\n pyCfg = ['runOnMC=True', 'globalTag=MCRUN2_74_V9']\n dataset = '/DYJetsToLL_M-50_TuneCUETP8M1_13TeV-amcatnloFXFX-pythia8/RunIISpring15DR74-AsymptFlat10to50bx25Raw_MCRUN2_74_V9-v1/AODSIM'\n splitting = 'FileBased'\n output = '/store/group/dpg_trigger/comm_trigger/L1Trigger/efficiency/'\n\nconfig.section_('General')\nconfig.General.transferOutputs = True\nconfig.General.requestName = requestName\nconfig.General.workArea = 'crab_projects'\n\nconfig.section_('JobType')\nconfig.JobType.psetName = '../customL1NtupleFromFevt.py'\nconfig.JobType.pluginName = 'Analysis'\nconfig.JobType.outputFiles = ['L1Tree.root']\nconfig.JobType.pyCfgParams = pyCfg\n\nconfig.section_('Data')\nconfig.Data.inputDataset = dataset\nconfig.Data.inputDBS = 'global'\nif not(RunOnMC) : config.Data.lumiMask = 'Cert_246908-258714_13TeV_PromptReco_Collisions15_25ns_JSON_MuonPhys.txt'\nconfig.Data.splitting = splitting\nconfig.Data.unitsPerJob = 1\nconfig.Data.outLFNDirBase = output\nconfig.Data.useParent = True\n\nconfig.section_('Site')\nconfig.Site.storageSite = 'T2_CH_CERN'\n"
},
{
"alpha_fraction": 0.35136157274246216,
"alphanum_fraction": 0.5370650291442871,
"avg_line_length": 19.330768585205078,
"blob_id": "1f680fd5f4152b810bf06c62812227d0fb0b2164",
"content_id": "efba689aa8605bddfccefc869a4712bd5b8490fc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2644,
"license_type": "no_license",
"max_line_length": 103,
"num_lines": 130,
"path": "/macros/menu/GetLumi.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n\n# File : GetLumi.py\n# Author : Ben Wu\n# Contact : [email protected]\n# Date : 2016 Aug 10\n#\n# Description :\n\nimport subprocess\nimport pandas as pd\nimport sys\nif sys.version_info[0] < 3:\n from StringIO import StringIO\nelse:\n from io import StringIO\n\nrunlist = [\n # 259721,\n # 259626,\n # 258425,\n # 258427,\n # 258428,\n # 258434,\n # 258440,\n # 258445,\n # 258448,\n # 274968,\n # 274969,\n # 274971,\n # 274998,\n # 274999,\n # 275001,\n # 275067,\n # 275066,\n # 275067,\n # 275068,\n # 275073,\n # 275074,\n # 275124,\n # 275125,\n # 276653,\n # 277069,\n # 277194,\n\n # 277216,\n # 277217,\n # 277218,\n # 277219,\n # 277220,\n # 277305,\n # 277420,\n # 278345,\n # 278346,\n # 278349,\n # 278366,\n # 278406,\n # 278509,\n # 278820,\n # 278821,\n # 278822,\n # 278923,\n # 278969,\n # 278975,\n # 278976,\n # 278986,\n\n # 277069,\n # 277070,\n # 277071,\n # 277072,\n # 277076,\n # 277087,\n # 277094,\n # 277096,\n # 277112,\n # 277180,\n # 277194,\n # 277202,\n # 278769,\n # 278770,\n # 278801,\n # 278803,\n # 278808,\n\n\n 279862,\n 279931,\n 279966,\n 279975,\n 279993,\n 279994,\n 279995,\n 280002,\n 280006,\n 280007,\n 280013,\n 280014,\n 280015,\n]\n\ndef Runcmd(run):\n # cmd = \"brilcalc lumi --byls\"\n cmd = \"brilcalc lumi --byls -u '1e30/cm2s' \"\n cmd += \" --output-style csv -b 'STABLE BEAMS' \"\n cmd += \" -r %d \" % run\n testcmd = cmd + \" --normtag /afs/cern.ch/user/l/lumipro/public/normtag_file/normtag_DATACERT.json \"\n pipe = subprocess.Popen(testcmd, shell=True, stdout=subprocess.PIPE)\n out, err = pipe.communicate()\n if len(out) == 221: # Empty output\n pipe = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\n out, err = pipe.communicate()\n Pandas(out)\n\ndef Pandas(file):\n # df = pd.read_csv(file, header=1, skipfooter=3)\n # df = pd.read_csv(StringIO(file), header=1, skipfooter=3)\n df = pd.read_csv(StringIO(file), header=1, skipfooter=3, engine='python')\n df.loc[:,\"run\"] = df[\"#run:fill\"].str.split(':').str[0]\n df.loc[:,\"fill\"] = df[\"#run:fill\"].str.split(':').str[1]\n df.loc[:,\"LS\"] = df[\"ls\"].str.split(':').str[0]\n df2=df[['fill','run','LS', 'avgpu']]\n df2.to_csv('lumi5.csv', mode='a', header=False, index=False)\n # df2.to_csv('run_lumi_old.csv', mode='a', header=False, index=False)\n # df.to_csv('lumi_new.csv', mode='a', header=False, index=False)\n\nif __name__ == \"__main__\":\n for run in runlist:\n Runcmd(run)\n\n"
},
{
"alpha_fraction": 0.5183529257774353,
"alphanum_fraction": 0.5666007995605469,
"avg_line_length": 27.879878997802734,
"blob_id": "341403d337988adf2d54517bd383291ef0dce626",
"content_id": "cb48d27f9dd2a4d85034823b25321a3c32e882c6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9617,
"license_type": "no_license",
"max_line_length": 112,
"num_lines": 333,
"path": "/macros/plot/PU_CSV.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n\n# File : CSV.py\n# Author : Zhenbin Wu\n# Contact : [email protected]\n# Date : 2016 Feb 12\n#\n# Description : \n\n\nimport pandas as pd\nimport numpy as np\nimport glob\nimport math\nimport ROOT\nimport collections\nimport os\nimport re\nimport tdrstyle\nfrom rootpy.interactive import wait\nfrom matplotlib import pyplot as plt\nfrom Config import DualMap, S1S2Map, S2S1Map\n\nfreq = 11245.6\nnBunches = 2736\nunit = \"kHz\"\n# unit = \"Hz\"\n# nBunches = 1\npubins = np.arange(0, 50, 0.2)\npumap = collections.defaultdict(list)\nfiledir =\"Output/MenuPU/*_tsgv4_PU.csv\"\ns1csv = pd.read_csv(\"HLT_Fit_Run258425-260627_Tot10_fit.csv\")\nDrawStage1= False\nmcdf = None\n\ndef GetStage1Fun(l1seed):\n s1seed = l1seed\n if l1seed in S2S1Map:\n s1seed = S2S1Map[l1seed]\n s1df = s1csv.loc[s1csv['path name'] == s1seed]\n if len(s1df) == 0:\n return None\n # if s1df['fit function'] != 'quad':\n # return None\n x0 = s1df.X0\n x1 = s1df.X1\n x2 = s1df.X2\n name = \"S1 = %.2f + %.2f*x + %.2f*x^2\" % (x0, x1, x2)\n fun = \"%f + %f*x + %f*x*x\" % (x0, x1, x2)\n # fun = s1df.X0 + s1\n s1fun = ROOT.TF1(name, fun, 0, 50 )\n return s1fun\n\ndef DrawPU(f, l1seed, key=None):\n df = f[(f.L1Seed == l1seed )]\n RetVar = None\n\n for i in range(0, len(pubins) -1):\n pumap[pubins[i]] = []\n pumap[pubins[i]].append(df[np.logical_and(df.PileUp > pubins[i], df.PileUp <= pubins[i+1])].Fired.sum())\n pumap[pubins[i]].append(df[np.logical_and(df.PileUp > pubins[i], df.PileUp <= pubins[i+1])].Total.sum())\n\n # # No merging\n # PileUp = pd.unique(df.PileUp)\n # for i in PileUp:\n # pumap[i] = []\n # pumap[i].append(df[df.PileUp == i].Fired.sum())\n # pumap[i].append(df[df.PileUp == i].Total.sum())\n\n x = []\n y = []\n yerr = []\n for k, v in pumap.iteritems():\n if v[1] != 0:\n x.append(k)\n if unit == \"Hz\":\n y.append(float(v[0])/v[1] * freq * nBunches )\n yerr.append( math.sqrt(float(v[0]))/v[1] * freq * nBunches )\n if unit == \"kHz\":\n y.append(float(v[0])/v[1] * freq * nBunches / 1000)\n yerr.append( math.sqrt(float(v[0]))/v[1] * freq * nBunches / 1000)\n\n ## Draw the plot\n graph = ROOT.TGraphErrors(len(x))\n minx = min(x)\n maxx = 31\n for i, (xx, yy, yee) in enumerate(zip(x, y, yerr)):\n graph.SetPoint(i, xx, yy)\n graph.SetPointError(i, 0, yee)\n\n c1 = ROOT.TCanvas(\"fd\",\"Fdf\", 600, 500)\n ROOT.gStyle.SetOptStat(000000000)\n tdrstyle.setTDRStyle()\n graph.Draw(\"AP\")\n graph.SetTitle(l1seed)\n graph.GetXaxis().SetTitle(\"PileUp\")\n graph.GetXaxis().SetLimits(0, 50)\n if unit == \"Hz\":\n graph.GetYaxis().SetTitle(\"Rate (nBunches = %d) [Hz]\" % nBunches)\n if unit == \"kHz\":\n graph.GetYaxis().SetTitle(\"Rate (nBunches = %d) [kHz]\" % nBunches)\n\n leg = ROOT.TLegend(0.7432886,0.1733615,0.9949664,0.3530655)\n leg.SetFillColor(0)\n leg.SetBorderSize(0)\n leg.SetBorderSize(0)\n leg.SetFillStyle(0)\n leg.SetTextFont(62)\n leg.AddEntry(graph, \"Data\", \"p\")\n\n ## Get Stage1\n s1fun = GetStage1Fun(l1seed)\n if DrawStage1 and s1fun is not None:\n s1fun.SetLineColor(ROOT.kGreen+2)\n s1fun.SetLineWidth(2)\n s1fun.Draw(\"same\")\n tex = ROOT.TLatex(0.19, 0.81, s1fun.GetName())\n tex.SetNDC()\n tex.SetTextAlign(13)\n tex.SetTextFont(61)\n tex.SetTextSize(0.04)\n tex.SetTextColor(ROOT.kGreen+2)\n tex.SetLineWidth(2)\n tex.Draw()\n\n\n tex = ROOT.TLatex(0.19, 0.9, l1seed)\n tex.SetNDC()\n tex.SetTextAlign(13)\n tex.SetTextFont(61)\n tex.SetTextSize(0.05)\n tex.SetTextColor(ROOT.kBlack)\n tex.SetLineWidth(2)\n tex.Draw()\n ## Pol2\n fitname = \"pol2\"\n graph.Fit(\"pol2\", \"QF\", \"\", minx, maxx)\n f2 = graph.GetFunction(fitname).Clone()\n f2.SetLineColor(ROOT.kBlue)\n f2.SetLineWidth(2)\n fun = \"f2 = %.2f + %.2f*x + %.3f*x^2\" % (f2.GetParameter(0), f2.GetParameter(1), f2.GetParameter(2) )\n RetVar = f2.GetParameter(2) \n tex = ROOT.TLatex(0.19, 0.75, fun)\n f2.Draw(\"same\")\n tex.SetNDC()\n tex.SetTextAlign(13)\n tex.SetTextFont(61)\n tex.SetTextSize(0.04)\n tex.SetTextColor(ROOT.kBlue)\n tex.SetLineWidth(2)\n tex.Draw()\n\n ## Pol1\n fitname = \"pol1\"\n graph.Fit(\"pol1\", \"QF\", \"\", minx, maxx)\n f1 = graph.GetFunction(fitname)\n f1.SetLineColor(ROOT.kRed)\n f1.SetLineWidth(2)\n f1.Draw(\"same\")\n # if l1seed == \"L1APhysics\":\n graph.GetYaxis().SetRangeUser(0, f1.Eval(50))\n fun = \"f1 = %.2f + %.2f*x \" % (f1.GetParameter(0), f1.GetParameter(1))\n tex = ROOT.TLatex(0.19, 0.69, fun)\n tex.SetNDC()\n tex.SetTextAlign(13)\n tex.SetTextFont(61)\n tex.SetTextSize(0.04)\n tex.SetTextColor(ROOT.kRed)\n tex.SetLineWidth(2)\n tex.Draw()\n\n\n if key is not None:\n tex = ROOT.TLatex(0.79, 0.89, key)\n tex.SetNDC()\n tex.SetTextFont(61)\n tex.SetTextSize(0.05)\n tex.SetTextColor(ROOT.kGreen+2)\n tex.SetLineWidth(2)\n tex.Draw()\n\n if mcdf is not None:\n DrawMCPoint(mcdf[ mcdf.L1Seed == l1seed], leg)\n\n c1.SetGridy()\n c1.SetGridx()\n leg.Draw()\n c1.Update()\n # c1.SaveAs(\"plots/PU_%s.root\" % l1seed)\n if key is not None:\n c1.SaveAs(\"plots/PU_%s_%s.png\" % (l1seed, key))\n c1.SaveAs(\"plots/PU_%s_%s.root\" % (l1seed, key))\n else:\n c1.SaveAs(\"plots/PU_%s.png\" % l1seed)\n c1.SaveAs(\"plots/PU_%s.root\" % l1seed)\n # wait()\n return RetVar\n\ndef GetMCDataFrame(allfiles):\n global mcdf\n mcdf = pd.DataFrame()\n mclist = [ ]\n for file_ in allfiles:\n if \"MC\" in file_:\n m = re.match(\".*MC(\\d*)PU.*\", file_)\n if m is not None:\n df_ = pd.read_csv(file_, index_col=None, header=0)\n df_['PileUp'] = m.group(1)\n mclist.append(df_)\n if len(mclist) > 0:\n mcdf = pd.concat(mclist)\n return mcdf\n else:\n return None\n\ndef DrawMCPoint(mcdf, leg=None):\n x = []\n y = []\n yerr = []\n for pu in mcdf.PileUp:\n x.append(float(pu))\n fired = mcdf[mcdf.PileUp==pu].Fired.sum()\n total = mcdf[mcdf.PileUp==pu].Total.sum()\n rate = float(fired)/ total * freq * nBunches\n raterr= math.sqrt(float(fired))/ total * freq * nBunches\n if unit == \"Hz\":\n y.append(rate)\n yerr.append(raterr)\n if unit == \"kHz\":\n y.append(rate/ 1000)\n yerr.append(raterr / 1000)\n\n ## Draw the plot\n graph = ROOT.TGraphErrors(len(x))\n for i, (xx, yy, yee) in enumerate(zip(x, y, yerr)):\n # print i, xx, yy\n graph.SetPoint(i, xx, yy)\n graph.SetPointError(i, 0, yee)\n graph.SetMarkerStyle(32)\n graph.SetMarkerSize(1.8)\n graph.SetMarkerColor(ROOT.kRed)\n graph.Draw(\"P\")\n if leg is not None:\n leg.AddEntry(graph, \"MC\", \"p\")\n\n fitlowx = min(x)\n fithighx= max(x)\n fitname = \"pol2\"\n graph.Fit(\"pol2\", \"QF\", \"\", fitlowx, fithighx)\n f2 = graph.GetFunction(fitname).Clone()\n f2.SetLineColor(ROOT.kOrange+1)\n f2.SetLineWidth(2)\n fun = \"MC = %.2f + %.2f*x + %.2f*x^2\" % (f2.GetParameter(0), f2.GetParameter(1), f2.GetParameter(2) )\n tex = ROOT.TLatex(0.19, 0.62, fun)\n f2.Draw(\"same\")\n tex.SetNDC()\n tex.SetTextAlign(13)\n tex.SetTextFont(61)\n tex.SetTextSize(0.04)\n tex.SetTextColor(ROOT.kOrange+1)\n tex.SetLineWidth(2)\n tex.Draw()\n\ndef DrawPUperFile(filedir, l1seed, key=None):\n global mcdf\n allfiles = glob.glob(filedir)\n if not os.path.exists(\"plots\"):\n os.mkdir(\"plots\")\n\n tdrstyle.setTDRStyle()\n ROOT.gStyle.SetOptStat(000000000)\n df = pd.DataFrame()\n flist = [ ]\n for file_ in allfiles:\n df_ = pd.read_csv(file_, index_col=None, header=0)\n flist.append(df_)\n df = pd.concat(flist)\n mcdf = GetMCDataFrame(allfiles)\n\n if l1seed == \"All\":\n for seed in pd.unique(df.L1Seed):\n DrawPU(df, seed)\n else:\n return DrawPU(df, l1seed, key)\n\ndef DrawMuonPU():\n ermap = {\n # 0.8 : \"MuER0p8\",\n # 1.25: \"MuER1p2\",\n # 1.5: \"MuER1p5\",\n # 1.8: \"MuER1p8\",\n # 2.0: \"MuER2p0\",\n # 2.1: \"MuER2p1\",\n # 2.2: \"MuER2p2\",\n # 2.3: \"MuER2p3\",\n # 2.4: \"MuER2p4\",\n 2.5: \"MuER2p5\",\n }\n l1seeds = [\n # \"L1_SingleMu14er\",\n # \"L1_SingleMu16er\",\n # \"L1_SingleMu18er\",\n \"L1_SingleMu20er\",\n # \"L1_SingleMu22er\",\n # \"L1_SingleMu25er\",\n # \"L1_SingleMu30er\",\n ]\n\n\n l1plts=[]\n for l1 in l1seeds:\n quardmap = dict()\n for k,v in ermap.iteritems():\n # filedir =\"Output/MuonBXAll/r259626_tsgv4_%s_PU.csv\" % v\n filedir =\"Output/MuonBXAll/r*_tsgv4_%s_PU.csv\" % v\n # filedir =\"Output/MuonBX2//r*_tsgv4_%s_PU.csv\" % v\n # filedir =\"Output/TSGv4Study/MuonER/Menu_MuonStudy_r*_tsgv4_%s_PU.csv\" % v\n quardmap[k] = DrawPUperFile(filedir, l1, v)\n # quardmap[k] = abs(DrawPUperFile(filedir, l1))\n # print quardmap\n quardmap = collections.OrderedDict(sorted(quardmap.items()))\n l1plts.append(plt.plot(quardmap.keys(), quardmap.values(), '-o', label=l1))\n # plt.xticks(range(len(quardmap)), quardmap.keys())\n plt.legend(l1seeds, loc=\"lower left\")\n plt.xlabel(\"MuonER\")\n plt.ylabel(\"Fitted Quad Term\")\n # plt.legend(l1seeds, loc=\"upper left\")\n plt.show()\n\nif __name__ == \"__main__\":\n DrawPUperFile(filedir, \"All\")\n # DrawPUperFile(filedir, \"L1APhysics\")\n"
},
{
"alpha_fraction": 0.7415035963058472,
"alphanum_fraction": 0.7651905417442322,
"avg_line_length": 30.322580337524414,
"blob_id": "eae593dd8f2786603bd916bda9de25fcee30a73b",
"content_id": "5f881fd11324bc359203b189047589d03c187408",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 971,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 31,
"path": "/test/crab/crab_NANO.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "from WMCore.Configuration import Configuration\n\nconfig = Configuration()\n\nrequestName = '254790_L1Accept'\npyCfg = ['runOnMC=False', 'globalTag=74X_dataRun2_Prompt_v1']\ndataset = '/L1Accept/Run2015C-v1/RAW'\nsplitting = 'LumiBased'\noutput = '/store/group/dpg_trigger/comm_trigger/L1Trigger/Data/Collisions/'\n\nconfig.section_('General')\nconfig.General.transferOutputs = True\nconfig.General.requestName = requestName\nconfig.General.workArea = 'crab_projects'\n\nconfig.section_('JobType')\nconfig.JobType.psetName = '../customL1NtupleFromNanoDST.py'\nconfig.JobType.pluginName = 'Analysis'\nconfig.JobType.outputFiles = ['L1Tree.root']\nconfig.JobType.pyCfgParams = pyCfg\n\nconfig.section_('Data')\nconfig.Data.inputDataset = dataset\nconfig.Data.inputDBS = 'global'\nconfig.Data.lumiMask = 'run_mask.txt'\nconfig.Data.splitting = splitting\nconfig.Data.unitsPerJob = 25\nconfig.Data.outLFNDirBase = output\n\nconfig.section_('Site')\nconfig.Site.storageSite = 'T2_CH_CERN'\n"
},
{
"alpha_fraction": 0.7002898454666138,
"alphanum_fraction": 0.7397101521492004,
"avg_line_length": 41.07316970825195,
"blob_id": "c497c567d2bc8f53dbdd823f7cfae14c37c960bd",
"content_id": "5c09636436c2f8e10da9b54644f4a2ffdfd6966b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1725,
"license_type": "no_license",
"max_line_length": 224,
"num_lines": 41,
"path": "/test/crab/crab_RAW.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "from WMCore.Configuration import Configuration\n\nconfig = Configuration()\n\nRunOnMC = False\n\nrequestName = '256843_ZeroBias1_ReemulMario'\npyCfg = ['runOnMC=False', 'globalTag=74X_dataRun2_Prompt_v1', 'reEmulation=True', 'patchNtuple=True', 'reEmulCalos=True', 'runOnPostLS1=True', 'useStage1Layer2=True', \"reEmulRCT=True\", 'whichPU=20', 'reEmulMuons=True']\ndataset = '/ZeroBias1/Run2015D-v1/RAW'\nsplitting = 'LumiBased'\noutput = '/store/group/dpg_trigger/comm_trigger/L1Trigger/Data/Collisions/'\n\nif RunOnMC :\n requestName = 'MC_50ns_Flat_for25'\n pyCfg = ['runOnMC=True', 'globalTag=MCRUN2_74_V9A', 'reEmulation=True', 'patchNtuple=True', 'reEmulCalos=True', 'reEmulMuons=True', 'runOnPostLS1=True', 'useStage1Layer2=True', 'whichPU=20', 'reEmulRCT=True']\n dataset = '/SingleNeutrino/RunIISpring15Digi74-Flat_10_50_50ns_tsg_MCRUN2_74_V6-v1/GEN-SIM-RAW'\n splitting = 'FileBased'\n output = '/store/group/dpg_trigger/comm_trigger/L1Trigger/L1Menu2015/'\n\nconfig.section_('General')\nconfig.General.transferOutputs = True\nconfig.General.requestName = requestName\nconfig.General.workArea = 'crab_projects'\n\nconfig.section_('JobType')\nconfig.JobType.psetName = '../customL1NtupleFromRaw.py'\nconfig.JobType.pluginName = 'Analysis'\nconfig.JobType.outputFiles = ['L1Tree.root']\nconfig.JobType.pyCfgParams = pyCfg\nconfig.JobType.inputFiles = ['../../data/Jet_Stage1_2015_v2.txt']\n\nconfig.section_('Data')\nconfig.Data.inputDataset = dataset\nconfig.Data.inputDBS = 'global'\nif not(RunOnMC) : config.Data.lumiMask = 'run_mask.txt'\nconfig.Data.splitting = splitting\nconfig.Data.unitsPerJob = 25\nconfig.Data.outLFNDirBase = output\n\nconfig.section_('Site')\nconfig.Site.storageSite = 'T2_CH_CERN'\n"
},
{
"alpha_fraction": 0.725123405456543,
"alphanum_fraction": 0.7495453357696533,
"avg_line_length": 44.82143020629883,
"blob_id": "3670efba475e4633d098a4971d9bdb591aa9b80e",
"content_id": "e689b23fc7ed1577e9eb64d32457f2a0e51deea0",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3849,
"license_type": "no_license",
"max_line_length": 108,
"num_lines": 84,
"path": "/python/customiseL1Calos_cff.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "import FWCore.ParameterSet.Config as cms\n\ndef updatel1ExtraReEmulTag(process,inputTag):\n\n l1ExtraReEmul = getattr(process,'l1ExtraReEmul') \n\n l1ExtraReEmul.isolatedEmSource = cms.InputTag(inputTag,\"isoEm\")\n l1ExtraReEmul.nonIsolatedEmSource = cms.InputTag(inputTag,\"nonIsoEm\")\n\n l1ExtraReEmul.forwardJetSource = cms.InputTag(inputTag,\"forJets\")\n l1ExtraReEmul.centralJetSource = cms.InputTag(inputTag,\"cenJets\")\n l1ExtraReEmul.tauJetSource = cms.InputTag(inputTag,\"tauJets\")\n l1ExtraReEmul.isoTauJetSource = cms.InputTag(inputTag,\"isoTauJets\")\n \n l1ExtraReEmul.etTotalSource = cms.InputTag(inputTag)\n l1ExtraReEmul.etHadSource = cms.InputTag(inputTag)\n l1ExtraReEmul.etMissSource = cms.InputTag(inputTag)\n l1ExtraReEmul.htMissSource = cms.InputTag(inputTag)\n \n l1ExtraReEmul.hfRingEtSumsSource = cms.InputTag(inputTag)\n l1ExtraReEmul.hfRingBitCountsSource = cms.InputTag(inputTag)\n\ndef updategtReEmulTag(process,inputTag):\n\n getattr(process,'gtReEmulDigis').GctInputTag = cms.InputTag(inputTag)\n getattr(process,'gtReEmulDigis').EmulateBxInEvent = cms.int32(1)\n\ndef updatel1ntupleTag(process,inputTag):\n\n ntuple = getattr(process,'l1NtupleProducer')\n ntuple.gctCentralJetsSource = cms.InputTag(inputTag,\"cenJets\")\n ntuple.gctNonIsoEmSource = cms.InputTag(inputTag,\"nonIsoEm\")\n ntuple.gctForwardJetsSource = cms.InputTag(inputTag,\"forJets\")\n ntuple.gctIsoEmSource = cms.InputTag(inputTag,\"isoEm\")\n ntuple.gctTauJetsSource = cms.InputTag(inputTag,\"tauJets\")\n ntuple.gctIsoTauJetsSource = cms.InputTag(inputTag,\"isoTauJets\")\n ntuple.gctEnergySumsSource = cms.InputTag(inputTag,\"\")\n ntuple.rctSource = cms.InputTag(\"none\")\n\ndef set10GCTtreshold(process):\n\n if hasattr(process,\"gctReEmulDigis\") :\n\n print \"[L1Menu]:\\tCustomising GCT configuration to use 10 GeV jet Seeds\"\n\n process.load(\"L1TriggerConfig.GctConfigProducers.L1GctConfig_cff\")\n process.L1GctConfigProducers.JetFinderCentralJetSeed = 10.0\n process.L1GctConfigProducers.JetFinderForwardJetSeed = 10.0\n process.es_prefer_gct = cms.ESPrefer(\"L1GctConfigProducers\")\n\ndef customiseStage1(process, runOnMC, runOnPostLS1, whichPU ):\n\n if hasattr(process,'reEmulCaloChain') :\n print \"[L1Menu]: Customising calo chain with new L1 Stage1 Emulator\"\n\n process.load('L1Trigger.L1TCalorimeter.L1TCaloStage1_PPFromRaw_cff')\n process.load('L1Trigger/L1TCalorimeter/caloStage1RegionSF_cfi')\n process.caloStage1Params.jetSeedThreshold = 5.0\n from L1Trigger.L1TCalorimeter.caloStage1RegionSF_cfi import regionSubtraction_PU40_MC13TeV\n from L1Trigger.L1TCalorimeter.caloStage1RegionSF_cfi import regionSubtraction_PU20_MC13TeV\n if runOnMC and whichPU == 20 :\n process.caloStage1Params.regionPUSParams = regionSubtraction_PU20_MC13TeV\n\n\n getattr(process,'reEmul').replace(process.reEmulCaloChain, process.L1TCaloStage1_PPFromRaw)\n\n ## unpack stage1 digis as well as gct digis\n from EventFilter.L1TRawToDigi.caloStage1Digis_cfi import caloStage1Digis\n process.caloStage1Digis = caloStage1Digis.clone()\n process.p.replace(process.gctDigis, process.gctDigis + process.caloStage1Digis)\n\n \n l1ExtraReEmul = getattr(process,'l1ExtraReEmul') \n\n updatel1ExtraReEmulTag(process,\"simCaloStage1LegacyFormatDigis\")\n updategtReEmulTag(process,\"simCaloStage1LegacyFormatDigis\")\n\n else :\n print \"[L1Menu]: ERROR: Can't customise calo chain with Stage1 emulator, reEmulCaloChain is missing!\"\n\n if hasattr(process,'l1NtupleProducer') and hasattr(process,'l1ExtraTreeProducer') :\n print \"[L1Menu]:\\tConfiguring Ntuple to use Stage1 emulator information\"\n \n updatel1ntupleTag(process,\"simCaloStage1LegacyFormatDigis\")\n"
},
{
"alpha_fraction": 0.29629629850387573,
"alphanum_fraction": 0.5314815044403076,
"avg_line_length": 26,
"blob_id": "3f1afe4daf744a10d17dd65a8711c351cf5d097e",
"content_id": "4a7e42088ed644feb0a3b4e2214f363e82ca5f46",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1620,
"license_type": "no_license",
"max_line_length": 68,
"num_lines": 60,
"path": "/macros/plot/PUDep.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n\n# File : PUDep.py\n# Author : Ben Wu\n# Contact : [email protected]\n# Date : 2016 Jul 01\n#\n# Description :\n\n\n\ndef Menu7E33(x):\n return 12.63 + 0.54 * x + 0.110 * x*x\n\n\ndef Menu8p5E33(x):\n # return -5.26 + 2.36 * x + 0.028 * x*x\n return -8.20 + 2.53 * x + 0.009 * x*x\n\ndef Menu1E34(x):\n # return -5.31 + 2.20 * x + 0.023 * x*x\n return -3.85 + 1.92 * x + 0.010 * x*x\n\ndef Menu1p15E34(x):\n return -1.70 + 1.46 * x + 0.011 * x*x\n\ndef Menu1p3E34(x):\n return -0.73 + 1.25 * x + 0.009 * x*x\n\ndef Menu1p5E34(x):\n return 2.78 + 0.74 * x + 0.013 * x*x\n\n# def Menu1E34v2(x):\n # # return -6.55 + 2.42 * x + 0.009 * x*x\n # return -2.86 + 1.91 * x + 0.023 * x*x\n\ndef Menu1p1E34(x):\n # return -1.76 + 1.66 * x + 0.016 * x*x\n return -0.35 + 1.41 * x + 0.023 * x*x\n\ndef Menu1p2E34(x):\n return 0.62 + 1.24 * x + 0.022 * x*x\n\n\n# print \"7E33 : %f\" % (Menu7E33(25) / Menu8E33(22.75) * 2064)\n# print \"8.5E33 : %f\" % (Menu8E33(30) / Menu8E33(30.9) * 2064)\nprint \"1E34 : %f\" % (Menu1E34(35) / Menu1E34(30.9) * 2064)\nprint \"1.15E34: %f\" % (Menu1p15E34(40) / Menu1p15E34(30.9) * 2064)\nprint \"1.3E34 : %f\" % (Menu1p3E34(45) / Menu1p3E34(30.9) * 2064)\nprint \"1.5E34 : %f\" % (Menu1p5E34(52) / Menu1p5E34(30.9) * 2064)\n\n# print Menu1E34v2(35)\n# print Menu1E34v2(30.9)\n# print \"1E34 : %f\" % (Menu1E34(35) / Menu1E34(30.9) * 2064)\n# print \"1.15E34 : %f\" % (Menu1E34(40) / Menu1E34(30.9) * 2064)\n# print \"1.3E34 : %f\" % (Menu1E34(45) / Menu1E34(30.9) * 2064)\n\n\n# print \"7E33 : %f\" % (Menu7E33(25) / Menu8E33(22.75) * 1)\n"
},
{
"alpha_fraction": 0.6920374631881714,
"alphanum_fraction": 0.7060890197753906,
"avg_line_length": 43.94736862182617,
"blob_id": "130e14c69811c1082516471607c345db5c4feac7",
"content_id": "dd15148d7e938ca86eef1d19965177d6df69c8cd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 854,
"license_type": "no_license",
"max_line_length": 109,
"num_lines": 19,
"path": "/python/pileUpReweighting_cff.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "import FWCore.ParameterSet.Config as cms\n\ndef pileUpReweighting(process, fileName, origHisto, targetHisto ):\n\n if hasattr(process,'l1NtupleProducer'):\n print \"[L1Menu]: Customising PU reweighting into ntuple with file\" , fileName\n \n ntuple = getattr(process,'l1NtupleProducer')\n ntuple.puMCFile = cms.untracked.string(fileName)\n ntuple.puDataFile = cms.untracked.string(fileName)\n ntuple.puMCHist = cms.untracked.string(origHisto)\n ntuple.puDataHist = cms.untracked.string(targetHisto)\n\n ntuple.useAvgVtx = cms.untracked.bool(False) # for MC reweighting use exact num of PU vertices\n ntuple.maxAllowedWeight = cms.untracked.double(10) # CB 10 for now, wors scaling 40 to 45 only!\n\n\n else :\n print \"[L1Menu]: Ntuple configuration not found. Can't customise PU reweighting!\"\n"
},
{
"alpha_fraction": 0.6098901033401489,
"alphanum_fraction": 0.6730769276618958,
"avg_line_length": 35.400001525878906,
"blob_id": "bcc3a146c7349633bb27fadb59bd21d04a8930c6",
"content_id": "758c38d825d52449535d2b068aa8f63634d83d0a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 364,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 10,
"path": "/macros/runBasicRates.C",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "{\n std::cout << \"L1Ntuple library loading ...\" <<std::endl;\n gROOT->ProcessLine(\".L L1Ntuple.C+\");\n gROOT->ProcessLine(\".L BasicRatePlots.C+\");\n // gROOT->ProcessLine(\".L L1AlgoFactory.h+\");\n\n goRatePlots(\"RUN256843_Stage2\",0,0)\n\n //(\"RUN256843_Stage2\" is the sample identifier, 0=plot rates (1=plot cross sections), 0=number of events to process (0=all))\n}\n"
},
{
"alpha_fraction": 0.6385397911071777,
"alphanum_fraction": 0.6493117809295654,
"avg_line_length": 28.3157901763916,
"blob_id": "5847e6847011dc8089ed39856147cd1898071ca6",
"content_id": "15521685e78f0467d02f6c3cb8b856c4b570ae12",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1671,
"license_type": "no_license",
"max_line_length": 163,
"num_lines": 57,
"path": "/scripts/getL1PrescalesRun1.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "#!/bin/env python\n#\n# Author: Takashi MATSUSHITA\n#\n# Usage:\n# python getL1PrescalesRun1.py --run 262163 --user <database account>\n#\n\nimport argparse\nimport cx_Oracle\n\n\nif __name__ == '__main__':\n run = None\n database = 'cms_omds_lb'\n user = None\n passwd = None\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--run\", dest=\"run\", default=run, type=int, action=\"store\", required=True, help=\"run number to process\")\n parser.add_argument(\"--db\", dest=\"database\", default=database, type=str, action=\"store\", help=\"database connection\")\n parser.add_argument(\"--user\", dest=\"user\", default=user, type=str, action=\"store\", required=True, help=\"database account user name\")\n parser.add_argument(\"--passwd\", dest=\"passwd\", default=passwd, type=str, action=\"store\", help=\"password\")\n\n options = parser.parse_args()\n\n if not options.passwd:\n import getpass\n options.passwd = getpass.getpass()\n\n con = cx_Oracle.connect('%s/%s@%s' % (options.user, options.passwd, options.database))\n cur = con.cursor()\n\n\n menu = {}\n query = \"\"\"select algo_index, alias from cms_gt.gt_run_algo_view where runnumber = %s order by algo_index\"\"\" % options.run\n cur.execute(query)\n rc = cur.fetchall()\n for x in rc:\n menu[x[0]] = x[1]\n\n prescales = {}\n for idx in menu.keys():\n print \"%3d %40s\" % (idx, menu[idx]),\n query = \"\"\"select prescale_index, prescale_factor_algo_%03d from cms_gt.gt_run_presc_algo_view where runnr = %s order by prescale_index\"\"\" % (idx, options.run)\n cur.execute(query)\n rc = cur.fetchall()\n prescales = {}\n for x in rc:\n prescales[x[0]] = x[1]\n\n for k, v in prescales.iteritems():\n print \"%6d\" % v,\n print\n\n# eof\n"
},
{
"alpha_fraction": 0.6265822649002075,
"alphanum_fraction": 0.6329113841056824,
"avg_line_length": 33.34782791137695,
"blob_id": "3a298fea59eef840e07e5965e415b7361ed32d46",
"content_id": "3caa5f67a26331dcb4c1ac21d41f83ec8ea4c0ab",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1580,
"license_type": "no_license",
"max_line_length": 134,
"num_lines": 46,
"path": "/scripts/getRunsByMenu.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "#!/bin/env python\n#\n# Author: Takashi MATSUSHITA\n#\n# Usage:\n# python getRunsByMenu.py --menu menu\n#\n\nimport argparse\nimport cx_Oracle\n\n\nif __name__ == '__main__':\n database = 'cms_omds_lb'\n user = None\n passwd = None\n menu = None\n \n parser = argparse.ArgumentParser()\n parser.add_argument(\"--menu\", dest=\"menu\", default=menu, type=str, action=\"store\", required=True, help=\"menu name\")\n parser.add_argument(\"--db\", dest=\"database\", default=database, type=str, action=\"store\", help=\"database connection\")\n parser.add_argument(\"--user\", dest=\"user\", default=user, type=str, action=\"store\", required=True, help=\"database account user name\")\n parser.add_argument(\"--passwd\", dest=\"passwd\", default=passwd, type=str, action=\"store\", help=\"passwd\")\n options = parser.parse_args()\n \n if not options.passwd:\n import getpass\n options.passwd = getpass.getpass()\n \n con = cx_Oracle.connect('%s/%s@%s' % (options.user, options.passwd, options.database))\n cur = con.cursor()\n \n query = \"\"\"select wbm.lhcfill, wbm.runnumber, wbm.gtkey, conf.id, menu.l1_menu\n from cms_wbm.runsummary wbm\n join cms_trg_l1_conf.l1_trg_conf_keys conf on wbm.tsckey in conf.id\n join cms_trg_l1_conf.ugt_keys menu on (conf.ugt_key in menu.id)\n where conf.id like 'collisions' || '%%' and menu.l1_menu like '%s' || '%%' order by wbm.runnumber\"\"\" % options.menu\n cur.execute(query)\n rc = cur.fetchall()\n print 'Run # for %s' % options.menu\n for x in rc:\n if x[0]:\n print ' ', x[1], 'with menu:', x[4], \" (\", x[2], \",\", x[3], \")\"\n print\n\n# eof\n"
},
{
"alpha_fraction": 0.5616500377655029,
"alphanum_fraction": 0.6143962740898132,
"avg_line_length": 30.61282730102539,
"blob_id": "32c592e5b5f1c98e7e99f5db8fd51b1233212c63",
"content_id": "569ad35caf45f175024d55a5a8ea1087b4e6069e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 13309,
"license_type": "no_license",
"max_line_length": 226,
"num_lines": 421,
"path": "/test/analyze_L1.C",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "// dPhi / dEta rectangle definition \n// for GMT - RECO matching\n#define MAX_MU_GMT_DPHI .2\n#define MAX_MU_GMT_DETA .5\n\nconst float MuPtBins[26] = {0., 3., 4., 5., 6., 7., 8., 10., 12., 14., 16., 18., 20., 25., 30., 35., 40., 45., 50., 60., 70., 80., 90., 100., 120., 140.};\n\n#include \"L1Ntuple.h\"\n#include \"TriggeredMuon.C\"\n\n#include \"TROOT.h\"\n#include \"TH1F.h\"\n#include \"TProfile.h\"\n#include \"TStyle.h\"\n\nclass analyze_L1 : public L1Ntuple {\n\npublic :\n\n analyze_L1(Bool_t isReco)\n {\n _isReco = isReco;\n }\n ~analyze_L1() {}\n\n void Loop();\n float binRecoMuPt(float theMuPt);\n\nprivate :\n\n Bool_t _isReco;\n\n};\n\nfloat analyze_L1::binRecoMuPt(float theMuPt){\n float binnedpt = -999.;\n\n if(theMuPt < 8.) binnedpt = trunc(theMuPt);\n else if(theMuPt < 10.) binnedpt = 8.;\n else if(theMuPt < 12.) binnedpt = 10.;\n else if(theMuPt < 14.) binnedpt = 12.;\n else if(theMuPt < 16.) binnedpt = 14.;\n else if(theMuPt < 18.) binnedpt = 16.;\n else if(theMuPt < 20.) binnedpt = 18.;\n else if(theMuPt < 25.) binnedpt = 20.;\n else if(theMuPt < 30.) binnedpt = 25.;\n else if(theMuPt < 35.) binnedpt = 30.;\n else if(theMuPt < 40.) binnedpt = 35.;\n else if(theMuPt < 45.) binnedpt = 40.;\n else if(theMuPt < 50.) binnedpt = 45.;\n else if(theMuPt < 60.) binnedpt = 50.;\n else if(theMuPt < 70.) binnedpt = 60.;\n else if(theMuPt < 80.) binnedpt = 70.;\n else if(theMuPt < 90.) binnedpt = 80.;\n else if(theMuPt < 100.) binnedpt = 90.;\n else if(theMuPt < 120.) binnedpt = 100.;\n else if(theMuPt < 140.) binnedpt = 120.;\n else binnedpt = 140.;\n\n return binnedpt;\n}\n\n\nvoid analyze_L1::Loop(){\n\n Int_t nevents = GetEntries();\n std::cout << \"Running on \" << nevents << \" events.\" << std::endl;\n if(nevents > 2000000) nevents = 2000000;\n\n TH1F hTT11bx(\"hTT11bx\",\"hTT11bx\",7,-3.5,3.5);\n\n TH1F hDTTFbx(\"hDTTFbx\",\"hDTTFbx\",7,-3.5,3.5);\n TH1F hCSCTFbx(\"hCSCTFbx\",\"hCSCTFbx\",7,-3.5,3.5);\n TH1F hRPCbbx(\"hRPCbbx\",\"hRPCbbx\",7,-3.5,3.5);\n TH1F hRPCfbx(\"hRPCfbx\",\"hRPCfbx\",7,-3.5,3.5);\n TH1F hGMTbx(\"hGMTbx\",\"hGMTbx\",7,-3.5,3.5);\n\n TH1F hGMTpt(\"hGMTpt\",\"hGMTpt\",100,0.,100.);\n TH1F hGMTeta(\"hGMTeta\",\"hGMTeta\",30,-2.5,2.5);\n TH1F hGMTphi(\"hGMTphi\",\"hGMTphi\",30,0.,6.3);\n\n TH1F hGMT2mubx(\"hGMT2mubx\",\"hGMT2mubx\",7,-3.5,3.5);\n TH1F hGMT2mupt(\"hGMT2mupt\",\"hGMT2mupt\",100,0.,100.);\n TH1F hGMT2muphi(\"hGMT2muphi\",\"hGMT2muphi\",30,0.,6.3);\n TH1F hGMT2mueta(\"hGMT2mueta\",\"hGMT2mueta\",30,-2.5,2.5);\n TH1F hGMT2mu1BX(\"hGMT2mu1BX\",\"hGMT2mu1BX\",7,-3.5,3.5);\n\n TH2F hDTRPCBX(\"hDTRPCBX\",\"hDTRPCBX\",7,-3.5,3.5,7,-3.5,3.5);\n TH2F hCSCRPCBX(\"hCSCRPCBX\",\"hCSCRPCBX\",7,-3.5,3.5,7,-3.5,3.5);\n TH2F hDTCSCBX(\"hDTCSCBX\",\"hDTCSCBX\",7,-3.5,3.5,7,-3.5,3.5);\n\n TH1F hpTresidual(\"hpTresidual\",\"hpTresidual\",100.,-10.,10.);\n TProfile hpTresidual_r(\"hpTresidual_r\",\"hpTresidual_r\",30.,0.,50.);\n TProfile hpTresidual_z(\"hpTresidual_z\",\"hpTresidual_z\",30.,-50.,50.);\n TProfile hpTresidual_eta(\"hpTresidual_eta\",\"hpTresidual_eta\",30.,-2.5,2.5);\n\n TH1F hRecoMupT(\"hRecoMupT\",\"hRecoMupT\",100.,0.,100.);\n TH1F hRecoMuBinpT(\"hRecoMuBinpT\",\"hRecoMuBinpT\",25,MuPtBins);\n TH1F hGMTMuBinpT(\"hGMTMuBinpT\",\"hGMTMuBinpT\",25,MuPtBins);\n TH2F hRecoMuGMTpT(\"hRecoMuGMTpT\",\"hRecoMuGMTpT\",25,MuPtBins,25,MuPtBins);\n\n for (Long64_t event=0; event<nevents; event++)\n { \n Long64_t ientry = LoadTree(event); if (ientry < 0) break;\n GetEntry(event);\n\n if (event%200000 == 0) {\n\tstd::cout << \"Processed \" << event << \" events.\" << std::endl;\n }\n\n //select events by technical trigger bit 11 - HO\n //Int_t Bit11 = (gt_->tt[2]>>11)&1;\n //if(Bit11 != 1) continue;\n\n Int_t Ndt = gmt_->Ndt;\n Int_t Ncsc = gmt_->Ncsc;\n Int_t Nrpcb = gmt_->Nrpcb;\n Int_t Nrpcf = gmt_->Nrpcf;\n Int_t Nmu = gmt_->N;\n\n if(_isReco){\n\tfor(int iMu=0;iMu<recoMuon_->nMuons;iMu++){\n\t if(recoMuon_->type.at(iMu) != 0) continue;\n\t if(recoMuon_->pt[iMu] < 3.) continue;\n\t bool isDisplaced = false;\n\t if( fabs(recoMuon_->tr_imp_point_z[iMu]) > 20. || sqrt( pow(recoMuon_->tr_imp_point_x[iMu],2.) + pow(recoMuon_->tr_imp_point_y[iMu],2) ) > 10.) isDisplaced = true;\n\n\t for (int iGMTmu=0; iGMTmu < Nmu; iGMTmu++){\n\t TriggeredMuon trigMuons(recoMuon_,iMu,gmt_,iGMTmu);\n\t if(!trigMuons.hasTriggerMatch() || !trigMuons.hasGmtBX0()) continue;\n\n\t float iMu_binnedpt = binRecoMuPt(recoMuon_->pt[iMu]);\n\t float theresidual = (iMu_binnedpt - gmt_->Pt[iGMTmu]) / iMu_binnedpt;\n\n\t if(!isDisplaced) hpTresidual.Fill(theresidual);\n\t hpTresidual_r.Fill(sqrt( pow(recoMuon_->tr_imp_point_x[iMu],2.) + pow(recoMuon_->tr_imp_point_y[iMu],2) ), theresidual);\n\t hpTresidual_z.Fill(recoMuon_->tr_imp_point_z[iMu] , theresidual);\n\t if(!isDisplaced) hpTresidual_eta.Fill(recoMuon_->eta[iMu] , theresidual);\n\n\t hRecoMupT.Fill(recoMuon_->pt[iMu]);\n\t if(iMu_binnedpt < 140. && gmt_->Pt[iGMTmu] < 140. && !isDisplaced){\n\t hRecoMuBinpT.Fill(iMu_binnedpt);\n\t hGMTMuBinpT.Fill(gmt_->Pt[iGMTmu]);\n\t hRecoMuGMTpT.Fill(iMu_binnedpt,gmt_->Pt[iGMTmu]);\n\t }\n\n\t if( fabs((iMu_binnedpt - gmt_->Pt[iGMTmu]) / iMu_binnedpt) > 3. && !isDisplaced){\n\t cout << \"###################\" << endl;\n\t cout << \"GMT pt = \" << gmt_->Pt[iGMTmu] << endl;\n\t cout << \"GMT quality = \" << gmt_->Qual[iGMTmu] << endl;\n\t cout << \"mu pt = \" << recoMuon_->pt[iMu] << endl;\n\t cout << \"binned mu pt = \" << iMu_binnedpt << endl;\n\t cout << \"Mu phi = \" << recoMuon_->phi[iMu] << endl;\n\t cout << \"Mu eta = \" << recoMuon_->eta[iMu] << endl;\n\t cout << \"Mu charge = \" << recoMuon_->ch[iMu] << endl;\n\t cout << \"Mu x = \" << recoMuon_->tr_imp_point_x[iMu] << endl;\n\t cout << \"Mu y = \" << recoMuon_->tr_imp_point_y[iMu] << endl;\n\t cout << \"Mu z = \" << recoMuon_->tr_imp_point_z[iMu] << endl;\n\t cout << \"Mu ch2 = \" << recoMuon_->tr_normchi2[iMu] << endl;\n\t cout << \"Mu ntrhits = \" << recoMuon_->tr_validhits[iMu] << endl;\n\t cout << \"Mu npixhits = \" << recoMuon_->tr_validpixhits[iMu] << endl;\n\t cout << \"N reco Mu = \" << recoMuon_->nMuons << endl;\n\t cout << \"N GMT Mu = \" << Nmu << endl;\n\t cout << \"Run number = \" << event_->run << endl;\n\t cout << \"Event number = \" << event_->event << endl;\n\t cout << \"###################\" << endl;\n\t }\n\n\n\t }\n\t}\n }\n\n for(int i11=0;i11<5;i11++){\n\tif( (gt_->tt[i11-2]>>11)&1 ) hTT11bx.Fill(i11-2.);\n }\n\n for (int idt=0; idt < Ndt; idt++){\n\tint bx = gmt_ -> Bxdt[idt];\n\thDTTFbx.Fill(bx);\n }\n \n for (int icsc=0; icsc < Ncsc; icsc++){\n\tint bx = gmt_ -> Bxcsc[icsc];\n\thCSCTFbx.Fill(bx);\n }\n\n for (int irpcb=0; irpcb < Nrpcb; irpcb++){\n\tint bx = gmt_ -> Bxrpcb[irpcb];\n\thRPCbbx.Fill(bx);\n }\n\n for (int irpcf=0; irpcf < Nrpcf; irpcf++){\n\tint bx = gmt_ -> Bxrpcf[irpcf];\n\thRPCfbx.Fill(bx);\n }\n \n for (int imu=0; imu < Nmu; imu++){\n\tint bx = gmt_->CandBx[imu];\n\tfloat ptmu = gmt_->Pt[imu];\n\tfloat etamu = gmt_->Eta[imu];\n\tfloat phimu = gmt_->Phi[imu];\n\n\thGMTbx.Fill(bx);\n\thGMTpt.Fill(ptmu);\n\thGMTeta.Fill(etamu);\n\thGMTphi.Fill(phimu);\n }\n\n if(Nmu > 1 && fabs((gmt_->Pt[0]-gmt_->Pt[1])/gmt_->Pt[0]) < 0.05 && fabs((gmt_->Eta[0]-gmt_->Eta[1])/gmt_->Eta[0]) < 0.1 ){\n\thGMT2mubx.Fill(gmt_->CandBx[0] - gmt_->CandBx[1]);\n\thGMT2mupt.Fill(gmt_->Pt[0]);\n\thGMT2muphi.Fill(gmt_->Phi[0]);\n\thGMT2mueta.Fill(gmt_->Eta[0]);\n\tif(gmt_->CandBx[0] <= gmt_->CandBx[1]) hGMT2mu1BX.Fill(gmt_->CandBx[0]);\n\telse if(gmt_->CandBx[0] > gmt_->CandBx[1]) hGMT2mu1BX.Fill(gmt_->CandBx[1]);\n }\n\n if(Ndt > 0 && Nrpcb > 0) hDTRPCBX.Fill(gmt_->Bxdt[0],gmt_->Bxrpcb[0]);\n if(Ncsc > 0 && Nrpcf > 0) hCSCRPCBX.Fill(gmt_->Bxcsc[0],gmt_->Bxrpcf[0]);\n if(Ndt > 0 && Ncsc > 0) hDTCSCBX.Fill(gmt_->Bxdt[0],gmt_->Bxcsc[0]);\n }\n\n //Aestethics\n hTT11bx.SetTitle(\"\");\n\n hDTTFbx.SetTitle(\"\");\n hCSCTFbx.SetTitle(\"\");\n hRPCbbx.SetTitle(\"\");\n hRPCfbx.SetTitle(\"\");\n hGMTbx.SetTitle(\"\");\n\n hGMTpt.SetTitle(\"\");\n hGMTeta.SetTitle(\"\");\n hGMTphi.SetTitle(\"\");\n\n hGMT2mubx.SetTitle(\"\");\n hGMT2mupt.SetTitle(\"\");\n hGMT2muphi.SetTitle(\"\");\n hGMT2mueta.SetTitle(\"\");\n hGMT2mu1BX.SetTitle(\"\");\n\n hDTRPCBX.SetTitle(\"\");\n hCSCRPCBX.SetTitle(\"\");\n hDTCSCBX.SetTitle(\"\");\n\n hpTresidual.SetTitle(\"\");\n hpTresidual_r.SetTitle(\"\");\n hpTresidual_z.SetTitle(\"\");\n hpTresidual_eta.SetTitle(\"\");\n hRecoMupT.SetTitle(\"\");\n hRecoMuBinpT.SetTitle(\"\");\n hGMTMuBinpT.SetTitle(\"\");\n hRecoMuGMTpT.SetTitle(\"\");\n\n hTT11bx.GetXaxis()->SetTitle(\"TT11 BX\");\n\n hDTTFbx.GetXaxis()->SetTitle(\"DTTF BX\");\n hCSCTFbx.GetXaxis()->SetTitle(\"CSCTF BX\");\n hRPCbbx.GetXaxis()->SetTitle(\"RPCb BX\");\n hRPCfbx.GetXaxis()->SetTitle(\"RPCf BX\");\n hGMTbx.GetXaxis()->SetTitle(\"GMT BX\");\n\n hGMTpt.GetXaxis()->SetTitle(\"L1 Muon #p_{T} [GeV]\");\n hGMTeta.GetXaxis()->SetTitle(\"L1 Muon #eta\");\n hGMTphi.GetXaxis()->SetTitle(\"L1 Muon #phi\");\n\n hGMT2mubx.GetXaxis()->SetTitle(\"#Delta_{BX} for identical muons\");\n hGMT2mupt.GetXaxis()->SetTitle(\"p_{T} for identical muons\");\n hGMT2muphi.GetXaxis()->SetTitle(\"#phi for identical muons\");\n hGMT2mueta.GetXaxis()->SetTitle(\"#eta for identical muons\");\n hGMT2mu1BX.GetXaxis()->SetTitle(\"BX for first muon for identical muons\");\n\n hDTRPCBX.GetXaxis()->SetTitle(\"DT BX\");\n hCSCRPCBX.GetXaxis()->SetTitle(\"CSC BX\");\n hDTCSCBX.GetXaxis()->SetTitle(\"DT BX\");\n\n hpTresidual.GetXaxis()->SetTitle(\"#Delta p_{T} / p_{T}\");\n hpTresidual_r.GetXaxis()->SetTitle(\"Radius on transverse plane (cm)\");\n hpTresidual_z.GetXaxis()->SetTitle(\"Distance on z (cm)\");\n hpTresidual_eta.GetXaxis()->SetTitle(\"#eta\");\n hRecoMupT.GetXaxis()->SetTitle(\"Reco Muon p_{T}\");\n hRecoMuBinpT.GetXaxis()->SetTitle(\"Muon p_{T}\");\n hGMTMuBinpT.GetXaxis()->SetTitle(\"Muon p_{T}\");\n hRecoMuGMTpT.GetXaxis()->SetTitle(\"Reco Muon p_{T}\");\n\n hDTRPCBX.GetYaxis()->SetTitle(\"RPC BX\");\n hCSCRPCBX.GetYaxis()->SetTitle(\"RPC BX\");\n hDTCSCBX.GetYaxis()->SetTitle(\"CSC BX\");\n\n hpTresidual_r.GetYaxis()->SetTitle(\"Average #Delta p_{T} / p_{T}\");\n hpTresidual_z.GetYaxis()->SetTitle(\"Average #Delta p_{T} / p_{T}\");\n hpTresidual_eta.GetYaxis()->SetTitle(\"Average #Delta p_{T} / p_{T}\");\n hRecoMuGMTpT.GetYaxis()->SetTitle(\"GMT Muon p_{T}\");\n\n hGMTMuBinpT.SetLineColor(kRed);\n hRecoMuBinpT.SetLineWidth(2);\n hGMTMuBinpT.SetLineWidth(2);\n\n TCanvas c0;\n c0.cd(); hTT11bx.Draw();\n c0.SaveAs(\"results/c0.gif\");\n\n TCanvas c1;\n c1.Divide(2,2);\n c1.cd(1); hDTTFbx.Draw();\n c1.cd(2); hCSCTFbx.Draw();\n c1.cd(3); hRPCbbx.Draw();\n c1.cd(4); hRPCfbx.Draw();\n c1.SaveAs(\"results/c1.gif\");\n\n TCanvas c2;\n c2.Divide(2,2);\n c2.cd(1); hGMTbx.Draw();\n c2.cd(2); hGMTpt.Draw();\n c2.cd(3); hGMTeta.Draw();\n c2.cd(4); hGMTphi.Draw();\n c2.SaveAs(\"results/c2.gif\");\n\n TCanvas c3;\n c3.Divide(2,2);\n c3.cd(1); hGMT2mubx.Draw();\n c3.cd(2); hGMT2mupt.Draw();\n c3.cd(3); hGMT2mueta.Draw();\n c3.cd(4); hGMT2muphi.Draw();\n c3.SaveAs(\"results/c3.gif\");\n\n TCanvas c4;\n c4.cd(); hGMT2mu1BX.Draw();\n c4.SaveAs(\"results/c4.gif\");\n\n TCanvas c5;\n c5.Divide(2,2);\n c5.cd(1); hDTRPCBX.Draw(\"COLZ\");\n c5.cd(2); hCSCRPCBX.Draw(\"COLZ\");\n c5.cd(3); hDTCSCBX.Draw(\"COLZ\");\n c5.SaveAs(\"results/c5.gif\");\n\n if(_isReco){\n\n TCanvas c6;\n c6.cd();\n hpTresidual.Draw();\n c6.SaveAs(\"results/c6.gif\");\n\n gStyle->SetOptStat(0);\n\n TCanvas c7;\n c7.cd();\n hRecoMupT.Draw();\n c7.SaveAs(\"results/c7.gif\");\n\n TCanvas c8(\"c8\",\"c8\",1200,1200);\n c8.cd();\n c8.SetLogx(true);\n c8.SetLogy(true);\n hRecoMuGMTpT.Draw(\"COLZ\");\n c8.SaveAs(\"results/c8.gif\");\n\n TCanvas c9;\n c9.cd();\n hGMTMuBinpT.Draw(\"E\");\n hRecoMuBinpT.Draw(\"ESAME\");\n c9.SaveAs(\"results/c9.gif\");\n\n TCanvas c10;\n c10.Divide(2,1);\n c10.cd(1);\n hpTresidual_r.Draw();\n c10.cd(2);\n hpTresidual_z.Draw();\n c10.SaveAs(\"results/c10.gif\");\n\n TCanvas c11;\n c11.cd();\n hpTresidual_eta.Draw();\n c11.SaveAs(\"results/c11.gif\");\n }\n\n return;\n}\n\nvoid RunL1(Int_t whichFileAndLumiToUse=1){\n\n std::string L1NtupleFileName = \"\";\n\n Bool_t isReco = false;\n\n if(whichFileAndLumiToUse==1){\n L1NtupleFileName = \"root://lxcms02//data2/p/pellicci/L1DPG/root/Data/Cosmics/229713_MinimumBias/L1Tree.root\";\n }\n else if(whichFileAndLumiToUse==2){\n L1NtupleFileName = \"root://lxcms02//data2/p/pellicci/L1DPG/root/Data/Cosmics/229713_Cosmics/L1Tree.root\";\n }\n else if(whichFileAndLumiToUse==3){\n L1NtupleFileName = \"root://lxcms02//data2/p/pellicci/L1DPG/root/Data/Cosmics/232956_Cosmics/L1Tree.root\";\n }\n else if(whichFileAndLumiToUse==4){\n L1NtupleFileName = \"root://lxcms02//data2/p/pellicci/L1DPG/root/Data/Cosmics/233238_Cosmics/L1Tree.root\";\n }\n else if(whichFileAndLumiToUse==5){\n L1NtupleFileName = \"file:///data2/p/pellicci/L1DPG/root/Data/Cosmics/238492_CosmicsSP/L1Tree.root\";\n isReco = true;\n }\n else if(whichFileAndLumiToUse==6){\n L1NtupleFileName = \"file:///data2/p/pellicci/L1DPG/root/Data/Cosmics/Full_SP_310315/L1Tree.root\";\n isReco = true;\n }\n else if(whichFileAndLumiToUse==7){\n L1NtupleFileName = \"root://lxcms02//data2/p/pellicci/L1DPG/root/Data/Collisions/256843_ZeroBias.root\";\n }\n else{\n std::cout << std::endl << \"ERROR: Please define a ntuple file which is in the allowed range! You did use: whichFileAndLumiToUse = \" << whichFileAndLumiToUse << \" This is not in the allowed range\" << std::endl << std::endl;\n }\n\n analyze_L1 a(isReco);\n a.Open(L1NtupleFileName);\n a.Loop();\n\n return;\n}\n"
},
{
"alpha_fraction": 0.5345016121864319,
"alphanum_fraction": 0.592392086982727,
"avg_line_length": 34.38823699951172,
"blob_id": "cccd81dc948cf7f0a6f1fa1f49489ace84b01875",
"content_id": "72ec8eed2edfbd80c98f826b05fcd0bbef745b51",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 21057,
"license_type": "no_license",
"max_line_length": 163,
"num_lines": 595,
"path": "/macros/BasicRatePlots.C",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "#include \"L1Ntuple.h\"\n#include \"L1AlgoFactory.h\"\n#include <algorithm>\n#include<map>\n#include<iostream>\n\n#include \"TH1F.h\"\n#include \"TH2F.h\"\n\nclass BasicRatePlots : public L1AlgoFactory\n{\npublic :\n \n //constructor \n BasicRatePlots(std::string filename){\n if (filename.find(\".root\") != std::string::npos) {\n std::cout << \"Reading RootFile: \" << filename << std::endl;\n L1Ntuple::Open(filename);\n }else{\n std::cout << \"Reading Filelist: \" << filename << std::endl;\n if (! L1Ntuple::OpenWithList(filename)) exit(0);\n }\n }\n ~BasicRatePlots() {}\n \n void run(bool runOnData, std::string resultTag, float crossSec, int nBunches, int isCrossSec, int nEvents = 0);\n\nprivate :\n \n float ScaleFactor(float nZeroBias, float nBunches);\n //void SingleJetPt(Float_t& ptcut, Bool_t isCentral = false);\n float SingleMuEta(float eta);\n //void SingleEGPt(Float_t& ptcut, Bool_t isIsolated, Bool_t isER);\n float SingleEGEta(float ptCut, bool doIso);\n float SingleJetEta(float pt, Int_t accept_flag = 0);\n\n void setRateError(TH1F* histo);\n \n //void ETMVal(Float_t& ETMcut);\n //void HTTVal(Float_t& HTTcut);\n //void HTMVal(Float_t& HTMcut);\n //void ETTVal(Float_t& ETTcut);\n \n std::map<std::string,TH1F*> hTH1F;\n std::map<std::string,TH2F*> hTH2F;\n};\n\n// ------------------------------------------------------------------\n// BasicRatePlots::BasicRatePlots(TTree *tree) : L1AlgoFactory(tree) {}\n\n// scale factor computed w.r.t. ZeroBias rate fratcion and # bunches \nfloat BasicRatePlots::ScaleFactor(float nZeroBias, float nBunches) {\n\n float scal = 11246.; // ZB per bunch in Hz\n scal /= nZeroBias;\n scal *= nBunches;\n\n return scal;\n}\n\nfloat BasicRatePlots::SingleMuEta(float ptCut ) {\n\n float maxPt = -10;\n float iMuMaxPt = -10;\n\n UInt_t nMuons = upgrade_ -> nMuons;\n for (UInt_t imu=0; imu < nMuons; imu++) \n {\n Int_t bx = upgrade_ -> muonBx.at(imu);\n if(bx != 0) continue;\n Float_t pt = upgrade_ -> muonEt.at(imu); \n if ( pt > maxPt) \n\t{\n\t maxPt = pt;\n\t iMuMaxPt = imu;\n\t}\n }\n \n float eta = maxPt>ptCut ? upgrade_ -> muonEta.at(iMuMaxPt) : -10.; \n\n //cout << \"max mu pt = \" << maxPt << \" max eta = \" << eta << endl;\n\n return eta;\n}\n\n\n\nfloat BasicRatePlots::SingleEGEta(float ptCut, bool doIso) {\n\n float maxPt = -10;\n float iEGMaxPt = -10;\n\n for (UInt_t ue=0; ue < upgrade_ -> nEGs; ue++) {\n Int_t bx = upgrade_ -> egBx.at(ue); \t\t\n if (bx != 0) continue;\n Bool_t iso = upgrade_ -> egIso.at(ue);\n if (!iso && doIso) continue;\n Float_t pt = upgrade_ -> egEt.at(ue);\n if ( pt >= maxPt) \n {\n\tmaxPt = pt;\n\tiEGMaxPt = ue;\n }\n }\n\n return iEGMaxPt>=0 && maxPt>ptCut ? upgrade_ -> egEta.at(iEGMaxPt) : -10.; \n}\n\n//void BasicRatePlots::SingleEGPt(Float_t& cut, Bool_t isIsolated , Bool_t isER) {\n\n \n ////if(nEGs < 1) return;\n\n //Float_t ptmax = -10.;\n\n //for(UInt_t ue=0; ue < upgrade_ -> nEGs; ue++) {\n //Int_t bx = upgrade_ -> egBx.at(ue); \n //if(bx != 0) continue;\n //if(isIsolated && !(upgrade_ -> egIso.at(ue))) continue;\n //Float_t eta = upgrade_ -> egEta.at(ue);\n //if(fabs(eta) > 2.1 && isER) continue; // eta = 5 - 16\n\n //Float_t pt = upgrade_ -> egEt.at(ue); // the rank of the electron\n //if(pt >= ptmax) ptmax = pt;\n //}\n\n //cut = ptmax;\n\n //return;\n//}\n\n//void BasicRatePlots::SingleJetPt(Float_t& cut, Bool_t isCentral) {\n\n //Float_t ptmax = -10.;\n //Int_t Nj = upgrade_ -> nJets ;\n //for(Int_t ue=0; ue < Nj; ue++) {\n //Int_t bx = upgrade_ -> jetBx.at(ue);\n //if(bx != 0) continue;\n //Bool_t isFwdJet = fabs(upgrade_ -> jetEta.at(ue)) > 3. ? true : false;\n //if(isCentral && isFwdJet) continue;\n ////if(NOTauInJets && upgrade_->Taujet[ue]) continue;\n ////if(isCentral && noHF && (upgrade_->jetEta.at(ue) < 5 || upgrade_->jetEta.at(ue) > 17)) continue;\n\n //Float_t pt = upgrade_ -> jetEt.at(ue);\n //if(pt >= ptmax) ptmax = pt;\n //}\n\n //cut = ptmax;\n //return;\n//}\n\nfloat BasicRatePlots::SingleJetEta(float ptCut, Int_t accept_flag) {\n\n float maxPt = -10;\n float iJetMaxPt = -10;\n \n for(UInt_t ue=0; ue < upgrade_ -> nJets; ue++) {\n Int_t bx = upgrade_ -> jetBx.at(ue); \t\t\n if(bx != 0) continue;\n Bool_t isFwdJet = fabs(upgrade_ -> jetEta.at(ue)) > 3. ? true : false;\n\n if(accept_flag == 1 && isFwdJet) continue;\n if(accept_flag == 2 && !isFwdJet) continue;\n\n Float_t pt = upgrade_ -> jetEt.at(ue);\n if(pt >= maxPt){\n maxPt = pt;\n iJetMaxPt = ue;\n }\n }\n\n return iJetMaxPt>=0 && maxPt>ptCut ? upgrade_ -> jetEta.at(iJetMaxPt) : -10.;\n}\n\n//void BasicRatePlots::ETMVal(Float_t& ETMcut ) {\n\n //Float_t TheETM = -10;\n //if(upgrade_ ->sumBx[2]==0) TheETM =upgrade_ ->sumEt[2];\n //ETMcut = TheETM;\n //return;\n//}\n\n//void BasicRatePlots::HTTVal(Float_t& HTTcut) {\n\n //Float_t TheHTT = -10;\n //if(upgrade_ ->sumBx[1]==0) TheHTT =upgrade_ ->sumEt[1];\n //HTTcut = TheHTT;\n //return;\n//}\n\n//void BasicRatePlots::HTMVal(Float_t& HTMcut) {\n\n //Float_t TheHTM = -10;\n //if (upgrade_ ->sumBx[3]==0) TheHTM = upgrade_ ->sumEt[3];\n //HTMcut = TheHTM;\n //return;\n//}\n\n//void BasicRatePlots::ETTVal(Float_t& ETTcut) {\n\n //Float_t TheETT = -10;\n //if(upgrade_ ->sumBx[0]==0) TheETT = upgrade_ ->sumEt[0];\n //ETTcut = TheETT;\n //return;\n//}\n\nvoid BasicRatePlots::setRateError(TH1F* histo) {\n\n int nBins = histo->GetNbinsX();\n\n for (int iBin=1; iBin<=nBins; ++iBin) {\n float value = histo->GetBinContent(iBin);\n float error = sqrt(value);\n\n histo->SetBinError(iBin,error);\n } \n}\n\n// --------------------------------------------------------------------\n// run function \n// --------------------------------------------------------------------\n\n\nvoid BasicRatePlots::run(bool runOnData, std::string resultTag, float crossSec, int nBunches, int isCrossSec, int nEvents) {\n\n system(\"mkdir -p results\");\n std::string resultName = \"results/results_\" + resultTag + (isCrossSec ? \"_XSEC\" : \"_RATE\") + \".root\";\n TFile *outFile = new TFile((resultName).c_str(),\"recreate\");\n outFile->cd();\n\n //Event Counter\n hTH1F[\"nEvts\"] = new TH1F(\"nEvts\",\"Number of Events Processed\",1,-0.5,.5);\n //Single stuff\n hTH1F[\"nJetVsPt\"] = new TH1F(\"nJetVsPt\",\"SingleJet; E_{T} cut; rate [Hz]\",256,-0.5,255.5);\n hTH1F[\"nJetCenVsPt\"] = new TH1F(\"nJetCenVsPt\",\"SingleJetCentral; E_{T} cut; rate [Hz]\",256,-0.5,255.5);\n\n hTH1F[\"nEGVsPt\"] = new TH1F(\"nEGVsPt\",\"SingleEG; E_{T} cut; rate [Hz]\",65,-0.5,64.5);\n hTH1F[\"nEGErVsPt\"] = new TH1F(\"nEGErVsPt\",\"SingleEGer; E_{T} cut; rate [Hz]\",65,-0.5,64.5);\n\n hTH1F[\"nTauVsPt\"] = new TH1F(\"nTauVsPt\",\"SingleTau; E_{T} cut; rate [Hz]\",65,-0.5,64.5);\n hTH1F[\"nTauErVsPt\"] = new TH1F(\"nTauErVsPt\",\"SingleTauer; E_{T} cut; rate [Hz]\",65,-0.5,64.5);\n hTH1F[\"nIsoTauVsPt\"] = new TH1F(\"nIsoTauVsPt\",\"SingleIsoTau; E_{T} cut; rate [Hz]\",65,-0.5,64.5);\n hTH1F[\"nIsoTauErVsPt\"] = new TH1F(\"nIsoTauErVsPt\",\"SingleIsoTauEr; E_{T} cut; rate [Hz]\",65,-0.5,64.5);\n\n hTH1F[\"nIsoEGVsPt\"] = new TH1F(\"nIsoEGVsPt\",\"SingleIsoEGer; E_{T} cut; rate [Hz]\",65,-0.5,64.5);\n hTH1F[\"nMuVsPt\"] = new TH1F(\"nMuVsPt\",\"SingleMu; p_{T} cut; rate [Hz]\",131,-0.5,130.5);\n hTH1F[\"nMuErVsPt\"] = new TH1F(\"nMuErVsPt\",\"SingleMu |#eta|<2.1; p_{T} cut; rate [Hz]\",131,-0.5,130.5);\n hTH1F[\"nMuVsEta\"] = new TH1F(\"nMuVsEta\",\"nMuVsEta\",24,-2.4,2.4);\n hTH1F[\"nEGVsEta\"] = new TH1F(\"nEGVsEta\",\"nEGVsEta\",50,-3.,3.);\n hTH1F[\"nIsoEGVsEta\"] = new TH1F(\"nIsoEGVsEta\",\"nIsoEGVsEta\",50,-3.,3.);\n hTH1F[\"nJetVsEta\"] = new TH1F(\"nJetVsEta\",\"nJetVsEta\",50,-5.,5.);\n hTH1F[\"nJetVsEta_Central\"] = new TH1F(\"nJetVsEta_Central\",\"nJetVsEta_Central\",50,-5.,5.);\n hTH1F[\"nJetVsEta_Fwd\"] = new TH1F(\"nJetVsEta_Fwd\",\"nJetVsEta_Fwd\",50,-5.,5.);\n\n //Multistuff\n hTH1F[\"nDiJetVsPt\"] = new TH1F(\"nDiJetVsPt\",\"DiJet; E_{T} cut; rate [Hz]\",256,-0.5,255.5);\n hTH1F[\"nDiCenJetVsPt\"] = new TH1F(\"nDiCenJetVsPt\",\"DiCenJet; E_{T} cut; rate [Hz]\",256,-0.5,255.5);\n hTH2F[\"nAsymDiJetVsPt\"] = new TH2F(\"nAsymDiJetVsPt\",\"DiJet; E_{T} cut jet 1; E_{T} cut jet 2\",256,-0.5,255.5,256,-0.5,255.5);\n hTH2F[\"nAsymDiCenJetVsPt\"] = new TH2F(\"nAsymDiCenJetVsPt\",\"DiCenJet; E_{T} cut jet 1; E_{T} cut jet 2\",256,-0.5,255.5,256,-0.5,255.5);\n hTH1F[\"nQuadJetVsPt\"] = new TH1F(\"nQuadJetVsPt\",\"QuadJet; E_{T} cut; rate [Hz]\",256,-0.5,255.5);\n hTH1F[\"nQuadCenJetVsPt\"] = new TH1F(\"nQuadCenJetVsPt\",\"QuadCenJet; E_{T} cut; rate [Hz]\",256,-0.5,255.5);\n hTH1F[\"nDiTauVsPt\"] = new TH1F(\"nDiTauVsPt\",\"DiTau; E_{T} cut; rate [Hz]\",256,-0.5,255.5);\n hTH1F[\"nDiEGVsPt\"] = new TH1F(\"nDiEGVsPt\",\"DiEG; E_{T} cut; rate [Hz]\",65,-0.5,64.5);\n hTH1F[\"nDiIsoEGVsPt\"] = new TH1F(\"nDiIsoEGVsPt\",\"DiIsoEG; E_{T} cut; rate [Hz]\",65,-0.5,64.5);\n hTH2F[\"nEGPtVsPt\"] = new TH2F(\"nEGPtVsPt\",\"DoubleEle; p_{T} cut EG_{1}; p_{T} cut EG_{2}\",65,-0.5,64.5,65,-0.5,64.5);\n hTH2F[\"nIsoEGPtVsPt\"] = new TH2F(\"nIsoEGPtVsPt\",\"DoubleIsolEle; p_{T} cut EG_{1}; p_{T} cut EG_{2}\",65,-0.5,64.5,65,-0.5,64.5);\n hTH2F[\"nMuPtVsPt\"] = new TH2F(\"nMuPtVsPt\",\"DoubleMu; p_{T} cut mu_{1}; p_{T} cut mu_{2}\",41,-0.25,20.25,41,-0.25,20.25);\n hTH2F[\"nOniaMuPtVsPt\"] = new TH2F(\"nOniaMuPtVsPt\",\"DoubleMu_Er_HighQ_WdEta22 (Quarkonia); p_{T} cut mu_{1}; p_{T} cut mu_{2}\",41,-0.25,20.25,41,-0.25,20.25);\n\n //Sums\n hTH1F[\"nHTTVsHTT\"] = new TH1F(\"nHTTVsHTT\",\"HTT; HTT cut; rate [Hz]\",512,-.5,511.5);\n hTH1F[\"nETTVsETT\"] = new TH1F(\"nETTVsETT\",\"ETT; ETT cut; rate [Hz]\",512,-.5,511.5);\n hTH1F[\"nETMVsETM\"] = new TH1F(\"nETMVsETM\",\"ETM; ETM cut; rate [Hz]\",512,-.5,511.5);\n\n if (isCrossSec) {\n std::map<std::string,TH1F*>::iterator hTH1FIt = hTH1F.begin();\n std::map<std::string,TH1F*>::iterator hTH1FEnd = hTH1F.end();\n\n for(; hTH1FIt!=hTH1FEnd; ++hTH1FIt)\n {\n\thTH1FIt->second->GetYaxis()->SetTitle(\"cross section [#mubarn]\");\n }\n }\n\n Double_t nZeroBias = 0.;\n\n int nLumi(0);\n unsigned int currentLumi(-1);\n\n if (nEvents <= 0){\n nEvents=fChain->GetEntriesFast();\n }\n std::cout << \"Tree contains \" << fChain->GetEntriesFast() << \" events.\" << std::endl;\n std::cout << \"Running on \" << nEvents << \" events.\" << std::endl;\n\n for (Long64_t event=0; event<nEvents; ++event) {\n \n Long64_t eventEntry = LoadTree(event);\n if (eventEntry < 0) break;\n GetEntry(event);\n\n if (event%200000 == 0) {\n if (event_!=NULL)\n std::cout << \"Processed \" << event << \" events. Current run number: \" << event_ -> run << \" lumi: \" << event_ -> lumi << std::endl;\n else\n std::cout << \"Processed \" << event << \" events.\" << std::endl;\n\n }\n\n if (event_!=NULL && event_ -> lumi != currentLumi){\n std::cout << \"New Lumi section: \" << event_->lumi << std::endl; \n currentLumi=event_ -> lumi;\n nLumi++;\n }\n \n hTH1F[\"nEvts\"]->Fill(0.); // count number of events processed\n\n nZeroBias += 1.;\n\n float jetPt = 0.; SingleJetPt(jetPt);\n float jetCenPt = 0.; SingleJetPt(jetCenPt,true);\n float jetEta = SingleJetEta(36.);\n float jetEta_Central = SingleJetEta(36.,1);\n float jetEta_Fwd = SingleJetEta(36.,2);\n\n float TauPt = 0.;\n float TauErPt = 0.;\n float isoTauPt = 0.;\n float isoTauErPt = 0.;\n SingleTauPt(TauPt , false, false);\n SingleTauPt(TauErPt , true, false);\n SingleTauPt(isoTauPt , false, true);\n SingleTauPt(isoTauErPt , true, true);\n\n\n float htt = 0.; HTTVal(htt);\n float ett = 0.; ETTVal(ett);\n float etm = 0.; ETMVal(etm);\n\n float egPt = 0.; SingleEGPt(egPt,false,false);\n float egErPt = 0.; SingleEGPt(egErPt,false,true);\n float isoEgPt = 0.; SingleEGPt(isoEgPt,true,true);\n float egEta = SingleEGEta(16.,false);\n float isoegEta = SingleEGEta(16.,true);\n\n //cout << \"Event number = \" << nZeroBias << endl;\n float muPt = -10.; SingleMuPt(muPt,false);\n //cout << \"muPt = \" << muPt << endl; \n float muErPt = -10.; SingleMuPt(muErPt,true);\n\n //cout << \"Event number = \" << nZeroBias << endl;\n float muEta = SingleMuEta(16.);\n //cout << \"muEta = \" << muEta << endl;\n\n float doubleMuPt1 = -10.; \n float doubleMuPt2 = -10.;\n DoubleMuPt(doubleMuPt1,doubleMuPt2);\n \n float oniaMuPt1 = 0.;\n float oniaMuPt2 = 0.;\n Onia2015Pt(oniaMuPt1,oniaMuPt2,true, false, 22);\n \n \n float dijetPt1 = -10.;\n float dijetPt2 = -10.;\n float diCenjetPt1 = -10.;\n float diCenjetPt2 = -10.;\n DoubleJetPt(dijetPt1,dijetPt2);\n DoubleJetPt(diCenjetPt1,diCenjetPt2,true);\n Float_t dummy = -1;\n float ditauPt = -10.; DoubleTauJetEta2p17Pt(dummy,ditauPt);\n dummy = -1.;\n float quadjetPt = -10.; QuadJetPt(dummy,dummy,dummy,quadjetPt);\n dummy = -1.;\n float quadjetCPt = -10.; QuadJetPt(dummy,dummy,dummy,quadjetCPt,true);\n dummy = -1.;\n // \n float diEG1 = -10.;\n float diEG2 = -10.;\n float diIsolEG1 = -10.;\n float diIsolEG2 = -10.;\n DoubleEGPt(diEG1,diEG2,false);\n DoubleEGPt(diIsolEG1,diIsolEG2,true);\n\n if(muEta > -9.) hTH1F[\"nMuVsEta\"]->Fill(muEta);\n hTH1F[\"nEGVsEta\"]->Fill(egEta);\n hTH1F[\"nIsoEGVsEta\"]->Fill(isoegEta);\n hTH1F[\"nJetVsEta\"]->Fill(jetEta);\n hTH1F[\"nJetVsEta_Central\"]->Fill(jetEta_Central);\n hTH1F[\"nJetVsEta_Fwd\"]->Fill(jetEta_Fwd);\n\n for(int ptCut=0; ptCut<256; ++ptCut) {\n if(jetPt>=ptCut)\t hTH1F[\"nJetVsPt\"]->Fill(ptCut);\n if(jetCenPt>=ptCut) hTH1F[\"nJetCenVsPt\"]->Fill(ptCut);\n if(TauPt>=ptCut)\t hTH1F[\"nTauVsPt\"]->Fill(ptCut);\n if(TauErPt>=ptCut)\t hTH1F[\"nTauErVsPt\"]->Fill(ptCut);\n if(isoTauPt>=ptCut)\t hTH1F[\"nIsoTauVsPt\"]->Fill(ptCut);\n if(isoTauErPt>=ptCut)\t hTH1F[\"nIsoTauErVsPt\"]->Fill(ptCut);\n \n if(dijetPt2>=ptCut){\n hTH1F[\"nDiJetVsPt\"]->Fill(ptCut);\n \n for(int ptCut_0=ptCut; ptCut_0<256; ++ptCut_0) {\n if(dijetPt1>=ptCut_0) hTH2F[\"nAsymDiJetVsPt\"]->Fill(ptCut_0,ptCut);\n }\n }\n \n if(diCenjetPt2>=ptCut){\n hTH1F[\"nDiCenJetVsPt\"]->Fill(ptCut);\n \n for(int ptCut_0=ptCut; ptCut_0<256; ++ptCut_0) {\n if(diCenjetPt1>=ptCut_0) hTH2F[\"nAsymDiCenJetVsPt\"]->Fill(ptCut_0,ptCut);\n }\n }\n \n if(ditauPt>=ptCut) hTH1F[\"nDiTauVsPt\"]->Fill(ptCut);\n if(quadjetPt>=ptCut) hTH1F[\"nQuadJetVsPt\"]->Fill(ptCut);\n if(quadjetCPt>=ptCut) hTH1F[\"nQuadCenJetVsPt\"]->Fill(ptCut);\n \n }//loop on 256\n // \n for(int ptCut=0; ptCut<65; ++ptCut) {\n if(egPt>=ptCut) hTH1F[\"nEGVsPt\"]->Fill(ptCut);\n if(egErPt>=ptCut) hTH1F[\"nEGErVsPt\"]->Fill(ptCut);\n if(isoEgPt>=ptCut) hTH1F[\"nIsoEGVsPt\"]->Fill(ptCut);\n \n if(diEG2>=ptCut) hTH1F[\"nDiEGVsPt\"]->Fill(ptCut);\n if(diIsolEG2>=ptCut) hTH1F[\"nDiIsoEGVsPt\"]->Fill(ptCut);\n \n \n for(int ptCut2=0; ptCut2<=65; ++ptCut2) {\n if(diEG1>=ptCut && diEG2>=ptCut2 && ptCut2 <= ptCut) hTH2F[\"nEGPtVsPt\"]->Fill(ptCut,ptCut2);\n if(diIsolEG1>=ptCut && diIsolEG2>=ptCut2 && ptCut2<= ptCut) hTH2F[\"nIsoEGPtVsPt\"]->Fill(ptCut,ptCut2);\n }\n \n }//loop on 65\n // \n for(int ptCut=0; ptCut<131; ++ptCut) {\n if (muPt>=ptCut) hTH1F[\"nMuVsPt\"]->Fill(ptCut);\n if (muErPt>=ptCut) hTH1F[\"nMuErVsPt\"]->Fill(ptCut);\n }\n \n \n for(int iCut=0; iCut<41; ++iCut) {\n for(int iCut2=0; iCut2<=iCut; ++iCut2) {\n float ptCut = iCut*0.5;\n float ptCut2 = iCut2*0.5;\n if (doubleMuPt1>=ptCut && doubleMuPt2>=ptCut2) hTH2F[\"nMuPtVsPt\"]->Fill(ptCut,ptCut2);\n if (oniaMuPt1>=ptCut && oniaMuPt2>=ptCut2) hTH2F[\"nOniaMuPtVsPt\"]->Fill(ptCut,ptCut2);\n }\n }\n \n for(int httCut=0; httCut<512; ++httCut) {\n if(htt>httCut) hTH1F[\"nHTTVsHTT\"]->Fill(httCut);\n if(ett>httCut) hTH1F[\"nETTVsETT\"]->Fill(httCut);\n if(etm>httCut) hTH1F[\"nETMVsETM\"]->Fill(httCut);\n }\n \n\n } // end event loop\n\n float scaleFactor(1.);\n if (runOnData){\n std::cout << \"# of lumis sections used for rate computation : \" << nLumi << std::endl;\n //scaleFactor = (80.*631.)/(1326*23.3); \n scaleFactor = (80.*631.)/(nLumi*23.3); \n }else{\n std::cout << \"# of zero bias events (weighted) used for rate computation : \" << nZeroBias << std::endl;\n scaleFactor = ScaleFactor(nZeroBias,nBunches); \n }\n std::cout << \"Scale factor applied to histograms = \" << scaleFactor << std::endl;\n\n std::map<std::string,TH1F*>::iterator hTH1FIt = hTH1F.begin();\n std::map<std::string,TH1F*>::iterator hTH1FEnd = hTH1F.end();\n\n for(; hTH1FIt!=hTH1FEnd; ++hTH1FIt) {\n TH1F* histo = hTH1FIt->second;\n setRateError(histo);\n histo->Scale(scaleFactor);\n }\n\n std::map<std::string,TH2F*>::iterator hTH2FIt = hTH2F.begin();\n std::map<std::string,TH2F*>::iterator hTH2FEnd = hTH2F.end();\n\n for(; hTH2FIt!=hTH2FEnd; ++hTH2FIt) {\n TH2F* histo = hTH2FIt->second;\n histo->Scale(scaleFactor);\n }\n\n outFile->Write();\n outFile->Close();\n delete outFile;\n}\n\n// --------------------------------------------------------------------\n\nvoid goRatePlots(std::string fileType, int isCrossSec = false, int nEvents = 0) \n{\n //int nBunches50ns = 1368;\n int nBunches25ns = 2508; //2508 is what agreed with TSG for # bunches\n //int nBunches25ns_run256843 = 1021;\n int nBunches = -1;\n\n float xSec13TeV = isCrossSec ? 78.26 : 80.; // Using McM for cross section comparison and 80 (agreed with TSG) for rates\n //float xSec8TeV = 72.7; \n\n std::string filename;\n bool isData(true);\n \n if (fileType == \"13TEV_40PU_2016_RE-EMUL\")\n {\n isData = false;\n nBunches = nBunches25ns;\n filename = \"/afs/cern.ch/user/p/pellicci/data2/L1DPG/root/2016/v2/40PU_25ns_Stage2/40PU_25ns_Stage2_1.root\";\n }\n else if (fileType == \"13TEV_20PU_2016_RE-EMUL\")\n {\n isData = false;\n nBunches = nBunches25ns;\n filename = \"/afs/cern.ch/user/p/pellicci/data2/L1DPG/root/2016/v2/20PU_25ns_Stage2/20PU_25ns_Stage2_1.root\";\n }\n else if (fileType == \"RUN256843_Stage1\")\n {\n isData = true; \n // filename = \"/data/user/gennai/L1Ntuple/l1t_debug-stage-2_256843.root\";\n filename = \"ntuple/Run256843_stage1_Tune.list\";\n //filename = \"ntuples_256843_stage1B.list\";\n }\n else if (fileType == \"RUN256843_Stage2_8X\")\n {\n isData = true; \n //isData = false; \n //nBunches = 1021;\n // filename = \"/data/user/gennai/L1Ntuple/l1t_debug-stage-2_256843.root\";\n // filename = \"root://cmseos.fnal.gov//store/user/lpctrig/apana/Stage2/ZeroBias1/crab_ZeroBias1_Run2015D-v1/151230_012024/0000/l1t_stage2_2.root\";\n filename = \"ntuple/Run256843_stage2_8X.list\";\n //filename = \"ntuples_256843_stage2_full.list\";\n }\n else if (fileType == \"RUN259721_Stage1v2\")\n {\n isData = false; \n nBunches = 517;\n // filename = \"/data/user/gennai/L1Ntuple/l1t_debug-stage-2_256843.root\";\n // filename = \"root://cmseos.fnal.gov//store/user/lpctrig/apana/Stage2/ZeroBias1/crab_ZeroBias1_Run2015D-v1/151230_012024/0000/l1t_stage2_2.root\";\n filename = \"ntuple/r259721_Stage1v2.list\";\n //filename = \"ntuples_256843_stage2_full.list\";\n }\n else if (fileType == \"RUN256843_Stage2_76\")\n {\n isData = true; \n // filename = \"/data/user/gennai/L1Ntuple/l1t_debug-stage-2_256843.root\";\n // filename = \"root://cmseos.fnal.gov//store/user/lpctrig/apana/Stage2/ZeroBias1/crab_ZeroBias1_Run2015D-v1/151230_012024/0000/l1t_stage2_2.root\";\n filename = \"ntuple/Run256843_stage2_Len.list\";\n //filename = \"ntuples_256843_stage2_full.list\";\n }\n else if (fileType == \"Stage2_Simone\")\n {\n isData = false; \n nBunches = 1021;\n // filename = \"/data/user/gennai/L1Ntuple/l1t_debug-stage-2_256843.root\";\n filename = \"ntuple/Run256843_stage2_Simone.list\";\n //filename = \"ntuples_256843_stage2_Simone.list\";\n }\n else if (fileType == \"RUN259721_Stage2\")\n {\n isData = false; \n nBunches = 517; \n // filename = \"/data/user/gennai/L1Ntuple/l1t_debug-stage-2_256843.root\";\n filename = \"ntuple/Run259721_stage2_Simone.list\";\n //filename = \"ntuples_256843_stage2_Simone.list\";\n }\n else if (fileType == \"RUN260627_Aaron\")\n {\n isData = false; \n nBunches = 1021;\n // filename = \"/data/user/gennai/L1Ntuple/l1t_debug-stage-2_256843.root\";\n filename = \"ntuples_260627_Aaron.list\";\n }\n else \n {\n std::cout << \"Config param \" << fileType << \" invalid! \\n\"\n\t\t<< \"Valid fileType values are : DATA, 8TEV_TF_DATA, 8TEV_TF_2012_RE-EMUL, \"\n\t\t<< \"8TEV_25PU_ORIG_RE-EMUL, 8TEV_25PU_2012_RE-EMUL, 8TEV_25PU_2012GCT10GEV_RE-EMUL, 8TEV_25PU_2015_RE-EMUL, \"\n\t\t<< \"13TEV_25PU_ORIG_RE-EMUL, 13TEV_25PU_2012_RE-EMUL, 13TEV_25PU_2012GCT10GEV_RE-EMUL, 13TEV_25PU_2015_RE-EMUL\\n\";\n }\n\n // TTree *tree;\n // TFile f(filename.c_str());\n // TDirectory * dir = (TDirectory*)f.Get(\"l1UpgradeTree\");\n // dir->GetObject(\"L1UpgradeTree\",tree);\n\n BasicRatePlots basicRatePlots(filename); \n basicRatePlots.run(isData,fileType,xSec13TeV,nBunches,isCrossSec,nEvents);\n \n}\n\n"
},
{
"alpha_fraction": 0.5316174030303955,
"alphanum_fraction": 0.5543868541717529,
"avg_line_length": 24.983922958374023,
"blob_id": "2299fb054e66314c36700084de5f895f56feb937",
"content_id": "3c6c900c098f72aabfeda27b03722a20f24c2c22",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 8081,
"license_type": "no_license",
"max_line_length": 98,
"num_lines": 311,
"path": "/macros/comparePlots.cc",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "#include <map>\n#include <vector>\n#include <string>\n#include <fstream>\n#include <sstream>\n#include <iostream>\n#include <iomanip>\n#include <cmath>\n#include <stdlib.h>\n\n#include \"TH1F.h\"\n#include \"TH2F.h\"\n#include \"TH1D.h\"\n#include \"TFile.h\"\n#include \"TList.h\"\n#include \"THStack.h\"\n#include \"TIterator.h\"\n#include \"TObject.h\"\n#include \"TClass.h\"\n#include <TROOT.h>\n#include <TCanvas.h>\n#include <TLegend.h>\n#include <TSystem.h>\n\n#include \"tdrstyle.C\"\n\nstd::string BuildLeg(std::string filename);\nvoid getPlotList( const std::string & fileName,\n\t\t std::map<std::string, std::vector<std::string> > & plotList )\n{\n TH1::AddDirectory(kFALSE);\n\n // build list of histogram names\n TFile rootfile( fileName.c_str() );\n\n std::vector< std::string > dirList;\n\t \n TList *dirs = rootfile.GetListOfKeys();\n TIterator *itdir = dirs->MakeIterator();\n TObject *nextdir;\n\n while ( (nextdir = itdir->Next()) ) {\n \n if( nextdir->IsFolder())\n dirList.push_back( nextdir->GetName() );\n else \n plotList[\"\"].push_back( ( nextdir->GetName() ) );\n\n \n }\n \n std::vector<std::string>::const_iterator dirIt = dirList.begin();\n std::vector<std::string>::const_iterator dirEnd = dirList.end();\n \n for (;dirIt!=dirEnd;++dirIt){\n \n TDirectory * thisdir = (TDirectory*)( rootfile.Get( dirIt->c_str() ) );\n \n TList * dircontent = thisdir->GetListOfKeys();\n TIterator * thisplot = dircontent->MakeIterator();\n TObject * nextplot;\n \n const std::string & dirName = (*dirIt); \n \n while ( (nextplot = thisplot->Next()) ) {\n plotList[dirName].push_back( ( dirName + \"/\" + nextplot->GetName() ) );\n }\n\n }\n\n rootfile.Close();\n\n}\n\n\nvoid getRange( TH1* plot, float & minY, float & maxY )\n{\n\n minY = 1E10;\n maxY = 0.;\n\n int nBins = plot->GetNbinsX();\n \n for ( int iBin=0; iBin<=nBins; ++iBin )\n {\n\n float val = plot->GetBinContent( iBin );\n minY = ( val > 0.001 && val < minY ) ? val : minY;\n maxY = ( val > 0.001 && val > maxY ) ? val : maxY;\n\n }\n\n minY = ( fabs(minY - 1E10) > 0.01 ) ? minY*0.5 : 0.;\n maxY = ( fabs(maxY - 0. ) > 0.01 ) ? maxY*2. : 1.;\n\n return;\n\n}\n\n\nvoid plot( std::vector<TH1*> plots,\n\t std::string &baseDir, std::string outputDir,\n std::vector<std::string> legs) \n{\n \n if (plots.at(0))\n {\n std::cout << \"Plotting : \" << plots.at(0)->GetName() << std::endl;\n \n // plot everything\n TCanvas *c = new TCanvas();\n\n c->cd();\n\n if (dynamic_cast<TH1F*>(plots.at(0))) \n\t{\n\n float minY = 0;\n float maxY = 0;\n\n\t for (size_t iPlot=0; iPlot<plots.size(); ++iPlot){\n\t float tmp_minY = 999.;\n\t float tmp_maxY = -999.;\n getRange( plots.at(iPlot), tmp_minY, tmp_maxY );\n\t if(tmp_minY < minY) minY = tmp_minY;\n\t if(tmp_maxY > maxY) maxY = tmp_maxY;\n\t }\n\n\t std::cout << \"min \" << minY << std::endl;\n\t std::cout << \"max \" << maxY << std::endl;\n\t \n\t TPad *pPlot = ( plots.size()>1 ) ? new TPad(\"pPlot\",\"\",0.05,0.26,0.99,0.99) :\n\t new TPad(\"pPlot\",\"\",0.05,0.01,0.99,0.99) ;\n\t \n\t pPlot->Draw();\n\t pPlot->SetGrid();\n TLegend *leg = new TLegend(0.4055405,0.7411604,0.9767243,0.896555,NULL,\"brNDC\");\n leg->SetFillColor(0);\n leg->SetBorderSize(0);\n leg->SetBorderSize(0);\n leg->SetFillStyle(0);\n leg->SetTextFont(62);\n\t \n\t c->cd();\n\t \n\t TPad *pRatio = ( plots.size()>1 ) ? new TPad(\"pRatio\",\"\",0.05,0.01,0.99,0.25) : 0;\n\t if(pRatio)\n\t {\n\t pRatio->Draw();\n\t pRatio->SetGrid();\n\t }\n\t \n\t for (size_t iPlot=0; iPlot<plots.size(); ++iPlot) \n\t {\n\t pPlot->cd();\n\t plots.at(iPlot)->SetLineColor( iPlot+1 );\n\t plots.at(iPlot)->SetFillColor( iPlot+1 );\n\t plots.at(iPlot)->SetMarkerColor( iPlot+1 );\n\t plots.at(iPlot)->SetMarkerStyle( 21 + iPlot );\n\t \n getRange( plots.at(iPlot), minY, maxY );\n\t plots.at(iPlot)->GetYaxis()->SetRangeUser( minY, maxY );\n\t plots.at(iPlot)->GetYaxis()->SetTitleSize(0.06);\n\t plots.at(iPlot)->GetYaxis()->SetTitleOffset(0.7);\n\t plots.at(iPlot)->Draw( iPlot ? \"samePE1\" : \"PE1\" );\n leg->AddEntry(plots.at(iPlot), BuildLeg(legs.at(iPlot)).c_str(), \"P\");\n\t \n\n\t if ( iPlot>0 ) \n\t\t{\n\t\t pRatio->cd();\n\t\t TH1* den = plots.at(0);\n\t\t std::string name = std::string(plots.at(iPlot)->GetName()) + \"_Eff\";\n\t\t TH1* eff = static_cast<TH1*>( plots.at(iPlot)->Clone( name.c_str() ) );\n\t\t eff->Divide(den);\n\t\t eff->SetTitle(\";;Ratio\");\n\t\t \n\t\t eff->SetLineColor( iPlot+1 );\n\t\t eff->SetFillColor( iPlot+1 );\n\t\t eff->SetMarkerColor( iPlot+1 );\n\t\t eff->SetMarkerStyle( 21 + iPlot );\n\t eff->GetYaxis()->SetTitleSize(0.14);\n eff->GetYaxis()->SetTitleOffset(0.4);\n\t\t eff->GetYaxis()->SetRangeUser( .1, 5.);\n\t\t eff->GetYaxis()->SetLabelSize( .11);\n\t\t \n\t\t eff->Draw( iPlot>1 ? \"samePE1\" : \"PE1\" );\n\t\t}\n\t }\n\t \n pPlot->cd();\n\t pPlot->SetLogy();\n leg->Draw();\n\t}\n else if(dynamic_cast<TH2F*>(plots.at(0)) && plots.size() == 2) \n\t{ \n\t c->SetGrid();\n\t \n\t TH1* den = plots.at(0);\n\t std::string name = std::string(plots.at(1)->GetName()) + \"_Eff\";\n\t TH1* eff = static_cast<TH1*>( plots.at(1)->Clone( name.c_str() ) );\n\t eff->Divide(den);\n\t eff->SetTitle(\";;Ratio\");\n\t eff->SetMinimum(1);\n\t eff->SetMaximum(2.5);\n\t eff->Draw(\"colz\");\n\t}\n \n std::string path = baseDir + \"/\" + outputDir;\n system( (std::string(\"mkdir -p \") + path).c_str() );\n \n c->Update();\n std::string printname = path + \"/\" + plots.at(0)->GetName();\n c->Print ( ( printname + \".gif\" ).c_str() ); \n c->Print ( ( printname + \".root\" ).c_str() ); \n //c->Print ( ( printname + \".C\" ).c_str() ); \n }\n \n}\n\nvoid plotAll(std::vector<std::string> &files,\n\t std::string &baseDir) \n{\n\n size_t nFiles = 0;\n std::vector<TFile*> filesRoot;\n\n for (size_t iFile=0; iFile<files.size(); ++iFile) {\n filesRoot.push_back(new TFile(files.at(iFile).c_str(),\"READONLY\"));\n }\n\n system( (std::string(\"mkdir -p \") + baseDir).c_str() );\n \n std::map<std::string, std::vector<std::string> > plotNames;\n\n getPlotList(files.at(0),plotNames);\n\n std::map<std::string, std::vector<std::string> >::const_iterator plotDirIt = plotNames.begin();\n std::map<std::string, std::vector<std::string> >::const_iterator plotDirEnd = plotNames.end();\n\n for(;plotDirIt!=plotDirEnd;++plotDirIt) {\n\n std::vector<std::string>::const_iterator plotIt = plotDirIt->second.begin();\n std::vector<std::string>::const_iterator plotEnd = plotDirIt->second.end();\n\n for(;plotIt!=plotEnd;++plotIt) {\n\n std::vector<TH1*> plots;\n std::vector<std::string> legs;\n\n for (size_t iFile=0; iFile<filesRoot.size(); ++iFile) {\n plots.push_back(static_cast<TH1*>( filesRoot.at(iFile)->Get( plotIt->c_str() ) )); \n legs.push_back(files.at(iFile));\n }\n \n plot(plots,baseDir,plotDirIt->first, legs);\n \n }\n }\n \n}\n\n// === FUNCTION ============================================================\n// Name: BuildLeg\n// Description: \n// ===========================================================================\nstd::string BuildLeg(std::string filename)\n{\n std::string temp=filename;\n size_t found = filename.find_last_of(\"/\");\n if (found != std::string::npos)\n {\n temp = filename.substr(found+1);\n }\n\n found = temp.find_last_of(\".\");\n if (found != std::string::npos)\n {\n temp = temp.substr(0, found);\n }\n\n return temp;\n} // ----- end of function BuildLeg -----\n\nint main(int argc, char* argv[]) \n{ \n\n setTDRStyle();\n \n if ( argc<2 ) {\n std::cout << \"Error in number of arguments: \" << argc << std::endl;\n std::cout << \"Passed args: \" << argc << std::endl;\n for ( int i = 1; i < argc; ++i ) {\n std::cout << \"\\t\" << argv[i] << std::endl;\n }\n std::cout << \"Usage: \\n\\t\\t \" << argv[0] << \" <first inputfile> <second inputfile> ... \"\n\t << std::endl << std::endl;\n return -1;\n }\n\n \n std::vector<std::string> files;\n for (int iArg=1; iArg<argc; ++iArg) {\n files.push_back(argv[iArg]);\n }\n\n std::string baseDir = \"results/comparePlots\";\n\n plotAll(files,baseDir);\n\n}\n"
},
{
"alpha_fraction": 0.25930824875831604,
"alphanum_fraction": 0.35418635606765747,
"avg_line_length": 51.90999984741211,
"blob_id": "948c9c00e234eef7b1fc8f6f674e9679dfa0cce4",
"content_id": "4c1478dc03bd233b6b39d6a15c2ee585bd0a8eff",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5291,
"license_type": "no_license",
"max_line_length": 126,
"num_lines": 100,
"path": "/macros/menu/Slim2E34.txt",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "## Start with 100kHz in Level 1\n## Assume 2kHz for Zero bias\n## Assume bptx trigger rates are PU independant, get them from WBM\n## Assume 4kHz for bxpt seeds\n## Assume 5kHz for buffer\n## Menu rate = 100 - 2 - 4 - 5 = 89kHz\n## Slim Menu rate = 62kHz\n\n#============================================================================#\n#------------------------------- Menu -------------------------------#\n#============================================================================#\n# L1Seed Bit Prescale POG PAG\n# L1_ZeroBias 0 25409 Tech\n## Muon\nL1_SingleMu22 11 0 Mu\nL1_SingleMu25 12 1 Mu\nL1_SingleMu30 13 1 Mu\nL1_SingleMu20er 19 0 Mu\nL1_SingleMu22er 20 1 Mu\nL1_SingleMu25er 21 1 Mu\nL1_SingleMu30er 22 1 Mu\nL1_DoubleMu_12_5 28 0 Mu\nL1_DoubleMu_13_6 29 1 Mu\nL1_DoubleMu_15_5 30 1 Mu\nL1_DoubleMu_12_8 31 1 Mu\nL1_TripleMu_5_0_0 276 0 Mu\nL1_TripleMu_5_5_3 37 1 Mu\nL1_QuadMu0 38 1 Mu\n\n## EG\nL1_SingleEG36 259 0 EG\nL1_SingleEG38 260 0 EG\nL1_SingleEG40 50 1 EG\nL1_SingleEG45 52 1 EG\nL1_SingleIsoEG34 61 0 EG\nL1_SingleIsoEG36 262 0 EG\nL1_SingleIsoEG38 286 1 EG\nL1_SingleIsoEG32er 263 0 EG\nL1_SingleIsoEG34er 70 0 EG\nL1_SingleIsoEG36er 270 1 EG\nL1_DoubleEG_24_17 77 1 EG\nL1_DoubleEG_25_12 277 0 EG\nL1_DoubleEG_25_13 498 0 EG\nL1_DoubleEG_25_14 479 1 EG\nL1_TripleEG_18_17_8 79 1 EG\n\n## Jet\nL1_SingleJet180 90 1 Jet\nL1_SingleJet200 91 1 Jet\nL1_DoubleJetC112 97 1 Jet\nL1_DoubleJetC120 98 1 Jet\nL1_TripleJet_92_76_64_VBF 101 1 Jet\nL1_QuadJetC50 103 1 Jet\nL1_QuadJetC60 104 1 Jet\n\n## Tau\nL1_SingleTau120er 107 1 Tau\nL1_DoubleIsoTau30er 110 0 Tau\nL1_DoubleIsoTau32er 111 0 Tau\nL1_DoubleIsoTau33er 264 0 Tau\nL1_DoubleIsoTau34er 265 1 Tau\nL1_DoubleIsoTau35er 266 1 Tau\nL1_DoubleIsoTau36er 278 1 Tau\nL1_DoubleTau50er 114 0 Tau\nL1_DoubleTau70er 289 1 Tau\n\n## HTT\nL1_HTT300 123 0 Sum\nL1_HTT320 124 0 Sum\nL1_HTT340 424 0 Sum\nL1_HTT360 224 0 Sum\nL1_HTT380 225 1 Sum\nL1_HTT400 226 1 Sum\n\n## ETM\nL1_ETM100 142 0 Sum\nL1_ETM120 143 1 Sum\nL1_ETM105 286 0 Sum\nL1_ETM110 287 0 Sum\nL1_ETM115 288 0 Sum\n#============================================================================#\n#---------------------------- Fixed Rate ----------------------------#\n#============================================================================#\n# # L1_AlwaysTrue\n# # L1_BptxPlus\n# # L1_BptxMinus\n# # L1_BptxOR\n# # L1_SingleMuOpen_NotBptxOR_3BX\n# # L1_SingleJetC20_NotBptxOR_3BX\n# # L1_SingleJetC32_NotBptxOR_3BX\n# # L1_SingleJetC36_NotBptxOR_3BX\n# # L1_SingleMuOpen_NotBptxOR 454 -1 Mu #Assume 1kHz for all bptx triggers\n# # L1_SingleJetC32_NotBptxOR 455 -1 Jet #Assume 1kHz for all bptx triggers\n# # L1_SingleJetC20_NotBptxOR 456 -1 Jet #Assume 1kHz for all bptx triggers\n# # L1_SingleEG2_BptxAND 457 -1 Jet #Assume 1kHz for all bptx triggers\n# # L1_ETT15_BptxAND 458 -1 Sum #Assume 1kHz for all bptx triggers\n# # L1_SingleJet8_BptxAND 459 -1 Jet #Assume 1kHz for all bptx triggers\n# # L1_SingleJet12_BptxAND 460 -1 Jet #Assume 1kHz for all bptx triggers\n\n# vim: ft=python:nolbr:cc=88\n"
},
{
"alpha_fraction": 0.6324085593223572,
"alphanum_fraction": 0.6762295365333557,
"avg_line_length": 47.04545593261719,
"blob_id": "ee8ddf35064e6c545e8cad3be4c89b49cb2fc8e2",
"content_id": "4fe99f3913e3a0c3cbad645bdc99a38705c96cde",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3172,
"license_type": "no_license",
"max_line_length": 214,
"num_lines": 66,
"path": "/test/crab/multicrab.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "from WMCore.Configuration import Configuration\n\nconfig = Configuration()\n\nconfig.section_('General')\nconfig.General.transferOutputs = True\nconfig.General.transferLogs = True\nconfig.General.workArea = 'crab_projects'\n\nconfig.section_('JobType')\nconfig.JobType.psetName = '../customL1NtupleFromRaw.py'\nconfig.JobType.pluginName = 'Analysis'\nconfig.JobType.outputFiles = ['L1Tree.root']\nconfig.JobType.inputFiles = ['../../data/Jet_Stage1_2015_v2.txt']\n\nconfig.section_('Data')\nconfig.Data.inputDBS = 'global'\nconfig.Data.splitting = 'FileBased'\nconfig.Data.unitsPerJob = 10\n\nconfig.section_('Site')\nconfig.Site.storageSite = 'T2_CH_CERN'\n\nif __name__ == '__main__':\n\n from CRABAPI.RawCommand import crabCommand\n from CRABClient.ClientExceptions import ClientException\n from httplib import HTTPException\n from multiprocessing import Process\n\n def submit(config):\n try:\n crabCommand('submit', config = config)\n except HTTPException as hte:\n print \"Failed submitting task: %s\" % (hte.headers)\n except ClientException as cle:\n print \"Failed submitting task: %s\" % (cle)\n\n #############################################################################################\n ## From now on that's what users should modify: this is the a-la-CRAB2 configuration part. ##\n #############################################################################################\n\n config.General.requestName = '13TeV_20PU_25ns_ReEmul2015_v16'\n config.Data.unitsPerJob = 7\n config.Data.inputDataset = '/SingleNeutrino/RunIISpring15Digi74-AVE_20_BX_25ns_tsg_MCRUN2_74_V7-v1/GEN-SIM-RAW'\n config.Data.outLFNDirBase = '/store/group/dpg_trigger/comm_trigger/L1Trigger/L1Menu2015/v16/'\n config.JobType.pyCfgParams = ['reEmulation=True', 'reEmulMuons=True', 'reEmulCalos=True', 'patchNtuple=True', 'useStage1Layer2=True', 'globalTag=MCRUN2_74_V9', 'runOnMC=True', 'runOnPostLS1=True', 'whichPU=20']\n p = Process(target=submit, args=(config,))\n p.start()\n p.join()\n\n config.General.requestName = '13TeV_40PU_25ns_ReEmul2015_v16'\n config.Data.inputDataset = '/SingleNeutrino/RunIISpring15Digi74-AVE_40_BX_25ns_tsg_MCRUN2_74_V7-v2/GEN-SIM-RAW'\n config.Data.outLFNDirBase = '/store/group/dpg_trigger/comm_trigger/L1Trigger/L1Menu2015/v16/'\n config.JobType.pyCfgParams = ['reEmulation=True', 'reEmulMuons=True', 'reEmulCalos=True', 'patchNtuple=True', 'useStage1Layer2=True', 'globalTag=MCRUN2_74_V9', 'runOnMC=True', 'runOnPostLS1=True', 'whichPU=40']\n p = Process(target=submit, args=(config,))\n p.start()\n p.join()\n\n #config.General.requestName = '13TeV_30PU_50ns_ReEmul2012Gct10GeV_v16'\n #config.Data.inputDataset = '/SingleNeutrino/RunIISpring15Digi74-AVE_30_BX_50ns_tsg_MCRUN2_74_V6-v1/GEN-SIM-RAW'\n #config.Data.outLFNDirBase = '/store/group/dpg_trigger/comm_trigger/L1Trigger/L1Menu2015/v16/'\n #config.JobType.pyCfgParams = ['reEmulation=True', 'reEmulMuons=True', 'reEmulCalos=True', 'patchNtuple=True', 'globalTag=MCRUN2_74_V8', 'runOnMC=True', 'runOnPostLS1=True', 'jetSeedThr10GeV=True']\n #p = Process(target=submit, args=(config,))\n #p.start()\n #p.join()\n\n"
},
{
"alpha_fraction": 0.49913105368614197,
"alphanum_fraction": 0.510948896408081,
"avg_line_length": 24.909910202026367,
"blob_id": "a1c5281addfab8cb0157188f7c7c2961b7265b04",
"content_id": "f7c1beba1718c450d1629df1d868716fa1fc6031",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2877,
"license_type": "no_license",
"max_line_length": 84,
"num_lines": 111,
"path": "/macros/plot/compareFiles.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "from ROOT import *\nfrom sys import argv\nimport os\nimport copy\nfrom Config import DualMap\n\nNORM=False\nLOG=True\n\ngStyle.SetOptStat(False)\ngROOT.SetBatch(True)\n\ntry: fileNames=argv[1:]\nexcept:\n print \"No files specified\"\n exit()\n\nif not os.path.exists(\"plots\"): os.mkdir(\"plots\")\n\nfiles=[]\nfor fileName in fileNames:\n files.append(TFile(fileName))\n\ndef getall(d, basepath=\"\"):\n \"Generator function to recurse into a ROOT file/dir and yield (path, obj) pairs\"\n for key in d.GetListOfKeys():\n kname = key.GetName()\n if key.IsFolder():\n # TODO: -> \"yield from\" in Py3\n for i in getall(d.Get(kname), basepath+kname+\"/\"):\n yield i\n else:\n yield basepath+kname, d.Get(kname)\n\nkeys=getall(files[0])\n\nc=TCanvas()\nfor k, o in getall(files[0]):\n if type(files[0].Get(k))!=type(TH1F()) and \\\n type(files[0].Get(k))!=type(TProfile()) and \\\n type(files[0].Get(k))!=type(TH1D()) and \\\n type(files[0].Get(k))!=type(TGraphAsymmErrors()):\n continue\n\n l=TLegend(.49,.69,.89,.89)\n l.SetFillStyle(0)\n hists=[]\n max=0\n\n for lp in range(len(files)):\n file=files[lp]\n fileName=fileNames[lp]\n\n file.cd()\n h = file.Get(k)\n if h == None:\n temph = None\n tempk = copy.copy(k)\n for mapk in DualMap.keys():\n if mapk in tempk:\n tempk =tempk.replace(mapk, DualMap[mapk])\n\n temph = file.Get(tempk)\n if temph == None:\n continue\n else:\n h = temph\n\n #h.Rebin(4)\n hists.append(h)\n\n if NORM:h.Scale(1./h.Integral())\n\n if h.GetMaximum()>max: max=h.GetMaximum()\n\n h.SetLineColor(1+lp)\n h.SetLineWidth(3)\n legname = fileNames[lp].split('/')[-1]\n legname = legname.split('.')[0]\n legname = legname.replace(\"results_\", \"\")\n legname = legname.replace(\"_Menu\", \"\")\n legname = legname.replace(\"_RATE\", \"\")\n l.AddEntry(h,legname.replace('_', ' '),\"l\")\n\n for lp in range(len(hists)):\n h=hists[lp]\n\n if lp==0:\n if LOG or k == \"jet_eta\":\n c.SetLogy(True)\n h.SetMaximum(100*max)\n else:\n c.SetLogy(False)\n # h.SetMaximum(2*max)\n h.SetMinimum(0)\n if type(h) == type(TGraphAsymmErrors()):\n c.SetLogy(False)\n h.SetMaximum(1.8)\n h.Draw(\"AP\")\n else:\n h.Draw(\"hist\")\n else:\n if type(h) == type(TGraphAsymmErrors()):\n h.Draw(\"P\")\n else:\n h.Draw(\"histSAME\")\n l.Draw(\"SAME\")\n kname = k.replace(\"/\", \"_\")\n c.SaveAs(\"plots/\"+kname+\".pdf\")\n c.SaveAs(\"plots/\"+kname+\".root\")\n c.SaveAs(\"plots/\"+kname+\".png\")\n\n"
},
{
"alpha_fraction": 0.48566821217536926,
"alphanum_fraction": 0.5312405228614807,
"avg_line_length": 33.21310806274414,
"blob_id": "e92faa5a685341d07f8c90d69b4da3a91f41c036",
"content_id": "57935c21e923d25d209ed729594e2ae54cd1af07",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 72566,
"license_type": "no_license",
"max_line_length": 164,
"num_lines": 2121,
"path": "/macros/L1Menu2016.C",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "// ===========================================================================\n// \n// Filename: L1Menu2016.C\n// \n// Description: \n// \n// Version: 1.0\n// Created: 01/13/2016 18:39:20\n// Compiler: g++ -std=c++11\n// \n// Author: Zhenbin Wu (benwu)\n// Email: [email protected]\n// Company: UIC, CMS@LPC, CDF@FNAL\n// \n// ===========================================================================\n\n#include \"L1Menu2016.h\"\n\n//----------------------------------------------------------------------------\n// Class: L1Menu2016\n// Method: L1Menu2016\n// Description: constructor\n//----------------------------------------------------------------------------\nL1Menu2016::L1Menu2016 (std::string MenuName, std::string filelist):\n writefiles(true),writecsv(false),writeplots(true),\n menufilename(MenuName), \n tuplefilename(filelist),\n scale(0),\n l1Plot(nullptr),\n l1TnP(nullptr),\n l1uGT(nullptr),\n l1unpackuGT(nullptr)\n{\n InitConfig();\n} // ----- end of method L1Menu2016::L1Menu2016 (constructor) -----\n\n//----------------------------------------------------------------------------\n// Class: L1Menu2016\n// Method: ~L1Menu2016\n// Description: destructor\n//----------------------------------------------------------------------------\nL1Menu2016::~L1Menu2016 ()\n{\n outfile->close();\n outcsv->close();\n outrootfile->Close();\n fChain->Reset();\n //delete outfile;\n //delete outcsv;\n //delete outrootfile;\n} // ----- end of method L1Menu2016::-L1Menu2016 (destructor) -----\n\n//----------------------------------------------------------------------------\n// Class: L1Menu2016\n// Method: operator =\n// Description: assignment operator\n//----------------------------------------------------------------------------\n L1Menu2016&\nL1Menu2016::operator = ( const L1Menu2016 &other )\n{\n if ( this != &other ) {\n }\n return *this;\n} // ----- end of method L1Menu2016::operator = (assignment operator) ---\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ConfigOutput\n// Description: \n// ===========================================================================\nbool L1Menu2016::ConfigOutput(bool writetext_, bool writecsv_, bool writeplot_, \n std::string outputdir_, std::string outputname_)\n{\n writefiles = writetext_;\n writecsv = writecsv_;\n writeplots = writeplot_;\n outputdir = outputdir_;\n if (outputname_ == \"Auto\")\n {\n outputname = SetOutputName();\n }\n else\n outputname = outputname_;\n\n if (writefiles)\n outfile = new std::fstream( outputdir + \"/\" + outputname +\".txt\", std::fstream::out );\n if (writecsv)\n outcsv = new std::fstream( outputdir + \"/\" + outputname +\".csv\", std::fstream::out );\n if (writeplots)\n {\n std::string rootfilename = outputdir + \"/\" + outputname +\".root\";\n outrootfile = new TFile( rootfilename.c_str(), \"RECREATE\");\n }\n return true;\n} // ----- end of function L1Menu2016::ConfigOutput -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::InitConfig\n// Description: \n// ===========================================================================\nbool L1Menu2016::InitConfig()\n{\n L1Config[\"SumJetET\"] = 0;\n L1Config[\"SumJetEta\"] = 999;\n L1Config[\"nBunches\"] = 2592; //default for 2017 nBunches\n L1Config[\"doPlotRate\"] = 0;\n L1Config[\"doPlotEff\"] = 0;\n L1Config[\"doPlotTest\"] = 0;\n L1Config[\"doPlotuGt\"] = 0;\n L1Config[\"doTnPMuon\"] = 0;\n L1Config[\"doPlotLS\"] = 0;\n L1Config[\"doPrintPU\"] = 0;\n L1Config[\"doCompuGT\"] = 0;\n L1Config[\"maxEvent\"] = -1;\n L1Config[\"SetMuonER\"] = -1;\n L1Config[\"SetNoPrescale\"] = 0;\n L1Config[\"UseUpgradeLyr1\"] = -1;\n L1Config[\"UseL1CaloTower\"] = -1;\n L1Config[\"SelectRun\"] = -1;\n L1Config[\"SelectEvent\"] = -1;\n L1Config[\"UsePFMETNoMuon\"] = 0;\n L1Config[\"UseuGTDecision\"] = 0;\n L1Config[\"UseUnpackTree\"] = 0;\n L1Config[\"doScanLS\"] = 0;\n \n L1ConfigStr[\"SelectLS\"] = \"\";\n L1ConfigStr[\"SelectBX\"] = \"\";\n L1ConfigStr[\"Lumilist\"] = \"\";\n L1ConfigStr[\"SelectCol\"] = \"\";\n\n L1ObjectMap[\"Jet\"] = &L1Event.JetPt;\n L1ObjectMap[\"JetC\"] = &L1Event.JetCenPt;\n L1ObjectMap[\"Tau\"] = &L1Event.TauPt;\n L1ObjectMap[\"Tauer\"] = &L1Event.TauerPt;\n L1ObjectMap[\"IsoTau\"] = &L1Event.IsoTauPt;\n L1ObjectMap[\"EG\"] = &L1Event.EGPt;\n L1ObjectMap[\"EGer\"] = &L1Event.EGerPt;\n L1ObjectMap[\"IsoEG\"] = &L1Event.IsoEGPt;\n L1ObjectMap[\"IsoEGer\"] = &L1Event.IsoEGerPt;\n L1ObjectMap[\"Mu\"] = &L1Event.MuPt;\n L1ObjectMap[\"MuOpen\"] = &L1Event.MuOpenPt;\n L1ObjectMap[\"Muer\"] = &L1Event.MuerPt;\n L1ObjectMap[\"HTT\"] = &L1Event.HTT;\n L1ObjectMap[\"HTM\"] = &L1Event.HTM;\n L1ObjectMap[\"ETM\"] = &L1Event.ETM;\n L1ObjectMap[\"ETT\"] = &L1Event.ETT;\n L1ObjectMap[\"ETMHF\"] = &L1Event.ETMHF;\n L1ObjectMap[\"HTTHF\"] = &L1Event.HTTHF;\n\n\n //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Map to old func for now. ~~~~~\n // MutliJets\n L1SeedFun[\"L1_QuadJetC36_TauJet52\"] = std::bind(&L1AlgoFactory::QuadJetCentral_TauJet, this, 36.,52.);\n L1SeedFun[\"L1_QuadJetC36_Tau52\"] = std::bind(&L1AlgoFactory::QuadJetCentral_TauJet, this, 36.,52.);\n\n // MultiMuon\n L1SeedFun[\"L1_DoubleMu0er1p6_dEta_Max1p8_OS\"] = std::bind(&L1AlgoFactory::Onia2015, this, 0.,0.,true,true,18, 1.6);\n L1SeedFun[\"L1_DoubleMu0er1p6_dEta_Max1p8\"] = std::bind(&L1AlgoFactory::Onia2015, this, 0.,0.,true,false,18, 1.6);\n L1SeedFun[\"L1_DoubleMu0er1p25_dEta_Max1p8_OS\"] = std::bind(&L1AlgoFactory::Onia2015, this, 0.,0.,true,true,18, 1.25);\n L1SeedFun[\"L1_DoubleMu0er1p0_dEta_Max1p8_OS\"] = std::bind(&L1AlgoFactory::Onia2015, this, 0.,0.,true,true,18, 1.25);\n L1SeedFun[\"L1_DoubleMu0er1p4_dEta_Max1p8_OS\"] = std::bind(&L1AlgoFactory::Onia2015, this, 0.,0.,true,true,18, 1.4);\n L1SeedFun[\"L1_DoubleMu_10_0_dEta_Max1p8\"] = std::bind(&L1AlgoFactory::Onia2015, this, 10.,0.,false,false,18, 1.6);\n L1SeedFun[\"L1_DoubleMu0\"] = std::bind(&L1AlgoFactory::DoubleMu, this, 0.,0.,true, false);\n L1SeedFun[\"L1_DoubleMuOpen\"] = std::bind(&L1AlgoFactory::DoubleMuOpen, this, 0.);\n L1SeedFun[\"L1_DoubleMu_10_Open\"] = std::bind(&L1AlgoFactory::DoubleMuXOpen, this, 10.);\n L1SeedFun[\"L1_DoubleMu_10_0\"] = std::bind(&L1AlgoFactory::DoubleMu, this, 10.,0.,true, false);\n L1SeedFun[\"L1_DoubleMu_10_3p5\"] = std::bind(&L1AlgoFactory::DoubleMu, this, 10.,3.5,true, false);\n L1SeedFun[\"L1_DoubleMu_12_5\"] = std::bind(&L1AlgoFactory::DoubleMu, this, 12.,5.,true,false);\n L1SeedFun[\"L1_DoubleMu_11_4\"] = std::bind(&L1AlgoFactory::DoubleMu, this, 11.,4.,true,false);\n L1SeedFun[\"L1_DoubleMu_12_8\"] = std::bind(&L1AlgoFactory::DoubleMu, this, 12.,8.,true,false);\n L1SeedFun[\"L1_DoubleMu_13_6\"] = std::bind(&L1AlgoFactory::DoubleMu, this, 13.,6.,true,false);\n L1SeedFun[\"L1_DoubleMu_15_5\"] = std::bind(&L1AlgoFactory::DoubleMu, this, 15.,5.,true,false);\n L1SeedFun[\"L1_TripleMu0\"] = std::bind(&L1AlgoFactory::TripleMu, this, 0.,0.,0.,1);\n L1SeedFun[\"L1_TripleMuOpen\"] = std::bind(&L1AlgoFactory::TripleMu, this, 0.,0.,0.,0);\n L1SeedFun[\"L1_TripleMu_5_5_3\"] = std::bind(&L1AlgoFactory::TripleMu, this, 5.,5.,3.,1);\n L1SeedFun[\"L1_TripleMu_5_0_0\"] = std::bind(&L1AlgoFactory::TripleMu, this, 5.,0.,0.,1);\n L1SeedFun[\"L1_TripleMu_3_0_0\"] = std::bind(&L1AlgoFactory::TripleMu, this, 3.,0.,0.,1);\n L1SeedFun[\"L1_QuadMu0\"] = std::bind(&L1AlgoFactory::QuadMu, this, 0.,0.,0.,0.,1);\n\n //Cross\n L1SeedFun[\"L1_IsoEG20er_Tau20er_dEta_Min0p2\"] = std::bind(&L1AlgoFactory::IsoEGer_TauJetEta2p17, this, 20.,20.,false);\n L1SeedFun[\"L1_IsoEG22er_Tau20er_dEta_Min0p2\"] = std::bind(&L1AlgoFactory::IsoEGer_TauJetEta2p17, this, 22.,20.,false);\n L1SeedFun[\"L1_IsoEG20er_Tau24er_dEta_Min0p2\"] = std::bind(&L1AlgoFactory::IsoEGer_TauJetEta2p17, this, 20.,24.,false);\n L1SeedFun[\"L1_IsoEG22er_IsoTau26er_dEta_Min0p2\"] = std::bind(&L1AlgoFactory::IsoEGer_TauJetEta2p17, this, 22.,26.,true);\n L1SeedFun[\"L1_IsoEG20er_IsoTau25er_dEta_Min0p2\"] = std::bind(&L1AlgoFactory::IsoEGer_TauJetEta2p17, this, 20.,25.,true);\n L1SeedFun[\"L1_IsoEG18er_IsoTau23er_dEta_Min0p2\"] = std::bind(&L1AlgoFactory::IsoEGer_TauJetEta2p17, this, 18.,23.,true);\n L1SeedFun[\"L1_IsoEG18er_IsoTau25er_dEta_Min0p2\"] = std::bind(&L1AlgoFactory::IsoEGer_TauJetEta2p17, this, 18.,25.,true);\n L1SeedFun[\"L1_IsoEG18er_IsoTau24er_dEta_Min0p2\"] = std::bind(&L1AlgoFactory::IsoEGer_TauJetEta2p17, this, 18.,24.,true);\n L1SeedFun[\"L1_DoubleMu6_EG6\"] = std::bind(&L1AlgoFactory::DoubleMu_EG, this, 6.,6.,true);\n L1SeedFun[\"L1_DoubleMu6_EG16\"] = std::bind(&L1AlgoFactory::DoubleMu_EG, this, 6.,16.,true); // l1t-tsg-v3: L1_DoubleMu6_EG6\n L1SeedFun[\"L1_DoubleMu7_EG7\"] = std::bind(&L1AlgoFactory::DoubleMu_EG, this, 7,7.,true);\n L1SeedFun[\"L1_DoubleMu7_EG14\"] = std::bind(&L1AlgoFactory::DoubleMu_EG, this, 7,14.,true); // l1t-tsg-v3: L1_DoubleMu7_EG7\n L1SeedFun[\"L1_Mu5_DoubleEG5\"] = std::bind(&L1AlgoFactory::Mu_DoubleEG, this, 5., 5.);\n L1SeedFun[\"L1_Mu6_DoubleEG10\"] = std::bind(&L1AlgoFactory::Mu_DoubleEG, this, 6., 10.);\n L1SeedFun[\"L1_Mu6_DoubleEG17\"] = std::bind(&L1AlgoFactory::Mu_DoubleEG, this, 6., 17.); // l1t-tsg-v3: L1_Mu6_DoubleEG10\n\n //MultiCross\n L1SeedFun[\"L1_Mu3_JetC16_dEta_Max0p4_dPhi_Max0p4\"] = std::bind(&L1AlgoFactory::Mu_JetCentral_delta, this, 3.,16.);\n L1SeedFun[\"L1_Mu3_JetC52_dEta_Max0p4_dPhi_Max0p4\"] = std::bind(&L1AlgoFactory::Mu_JetCentral_delta, this, 3.,52.);\n L1SeedFun[\"L1_Mu3_JetC60_dEta_Max0p4_dPhi_Max0p4\"] = std::bind(&L1AlgoFactory::Mu_JetCentral_delta, this, 3.,60.);\n L1SeedFun[\"L1_Mu3_JetC120_dEta_Max0p4_dPhi_Max0p4\"] = std::bind(&L1AlgoFactory::Mu_JetCentral_delta, this, 3.,120.);\n L1SeedFun[\"L1_DoubleJetC56_ETM60\"] = std::bind(&L1AlgoFactory::DoubleJetCentral_ETM, this, 56.,56.,60.);\n L1SeedFun[\"L1_DoubleJetC60_ETM60\"] = std::bind(&L1AlgoFactory::DoubleJetCentral_ETM, this, 60.,60.,60.);\n L1SeedFun[\"L1_DoubleJetC60_ETM70\"] = std::bind(&L1AlgoFactory::DoubleJetCentral_ETM, this, 60.,60.,70.);\n L1SeedFun[\"L1_DoubleEG6_HTT150\"] = std::bind(&L1AlgoFactory::DoubleEG_HT, this, 6., 150.);\n L1SeedFun[\"L1_DoubleEG6_HTT255\"] = std::bind(&L1AlgoFactory::DoubleEG_HT, this, 6., 255.); // l1t-tsg-v3: L1_DoubleEG6_HTT150\n L1SeedFun[\"L1_Jet32_DoubleMuOpen_Mu10_dPhi_Jet_Mu0_Max1p05_dPhi_Mu_Mu_Min1p0\"] = std::bind(&L1AlgoFactory::Jet_MuOpen_Mu_dPhiMuMu1, this, 32.,10., 0);\n L1SeedFun[\"L1_Jet32_DoubleMuOpen_Mu10_dPhi_Jet_Mu0_Max0p4_dPhi_Mu_Mu_Min1p0\"] = std::bind(&L1AlgoFactory::Jet_MuOpen_Mu_dPhiMuMu1, this, 32.,10., 0);\n L1SeedFun[\"L1_Jet32_DoubleMu_10_0_dPhi_Jet_Mu0_Max0p4_dPhi_Mu_Mu_Min1p0\"] = std::bind(&L1AlgoFactory::Jet_MuOpen_Mu_dPhiMuMu1, this, 32.,10., 1 );\n L1SeedFun[\"L1_Jet32_MuOpen_EG10_dPhi_Jet_Mu_Max1p05_dPhi_Mu_EG_Min1p05\"] = std::bind(&L1AlgoFactory::Jet_MuOpen_EG_dPhiMuEG1, this, 32.,10., 0);\n L1SeedFun[\"L1_Jet32_MuOpen_EG10_dPhi_Jet_Mu_Max0p4_dPhi_Mu_EG_Min1p0\"] = std::bind(&L1AlgoFactory::Jet_MuOpen_EG_dPhiMuEG1, this, 32.,10.,0);\n L1SeedFun[\"L1_Jet32_Mu0_EG10_dPhi_Jet_Mu_Max0p4_dPhi_Mu_EG_Min1p0\"] = std::bind(&L1AlgoFactory::Jet_MuOpen_EG_dPhiMuEG1, this, 32.,10.,1);\n L1SeedFun[\"L1_Jet32MuOpen_EG17_dPhiMu_EG1\"] = std::bind(&L1AlgoFactory::Jet_MuOpen_EG_dPhiMuEG1, this, 32.,17., 0); // l1t-tsg-v3: L1_Jet32MuOpen_EG10_dPhiMu_EG1\n L1SeedFun[\"L1_DoubleMu0_ETM40\"] = std::bind(&L1AlgoFactory::DoubleMu_ETM, this, 0, 0, 40, false); \n L1SeedFun[\"L1_DoubleMu0_ETM50\"] = std::bind(&L1AlgoFactory::DoubleMu_ETM, this, 0, 0, 50, false); \n L1SeedFun[\"L1_DoubleMu0_ETM55\"] = std::bind(&L1AlgoFactory::DoubleMu_ETM, this, 0, 0, 55, false); \n L1SeedFun[\"L1_DoubleMu0_ETM60\"] = std::bind(&L1AlgoFactory::DoubleMu_ETM, this, 0, 0, 60, false); \n L1SeedFun[\"L1_DoubleMu0_ETM65\"] = std::bind(&L1AlgoFactory::DoubleMu_ETM, this, 0, 0, 65, false); \n L1SeedFun[\"L1_DoubleMu0_ETM70\"] = std::bind(&L1AlgoFactory::DoubleMu_ETM, this, 0, 0, 70, false); \n L1SeedFun[\"L1_DoubleMu0_ETM75\"] = std::bind(&L1AlgoFactory::DoubleMu_ETM, this, 0, 0, 75, false); \n\n L1SeedFun[\"L1_DoubleJet8_ForwardBackward\"] = std::bind(&L1AlgoFactory::DoubleJet_ForwardBackward, this, 8., 8.); \n L1SeedFun[\"L1_DoubleJet12_ForwardBackward\"] = std::bind(&L1AlgoFactory::DoubleJet_ForwardBackward, this, 12., 12.); \n L1SeedFun[\"L1_DoubleJet16_ForwardBackward\"] = std::bind(&L1AlgoFactory::DoubleJet_ForwardBackward, this, 16., 16.); \n L1SeedFun[\"L1_ETM60_Jet60_dPhi_Min0p4\"] = std::bind(&L1AlgoFactory::ETM_Jet, this, 60., 60., false); \n L1SeedFun[\"L1_ETM70_Jet60_dPhi_Min0p4\"] = std::bind(&L1AlgoFactory::ETM_Jet, this, 70., 60., false); \n L1SeedFun[\"L1_ETM75_Jet60_dPhi_Min0p4\"] = std::bind(&L1AlgoFactory::ETM_Jet, this, 75., 60., false); \n L1SeedFun[\"L1_ETM85_Jet60_dPhi_Min0p4\"] = std::bind(&L1AlgoFactory::ETM_Jet, this, 85., 60., false); \n L1SeedFun[\"L1_HTM60_HTT260\"] = std::bind(&L1AlgoFactory::HTM_HTT, this, 60., 260.); \n L1SeedFun[\"L1_HTM80_HTT220\"] = std::bind(&L1AlgoFactory::HTM_HTT, this, 80., 220.); \n L1SeedFun[\"L1_Mu3_JetC35\"] = std::bind(&L1AlgoFactory::Mu_Jet, this, 3., 35., false, true); \n L1SeedFun[\"L1_Mu3_JetC16\"] = std::bind(&L1AlgoFactory::Mu_Jet, this, 3., 16., false, true); \n L1SeedFun[\"L1_Mu3_JetC60\"] = std::bind(&L1AlgoFactory::Mu_Jet, this, 3., 60., false, true); \n L1SeedFun[\"L1_Mu3_JetC120\"] = std::bind(&L1AlgoFactory::Mu_Jet, this, 3., 120., false, true); \n L1SeedFun[\"L1_MU20_EG15\"] = std::bind(&L1AlgoFactory::Mu_EG, this,20, 15, false, 2);\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Mass Trigger ~~~~~\n L1SeedFun[\"L1_DoubleJet_90_30_Mj30j30_580\"] = std::bind(&L1AlgoFactory::DoubleJetMass, this, 90, 30., false, 30, 30, false, 580); \n L1SeedFun[\"L1_DoubleJet_90_50_Mj30j30_580\"] = std::bind(&L1AlgoFactory::DoubleJetMass, this, 90, 50., false, 30, 30, false, 580); \n L1SeedFun[\"L1_DoubleJet_90_60_Mj30j30_580\"] = std::bind(&L1AlgoFactory::DoubleJetMass, this, 90, 60., false, 30, 30, false, 580); \n L1SeedFun[\"L1_DoubleJet_90_70_Mj30j30_580\"] = std::bind(&L1AlgoFactory::DoubleJetMass, this, 90, 70., false, 30, 30, false, 580); \n L1SeedFun[\"L1_DoubleJet_90_80_Mj30j30_580\"] = std::bind(&L1AlgoFactory::DoubleJetMass, this, 90, 80., false, 30, 30, false, 580); \n L1SeedFun[\"L1_DoubleJet_90_90_Mj30j30_580\"] = std::bind(&L1AlgoFactory::DoubleJetMass, this, 90, 90., false, 30, 30, false, 580); \n L1SeedFun[\"L1_DoubleJet_90_30_Mj30j30_580\"] = std::bind(&L1AlgoFactory::DoubleJetMass, this, 90, 30., false, 30, 30, false, 580); \n L1SeedFun[\"L1_DoubleJet_90_30_Mj30j30_610\"] = std::bind(&L1AlgoFactory::DoubleJetMass, this, 90, 30., false, 30, 30, false, 610); \n L1SeedFun[\"L1_DoubleJet_90_30_Mj30j30_640\"] = std::bind(&L1AlgoFactory::DoubleJetMass, this, 90, 30., false, 30, 30, false, 640); \n L1SeedFun[\"L1_DoubleJet_90_30_Mj30j30_670\"] = std::bind(&L1AlgoFactory::DoubleJetMass, this, 90, 30., false, 30, 30, false, 670); \n L1SeedFun[\"L1_DoubleJet_90_30_Mj30j30_700\"] = std::bind(&L1AlgoFactory::DoubleJetMass, this, 90, 30., false, 30, 30, false, 700); \n L1SeedFun[\"L1_DoubleJet_90_30_Mj30j30_730\"] = std::bind(&L1AlgoFactory::DoubleJetMass, this, 90, 30., false, 30, 30, false, 730); \n L1SeedFun[\"L1_DoubleJet_90_30_Mj30j30_760\"] = std::bind(&L1AlgoFactory::DoubleJetMass, this, 90, 30., false, 30, 30, false, 760); \n\n\n L1SeedFun[\"L1_DoubleJet30_Mj30j30_360_Mu6\"] = std::bind(&L1AlgoFactory::DoubleJetMass_Mu, this, 30, 30., false, 30, 30, false, 360, 6, false, 2); \n L1SeedFun[\"L1_DoubleJet30_Mj30j30_360_Mu10\"] = std::bind(&L1AlgoFactory::DoubleJetMass_Mu, this, 30, 30., false, 30, 30, false, 360, 10, false, 2); \n L1SeedFun[\"L1_DoubleJet_40_30_Mj40j30_540_IsoEG12\"] = std::bind(&L1AlgoFactory::DoubleJetMass_Mu, this, 40, 30., false, 40, 30, false, 540, 12, true, false); \n\n L1SeedFun[\"L1_ZeroBias\"] = [](){return true;};\n return true;\n\n} // ----- end of function L1Menu2016::InitConfig -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::BookHistogram\n// Description: \n// ===========================================================================\nbool L1Menu2016::BookHistogram()\n{\n for(auto col : ColumnMap)\n {\n col.second->BookHistogram();\n }\n return true;\n} // ----- end of function L1Menu2016::BookHistogram -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::WriteHistogram\n// Description: \n// ===========================================================================\nbool L1Menu2016::WriteHistogram() \n{\n for(auto col : ColumnMap)\n {\n col.second->WriteHistogram(outrootfile);\n }\n return true;\n} // ----- end of function L1Menu2016::WriteHistogram -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ReadMenu\n// Description: /* cursor */\n// ===========================================================================\nbool L1Menu2016::ReadMenu()\n{\n mL1Seed.clear();\n vL1Seed.clear();\n\n //Read the prescales table\n std::ifstream menufile(menufilename);\n if (!menufile)\n {\n std::cout << \"MenuFile \"<<menufilename<<\" is not found !\"<<std::endl;\n return false;\n }\n\n if (writefiles)\n *outfile << \"---------------------------- Input Menu -------------------------\" << std::endl;\n\n if (menufilename.find_last_of(\"txt\")!= std::string::npos)\n ReadMenuTXT(menufile);\n else if (menufilename.find_last_of(\"csv\")!= std::string::npos)\n ReadMenuCSV(menufile);\n else\n {\n std::cout << \"Can not understand MenuFile \"<<menufilename<<\"! Please provide TXT or CSV format.\"<<std::endl;\n return false;\n }\n\n if (writefiles)\n *outfile << \"---------------------------- Input Menu -------------------------\" <<std::endl << std::endl;\n\n return true;\n} // ----- end of function L1Menu2016::ReadMenu -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ReadMenuTXT\n// Description: \n// ===========================================================================\nbool L1Menu2016::ReadMenuTXT(std::ifstream &menufile)\n{\n std::string line;\n\n while (std::getline(menufile, line))\n {\n if (line.empty()) continue;\n if (writefiles)\n *outfile << line <<std::endl;\n if (line.at(0) == '#')\n continue;\n if (line.at(0) == '%')\n {\n std::cout << \"Parsing config from menu: \" << line << std::endl;\n ParseConfig(line);\n continue;\n }\n\n std::size_t commentpos = line.find_first_of(\"#\");\n std::string goodline = \"\";\n std::string comline = \"\";\n\n if (commentpos != std::string::npos)\n {\n goodline = line.substr(0, commentpos);\n comline = line.substr(commentpos, line.length() - commentpos);\n }\n else\n goodline = line;\n std::istringstream iss(goodline);\n\n std::string seed;\n int bit;\n int prescale;\n std::string pog, pag;\n\n iss >> seed >> bit >> prescale >> pog >> pag;\n\n //~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Form L1Seed ~~~~~\n L1Seed temp;\n temp.name = seed;\n vL1Seed.push_back(seed);\n temp.bit = bit;\n temp.comment = comline;\n temp.prescale = prescale;\n\n if (L1Config[\"doCompuGT\"] || L1Config[\"SetNoPrescale\"] )\n temp.prescale = 1;\n \n if (pog.length() != 0)\n temp.POG = TokenGroups(pog);\n if (pag.length() != 0)\n temp.PAG = TokenGroups(pag);\n mL1Seed[seed] = temp;\n }\n return true;\n} // ----- end of function L1Menu2016::ReadMenuTXT -----\n\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ReadMenuCSV\n// Description: To be finished\n// ===========================================================================\nbool L1Menu2016::ReadMenuCSV(std::ifstream &menufile)\n{\n // Get the first line\n std::string line;\n while (std::getline(menufile, line))\n {\n line.erase( std::remove(line.begin(), line.end(), '\\r'), line.end() );\n if (line.empty()) continue;\n if (line.find_first_not_of(\", \") == std::string::npos) continue;\n if (line.at(0) == '#')\n continue;\n break; // Get the first line\n }\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Getting the header ~~~~~\n boost::char_separator<char> sep(\",\");\n tokenizer tokens(line, sep);\n std::map<int, std::string> premap;\n std::map<int, std::string> infomap;\n int j = 0;\n for(auto i : tokens)\n {\n i.erase(std::remove_if(i.begin(), i.end(), ::isspace), i.end());\n try\n {\n boost::lexical_cast<double>(i);\n premap[j] = i;\n }\n catch (const boost::bad_lexical_cast &) {\n infomap[j] = i;\n };\n j++;\n }\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Select the prescale column ~~~~~\n int targetcol = -1;\n if (premap.size() == 0)\n {\n std::cout << \"No prescale column found in \" << menufilename<<\". Exiting\" << std::endl;\n exit(1);\n }\n\n if (premap.size() == 1)\n {\n targetcol = premap.begin()->first;\n }\n else{\n if (premap.size() > 1 && L1ConfigStr[\"SelectCol\"] == \"\")\n {\n std::cout << \"Select prescale columns from: \";\n for(const auto &i : premap)\n std::cout << i.second <<\", \";\n std::cout << std::endl;\n exit(1);\n }\n\n for(const auto &i : premap)\n {\n if (i.second == L1ConfigStr[\"SelectCol\"] )\n {\n targetcol = i.first;\n break;\n }\n }\n if (targetcol == -1)\n {\n std::cout << \"Can not find \" << L1ConfigStr[\"SelectCol\"] <<\" in \";\n for(const auto &i : premap)\n std::cout << i.second <<\", \";\n std::cout <<\"Exiting\" << std::endl;\n exit(1);\n }\n }\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Finally reading in the menu ~~~~~\n std::vector<int> outidx;\n std::stringstream ss;\n ss << std::left;\n infomap[targetcol] = \"Prescale\";\n for(const auto &k : infomap)\n {\n tokenizer::iterator t = tokens.begin();\n std::advance(t, k.first);\n std::string it = std::regex_replace(*t, std::regex(\"^ +| +$|( ) +\"), \"$1\");\n ss << it <<\" \"; \n }\n if (writefiles)\n {\n assert(outfile != nullptr);\n *outfile << ss.str() <<std::endl;\n }\n\n while (std::getline(menufile, line))\n {\n line.erase( std::remove(line.begin(), line.end(), '\\r'), line.end() );\n if (line.empty()) continue;\n if (line.find_first_not_of(\", \") == std::string::npos) continue;\n if (line.at(0) == '#')\n continue;\n if (line.at(0) == '%')\n {\n std::cout << \"Parsing config from menu: \" << line << std::endl;\n ParseConfig(line);\n continue;\n }\n\n ss.str(\"\");\n L1Seed temp;\n\n tokenizer tokens(line, sep);\n for(const auto &k : infomap)\n {\n tokenizer::iterator t = tokens.begin();\n std::advance(t, k.first);\n std::string it = std::regex_replace(*t, std::regex(\"^ +|\\t+$| +$|( ) +\"), \"$1\");\n \n if (k.second == \"n\")\n {\n ss << std::setw(4) << it <<\" \"; \n try\n {\n temp.bit = boost::lexical_cast<int>(it);\n }\n catch (const boost::bad_lexical_cast &)\n {\n std::cout << \"Can't cast bit \" << it<< \" to int type in line: \" << line << std::endl;\n }\n }\n if (k.second == \"L1AlgoName\")\n {\n ss << std::setw(65) << it <<\" \"; \n temp.name = it;\n vL1Seed.push_back(it);\n }\n if (k.second == \"Prescale\")\n {\n ss << std::setw(5) << it <<\" \"; \n try\n {\n temp.prescale = boost::lexical_cast<int>(it);\n }\n catch (const boost::bad_lexical_cast &)\n {\n std::cout << \"Can't cast prescale \" << it<< \" to int type in line: \" << line << std::endl;\n }\n }\n if (k.second == \"Comment\")\n {\n\n ss << it <<\" \"; \n temp.comment = it;\n }\n if (k.second == \"POG\")\n {\n ss << std::setw(15) << it <<\" \"; \n temp.POG = TokenGroups(it);\n }\n if (k.second == \"PAG\")\n {\n ss << std::setw(15) << it <<\" \"; \n temp.PAG = TokenGroups(it);\n }\n\n if (L1Config[\"doCompuGT\"] || L1Config[\"SetNoPrescale\"] )\n temp.prescale = 1;\n }\n\n if (writefiles)\n *outfile << ss.str() <<std::endl;\n mL1Seed[temp.name] = temp;\n }\n\n return true;\n} // ----- end of function L1Menu2016::ReadMenuCSV -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::FormPrescaleColumns\n// Description: \n// ===========================================================================\nbool L1Menu2016::FormPrescaleColumns()\n{\n std::vector<std::string> VarSeeds;\n for(auto &seed : mL1Seed)\n {\n if (seed.second.prescale < 0)\n {\n VarSeeds.push_back(seed.first);\n std::cout << \"Varing \" << seed.first << std::endl;\n }\n }\n \n const int varSize = VarSeeds.size();\n int varCounts = 1 << varSize;\n for (int i = 0; i < varCounts; ++i)\n {\n std::map<std::string, L1Seed> tempL1Seed = mL1Seed;\n for (int j = 0; j < varSize; ++j)\n {\n tempL1Seed.at(VarSeeds.at(j)).prescale = (i & 1 << j) > 0 ; \n }\n ColumnMap[i] = new PreColumn(i, tempL1Seed);\n ColumnMap[i]->PassRelation( vL1Seed, BitMap, POGMap, PAGMap);\n }\n\n std::cout << \"In total ColumnMap \"<< ColumnMap.size() << std::endl;\n return true;\n} // ----- end of function L1Menu2016::FormPrescaleColumns -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ReadFilelist\n// Description: \n// ===========================================================================\nbool L1Menu2016::OpenWithList(std::string filelist)\n{\n L1Ntuple::SelectTree(L1Config[\"UseUnpackTree\"]);\n if (filelist.find(\".root\") != std::string::npos)\n {\n L1Ntuple::Open(filelist);\n return false;\n }\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ OpenNtupleList ~~~~~\n\n std::ifstream flist(filelist.c_str());\n if (!flist)\n {\n std::cout << \"File \"<<filelist<<\" is not found !\"<<std::endl;\n return false;\n }\n\n std::string line;\n while (std::getline(flist, line))\n {\n if (line.empty()) continue;\n if (line.at(0) == '#')\n continue;\n if (line.at(0) == '%')\n {\n std::cout << \"Parsing config from ntuple list: \" << line << std::endl;\n ParseConfig(line);\n continue;\n }\n if (!flist.fail())\n {\n listNtuples.push_back(line);\n }\n }\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ OpenNtupleList ~~~~~\n if (!CheckFirstFile()) exit(0);\n if (!OpenWithoutInit()) exit(0);\n\n std::cout.flush();\n std::cout<<\"Going to init the available trees...\"<<std::endl;\n std::cout.flush();\n Init();\n\n return true;\n} // ----- end of function L1Menu2016::ReadFilelist -----\n\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ParseConfig\n// Description: \n// ===========================================================================\nbool L1Menu2016::ParseConfig(const std::string line)\n{\n if (line.find('=') == std::string::npos)\n {\n std::cout << \"Wrong config: \" << line << std::endl;\n return false;\n }\n\n std::istringstream iss(line);\n\n std::string key, sign;\n double value;\n\n iss >> sign >> key >> sign >> value;\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parse for double inputs ~~~~~\n bool parDouble = iss.fail();\n if (!parDouble && L1Config.find(key) != L1Config.end())\n {\n L1Config[key] = value;\n return true;\n }\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Parse for string inputs ~~~~~\n bool parString = true;\n std::istringstream isss(line);\n key=sign=\"\";\n std::string valstr=\"\";\n\n if (parDouble)\n {\n isss >> sign >> std::ws >> key >>std::ws >> sign >>std::ws >> valstr;\n parString = isss.fail();\n }\n\n if (!parString && L1ConfigStr.find(key) != L1ConfigStr.end())\n {\n L1ConfigStr[key] = valstr;\n return true;\n }\n\n if (parDouble && parString)\n std::cout<<\"\\033[0;31mCan't parse config:\\033[0m \"<<line<< std::endl; \n else\n std::cout << \"Not reconfiguzed config key \" << key<< std::endl;\n \n return false;\n} // ----- end of function L1Menu2016::ParseConfig -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::GetRunConfig\n// Description: Get the running time config from command line\n// ===========================================================================\nbool L1Menu2016::GetRunConfig(std::map<std::string, float> &config, \n std::map<std::string, std::string> &configstr)\n{\n\n for(auto c : config)\n {\n if (L1Config.find(c.first) != L1Config.end())\n {\n L1Config[c.first] = c.second;\n }\n }\n\n for(auto c : configstr)\n {\n if (L1ConfigStr.find(c.first) != L1ConfigStr.end())\n {\n L1ConfigStr[c.first] = c.second;\n }\n }\n return true;\n} // ----- end of function L1Menu2016::GetRunConfig -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::PrintConfig\n// Description: \n// ===========================================================================\nbool L1Menu2016::PrintConfig() const\n{\n std::cout << \"Printing configuration ___________________________ \" << std::endl;\n for(auto &x: L1Config)\n std::cout << std::setw(20) <<x.first <<\" : \" << x.second << std::endl;\n for(auto &x: L1ConfigStr)\n std::cout << std::setw(20) <<x.first <<\" : \" << x.second << std::endl;\n std::cout << \"Printed configuration ============================ \" << std::endl;\n return true;\n} // ----- end of function L1Menu2016::PrintConfig -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::PreLoop\n// Description: \n// ===========================================================================\nbool L1Menu2016::PreLoop(std::map<std::string, float> &config, std::map<std::string, std::string> &configstr)\n{\n GetRunConfig(config, configstr);\n OpenWithList(tuplefilename);\n\n //Prepare Menu\n std::cout << \"Preparing menus __________________________________ \" << std::endl;\n ReadMenu();\n BuildRelation();\n L1SeedFunc();\n FormPrescaleColumns();\n\n PrintConfig();\n BookHistogram();\n \n if (writeplots)\n {\n GlobalAlgBlk *l1uGTsel_ = l1uGT_;\n TChain *fl1uGTsel = fl1uGT;\n \n if (L1Config[\"UseUnpackTree\"]){\n l1uGTsel_ = l1unpackuGT_;\n fl1uGTsel = fl1unpackuGT; \n }\n \n l1Plot = new L1Plot(outrootfile, event_, upgrade_, recoJet_,\n\t\t\trecoSum_, recoEle_, recoMuon_, recoTau_, recoFilter_, l1CaloTower_, recoVtx_, l1uGTsel_);\n l1Plot->SetTodo(L1Config);\n l1Plot->PreRun(&L1Event, &mL1Seed, L1Ntuple::GetuGTAlias(fl1uGTsel));\n }\n\n if (L1Config[\"doPrintPU\"])\n {\n ReadDataPU();\n }\n \n if (L1Config[\"doTnPMuon\"])\n {\n l1TnP = new L1TnP(outrootfile, event_, upgrade_, recoJet_,\n\t\t recoSum_, recoEle_, recoMuon_, recoTau_, recoFilter_, l1CaloTower_, recoVtx_, l1uGT_);\n if (L1Config[\"doTnPMuon\"])\n l1TnP->DoMuonTnP();\n }\n\n if (l1unpackuGT_ != NULL)\n {\n l1unpackuGT = new L1uGT( outrootfile, event_, l1unpackuGT_, &L1Event, &mL1Seed);\n l1unpackuGT->GetTreeAlias(L1Ntuple::GetuGTAlias(fl1unpackuGT));\n }\n\n if (L1Config[\"doCompuGT\"] || L1Config[\"UseuGTDecision\"] || L1Config[\"doPlotuGt\"])\n {\n assert(l1uGT_ != NULL);\n l1uGT = new L1uGT( outrootfile, event_, l1uGT_, &L1Event, &mL1Seed);\n l1uGT->GetTreeAlias(L1Ntuple::GetuGTAlias(fl1uGT));\n }\n\n\n if (L1Config[\"SetMuonER\"] != -1) SetMuonER(L1Config[\"SetMuonER\"]);\n if (L1Config[\"UseUpgradeLyr1\"] != -1) SetUseUpgradeLyr1(L1Config[\"UseUpgradeLyr1\"]);\n if (L1Config[\"UseL1CaloTower\"] != -1) SetUseL1CaloTower(L1Config[\"UseL1CaloTower\"]);\n\n if (L1ConfigStr[\"SelectLS\"] != \"\") \n ParseRanges(\"SelectLS\", pLS);\n\n if (L1ConfigStr[\"SelectBX\"] != \"\") \n ParseRanges(\"SelectBX\", pBX);\n return true;\n} // ----- end of function L1Menu2016::PreLoop -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::GetL1Event\n// Description: \n// ===========================================================================\nbool L1Menu2016::GetL1Event()\n{\n L1Event = {};\n\n //Jet\n L1AlgoFactory::SingleJetPt(L1Event.JetPt,false);\n L1AlgoFactory::SingleJetPt(L1Event.JetCenPt,true);\n\n //EG\n L1AlgoFactory::SingleEGPt(L1Event.EGPt,false, false);\n L1AlgoFactory::SingleEGPt(L1Event.EGerPt,false, true);\n L1AlgoFactory::SingleEGPt(L1Event.IsoEGPt,true, false);\n L1AlgoFactory::SingleEGPt(L1Event.IsoEGerPt,true, true);\n\n //Tau\n L1AlgoFactory::SingleTauPt(L1Event.TauPt, false, false); \n L1AlgoFactory::SingleTauPt(L1Event.TauerPt, true, false);\n L1AlgoFactory::SingleTauPt(L1Event.IsoTauPt, false, true);\n\n //Mu\n L1AlgoFactory::SingleMuPt(L1Event.MuPt, false, 2);\n L1AlgoFactory::SingleMuPt(L1Event.MuOpenPt, false, 0);\n L1AlgoFactory::SingleMuPt(L1Event.MuerPt, true, 2);\n\n //Sum\n if (L1Config[\"SumJetET\"] != 0 || L1Config[\"SumJetEta\"] != 999)\n {\n CalLocalHT(L1Event.HTT, false);\n CalLocalHT(L1Event.HTTHF, true);\n CalLocalHTM(L1Event.HTM);\n } else {\n L1AlgoFactory::HTTVal(L1Event.HTT);\n L1AlgoFactory::HTTHFVal(L1Event.HTTHF); // Not in L1Ntuple yet\n L1AlgoFactory::HTMVal(L1Event.HTM);\n }\n\n if (L1Config[\"UseL1CaloTower\"])\n {\n CalLocalETM(L1Event.ETM, false);\n CalLocalETM(L1Event.ETMHF, true);\n }\n else\n {\n L1AlgoFactory::ETMVal(L1Event.ETM);\n L1AlgoFactory::ETMHFVal(L1Event.ETMHF);\n }\n\n L1AlgoFactory::ETTVal(L1Event.ETT);\n\n // Mulit\n float dummy = 0;\n L1AlgoFactory::DoubleMuPt(L1Event.doubleMuPt1,L1Event.doubleMuPt2, true, false);\n L1AlgoFactory::Onia2015Pt(L1Event.oniaMuPt1, L1Event.oniaMuPt2,true, false, 18);\n L1AlgoFactory::DoubleJetPt(L1Event.dijetPt1,L1Event.dijetPt2);\n L1AlgoFactory::DoubleJetPt(L1Event.diCenjetPt1,L1Event.diCenjetPt2,true);\n L1AlgoFactory::DoubleTauJetEta2p17Pt(dummy,L1Event.ditauPt, false);\n L1AlgoFactory::DoubleTauJetEta2p17Pt(dummy,L1Event.diIsotauPt, true);\n L1AlgoFactory::QuadJetPt(dummy,dummy,dummy,L1Event.quadjetPt);\n L1AlgoFactory::QuadJetPt(dummy,dummy,dummy,L1Event.quadjetCPt,true);\n L1AlgoFactory::DoubleEGPt(L1Event.diEG1,L1Event.diEG2,false);\n L1AlgoFactory::DoubleEGPt(L1Event.diIsolEG1,L1Event.diIsolEG2,true);\n\n return true;\n} // ----- end of function L1Menu2016::GetL1Event -----\n// === FUNCTION ============================================================\n// Name: L1Menu2016::Loop\n// Description: \n// ===========================================================================\nbool L1Menu2016::Loop()\n{\n ////~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Initial ~~~~~\n //Int_t nevents = fChain->GetEntriesFast();//GetEntries();\n unsigned int currentLumi(-1);\n nZeroBiasevents = 0.;\n int i = -1;\n nLumi.clear();\n bool skipLS = false;\n\n while(true)\n {\n i++;\n Long64_t ientry = LoadTree(i); \n if (ientry < 0) break;\n GetEntry(i);\n if (L1Config[\"maxEvent\"] != -1 && i > L1Config[\"maxEvent\"]) break;\n\n if (event_ != NULL )\n {\n if (L1Config[\"SelectRun\"] != -1 && event_->run != L1Config[\"SelectRun\"])\n continue;\n\n if (L1Config[\"SelectEvent\"] != -1 && event_->event != L1Config[\"SelectEvent\"])\n continue;\n\n if(event_ -> lumi != currentLumi){\n currentLumi = event_ -> lumi;\n skipLS = CheckLS(currentLumi);\n if (!skipLS)\n nLumi.insert(currentLumi);\n } \n\n if (L1ConfigStr[\"SelectLS\"] != \"\" && skipLS)\n continue;\n\n if (L1ConfigStr[\"SelectBX\"] != \"\" && CheckBX(event_->bx) )\n continue;\n\n if (L1Config[\"doScanLS\"])\n continue;\n }\n\n if (i % 200000 == 0)\n {\n std::cout << \"Processed \" << i << \" events.\" << std::endl;\n }\n\n //Use Final decision by default, unless for PlotLS\n if (l1unpackuGT != NULL && !l1unpackuGT->GetuGTDecision(\"L1_ZeroBias\", L1Config[\"doPlotLS\"])) \n continue;\n\n nZeroBiasevents++;\n\n GetL1Event();\n RunMenu();\n\n if (L1Config[\"doPlotLS\"])\n FillLumiSection(currentLumi);\n\n if (L1Config[\"doPrintPU\"] && event_ != NULL)\n FillPileUpSec();\n\n if (l1Plot != NULL)\n l1Plot->RunPlot();\n\n if (l1TnP != NULL)\n l1TnP->RunTnP();\n\n if (L1Config[\"doCompuGT\"])\n l1uGT->CompEvents();\n }\n\n std::cout << \"Total Event: \" << i <<\" ZeroBias Event: \" << nZeroBiasevents << std::endl;\n return true;\n} // ----- end of function L1Menu2016::Loop -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::PostLoop\n// Description: \n// ===========================================================================\nbool L1Menu2016::PostLoop()\n{\n scale = CalScale(0, 0, true);\n\n std::cout << \"==================================== Summary\" << std::endl;\n\n for(auto col : ColumnMap)\n {\n col.second->CalRate(scale);\n col.second->FillDefHist1D(scale);\n col.second->FillDefHist2D(scale);\n }\n \n if (ColumnMap.size() == 1)\n PrintRates(std::cout);\n else{\n for(auto col : ColumnMap)\n col.second->PrintMenuRate(scale);\n }\n if (writefiles)\n PrintRates(*outfile);\n PrintCSV(*outcsv);\n\n if (l1Plot != NULL)\n {\n l1Plot->PostRun(scale);\n if (L1Config[\"doPlotLS\"])\n l1Plot->PlotRatePerLS(L1LSCount, L1Config[\"nBunches\"]);\n }\n\n if (l1TnP != NULL)\n l1TnP->PostRun();\n\n if (L1Config[\"doPrintPU\"])\n {\n PrintPUCSV();\n }\n WriteHistogram();\n return true;\n} // ----- end of function L1Menu2016::PostLoop -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::PrintPUCSV\n// Description: \n// ===========================================================================\nbool L1Menu2016::PrintPUCSV()\n{\n //const int nBunches = 2736;\n std::fstream pucsv (outputdir + \"/\" + outputname+\"_PU\" +\".csv\", std::fstream::out );\n\n // L1Seeds\n std::vector<std::string> csvout;\n for(auto col : ColumnMap)\n {\n col.second->PrintPUCSV(csvout);\n }\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Writing out to file ~~~~~\n for(auto i : csvout)\n {\n pucsv << i <<std::endl;\n }\n pucsv.close();\n\n return true;\n} // ----- end of function L1Menu2016::PrintPUCSV -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::PrintRates\n// Description: \n// ===========================================================================\nbool L1Menu2016::PrintRates(std::ostream &out)\n{\n for(auto col : ColumnMap)\n {\n col.second->PrintRates(out, scale);\n }\n return true;\n} // ----- end of function L1Menu2016::PrintRates -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::BuildRelation\n// Description: \n// ===========================================================================\nbool L1Menu2016::BuildRelation()\n{\n int misbit= -1;\n for(auto &l1 : mL1Seed)\n {\n\n // bit\n if (BitMap.find(l1.second.bit) != BitMap.end())\n {\n std::cout << \"Duplicate bit number at \" << l1.second.bit <<\" for \" \n << BitMap[l1.second.bit] <<\" and \" << l1.first \n << \"; setting \" << l1.first << \" to bit \" << misbit << std::endl;\n l1.second.bit = misbit;\n BitMap[l1.second.bit] = l1.first;\n misbit--;\n } else BitMap[l1.second.bit] = l1.first;\n\n for(auto &pog : l1.second.POG)\n {\n if (POGMap.find(pog) != POGMap.end())\n {\n POGMap[pog] = {};\n assert(POGMap[pog].size() == 0);\n } else POGMap[pog].push_back(l1.second.bit);\n }\n\n for(auto &pag : l1.second.PAG)\n {\n if (PAGMap.find(pag) != PAGMap.end())\n {\n PAGMap[pag] = {};\n assert(PAGMap[pag].size() == 0);\n } else PAGMap[pag].push_back(l1.second.bit);\n }\n }\n\n return true;\n} // ----- end of function L1Menu2016::BuildRelation -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::L1SeedFunc\n// Description: \n// ===========================================================================\nbool L1Menu2016::L1SeedFunc()\n{\n#ifdef UTM_MENULIB\n addFuncFromName(L1SeedFun, upgrade_);\n#endif\n \n for(auto &L1Seed : mL1Seed)\n {\n if (L1SeedFun.find(L1Seed.first) != L1SeedFun.end())\n continue;\n\n if(ParseL1Seed(L1Seed.first))\n continue;\n\n std::cout << \"No function call for \" << L1Seed.first <<\"; setting to no fire\"<< std::endl;\n }\n\n return true;\n} // ----- end of function L1Menu2016::L1SeedFunc -----\n\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::CheckL1Seed\n// Description: /* cursor */\n// ===========================================================================\nbool L1Menu2016::CheckL1Seed(const std::string L1Seed)\n{\n if (L1SeedFun.find(L1Seed) != L1SeedFun.end())\n {\n return L1SeedFun[L1Seed]();\n }\n return false;\n} // ----- end of function L1Menu2016::CheckL1Seed -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::RunMenu\n// Description: \n// ===========================================================================\nbool L1Menu2016::RunMenu()\n{\n for(auto col : ColumnMap)\n {\n col.second->EventReset();\n }\n\n for(auto& seed: mL1Seed)\n {\n bool IsFired = false;\n if (L1Config[\"UseuGTDecision\"])\n {\n assert(l1uGT != NULL);\n IsFired = l1uGT->GetuGTDecision(seed.first);\n }\n else\n IsFired = CheckL1Seed(seed.first);\n \n for(auto col : ColumnMap)\n {\n col.second->InsertInMenu(seed.first, IsFired);\n seed.second.eventfire = IsFired;\n }\n }\n\n for(auto col : ColumnMap)\n {\n col.second->CheckCorrelation();\n }\n\n return true;\n} // ----- end of function L1Menu2016::RunMenu -----\n\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::CalScale\n// Description: \n// ===========================================================================\ndouble L1Menu2016::CalScale(int nEvents_, int nBunches_, bool print) \n{\n double scale = 0.0;\n int nEvents = nEvents_ == 0 ? nZeroBiasevents : nEvents_;\n double nBunches = nBunches_ == 0 ? L1Config[\"nBunches\"] : nBunches_;\n\n if (L1Config[\"nBunches\"] < 0)\n {\n scale = (-1.*L1Config[\"nBunches\"])/(nLumi.size()*23.31); \n if (print)\n std::cout << \"Scale by \" << \"(\"<< -1. * L1Config[\"nBunches\"] <<\")/(nLumi*23.31) with nLumi = \" << nLumi.size() << std::endl;\n } else {\n scale = 11246.; // ZB per bunch in Hz\n //scale /= nZeroBiasevents*1000.; // in kHz\n scale /= nEvents; // in Hz\n scale *= nBunches;\n if (print)\n std::cout << \"Scale by \" << \" 11246 / nZeroBiasevents * NumberOfBunches, with nZeroBiasevents = \" \n << nEvents <<\" NumberOfBunches = \" << nBunches << std::endl;\n }\n return scale;\n} // ----- end of function L1Menu2016::CalScale -----\n\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::SetOutputName\n// Description: \n// ===========================================================================\nstd::string L1Menu2016::SetOutputName() const\n{\n boost::filesystem::path menupath(menufilename);\n boost::filesystem::path flistpath(tuplefilename);\n std::stringstream ss;\n ss << menupath.stem().string() << \"-\" << flistpath.stem().string();\n return ss.str();\n} // ----- end of function L1Menu2016::SetOutputName -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ParseL1Seed\n// Description: \n// ===========================================================================\nbool L1Menu2016::ParseL1Seed(const std::string SeedName)\n{\n if (SeedName.find(\"L1_\") == std::string::npos)\n {\n return false;\n }\n\n if (ParseSingleObject(SeedName)) return true;\n\n // Jets\n if (ParseDoubleJet(SeedName)) return true;\n if (ParseTripleJetVBF(SeedName)) return true;\n if (ParseQuadJet(SeedName)) return true;\n // EG\n if (ParseDoubleEG(SeedName)) return true;\n if (ParseTripleEG(SeedName)) return true;\n // Tau\n if (ParseDoubleTau(SeedName)) return true;\n\n // Mu_Tau\n if (ParseMuerTauer(SeedName)) return true;\n // Mu_EG\n if (ParseMuEG(SeedName)) return true;\n // Mu_Sum\n if (ParseMuSum(SeedName)) return true;\n\n // EG_Sum\n if (ParseEGSum(SeedName)) return true;\n\n if (ParseEGStrategy(SeedName)) return true;\n\n if (ParseETMJetdPhi(SeedName)) return true;\n\n if (ParseComplexSingleMu(SeedName)) return true;\n // EGMass\n //if (ParseMultiEGMass(SeedName)) return true;\n\n return false;\n} // ----- end of function L1Menu2016::ParseL1Seed -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ParseSingleObject\n// Description: /* cursor */\n// ===========================================================================\nbool L1Menu2016::ParseSingleObject(const std::string SeedName)\n{\n std::string L1object =\"\";\n std::string postfix = \"\";\n int pt = -10;\n\n boost::char_separator<char> sep(\"_\");\n tokenizer tokens(SeedName, sep);\n if (std::distance(tokens.begin(), tokens.end()) < 2) return false;\n boost::tokenizer<boost::char_separator<char> >::iterator tokenit = tokens.begin();\n tokenit++;\n std::string Seedtoken(*tokenit);\n\n std::smatch base_match;\n std::regex integerobj(\"Single([^0-9]+)([0-9]+)([^0-9]*)\");\n std::regex integerSum(\"(ETM|HTT|ETT|HTM)([0-9]+)\");\n if (std::regex_match(Seedtoken, base_match, integerobj))\n {\n\t// The first sub_match is the whole string; the next\n\t// sub_match is the first parenthesized expression.\n L1object = base_match[1].str();\n pt = std::stoi(base_match[2].str(), nullptr);\n postfix = base_match[3].str();\n }else if (std::regex_match(Seedtoken, base_match, integerSum))\n {\n\t// The first sub_match is the whole string; the next\n\t// sub_match is the first parenthesized expression.\n L1object = base_match[1].str();\n pt = std::stoi(base_match[2].str(), nullptr);\n postfix = \"\";\n } else if(Seedtoken == \"SingleMuOpen\")\n {\n L1object = \"Mu\";\n postfix = \"Open\";\n pt = 0;\n }\n \n\n L1object += postfix;\n mL1Seed[SeedName].singleObj = L1object;\n std::vector<std::function<bool()>> funs;\n\n //std::cout << std::distance(tokenit, tokens.end())<< std::endl;\n if (std::distance(tokenit, tokens.end()) > 1) \n {\n tokenit++;\n Seedtoken = *tokenit;\n if (Seedtoken == \"NotBptxOR\" || Seedtoken == \"BptxAND\")\n {\n funs.push_back(ParseBptx(Seedtoken));\n }\n else return false;\n }\n\n if (L1ObjectMap.find(L1object) != L1ObjectMap.end())\n {\n //funs.push_back(std::bind(&SingleObjPt, L1ObjectMap[L1object], pt));\n // No idea for the funs vector \n L1SeedFun[SeedName] = std::bind(&SingleObjPt, L1ObjectMap[L1object], pt);\n } else return false;\n\n return true;\n} // ----- end of function L1Menu2016::ParseSingleObject -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ParseBptx\n// Description: /* cursor */\n// ===========================================================================\nstd::function<bool()> L1Menu2016::ParseBptx(const std::string /*Seedtoken*/)\n{\n return [](){return true;};\n} // ----- end of function L1Menu2016::ParseBptx -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ParseDoubleJet\n// Description: \n// ===========================================================================\nbool L1Menu2016::ParseDoubleJet(const std::string& SeedName)\n{\n std::smatch base_match;\n std::regex integer(\"L1_DoubleJet([C]*)([0-9]+)\");\n if (std::regex_match(SeedName, base_match, integer))\n {\n bool isCentral = base_match.length(1) == 1;\n unsigned int pt = std::stoi(base_match[2].str(), nullptr);\n L1SeedFun[SeedName] = std::bind(&L1AlgoFactory::DoubleJet, this, pt, pt, isCentral);\n return true;\n }\n else return false;\n} // ----- end of function L1Menu2016::ParseDoubleJet -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ParseDoubleTau\n// Description: /* cursor */\n// ===========================================================================\nbool L1Menu2016::ParseDoubleTau(const std::string& SeedName) \n{\n std::smatch base_match;\n std::regex integer(\"L1_Double(Iso|)Tau([0-9]+)er\");\n if (std::regex_match(SeedName, base_match, integer))\n {\n bool isIso = base_match.length(1) == 3;\n unsigned int pt = std::stoi(base_match[2].str(), nullptr);\n L1SeedFun[SeedName] = std::bind(&L1AlgoFactory::DoubleTauJetEta2p17, this, pt, pt, isIso);\n return true;\n }\n else return false;\n} // ----- end of function L1Menu2016::ParseDoubleTau -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ParseTripleJetVBF\n// Description: \n// ===========================================================================\nbool L1Menu2016::ParseTripleJetVBF(const std::string& SeedName)\n{\n const int jetclass = 0; \n std::smatch base_match;\n std::regex integer(\"L1_TripleJet_([0-9]+)_([0-9]+)_([0-9]+)_VBF\");\n if (std::regex_match(SeedName, base_match, integer))\n {\n L1SeedFun[SeedName] = std::bind(&L1AlgoFactory::TripleJet_VBF, this, \n std::stoi(base_match[1].str(), nullptr),\n std::stoi(base_match[2].str(), nullptr),\n std::stoi(base_match[3].str(), nullptr), jetclass);\n return true;\n }\n else return false;\n} // ----- end of function L1Menu2016::ParseTripleJetVBF -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ParseQuadJet\n// Description: \n// ===========================================================================\nbool L1Menu2016::ParseQuadJet(const std::string& SeedName)\n{\n int pt1 = -10;\n int pt2 = -10;\n int pt3 = -10;\n int pt4 = -10;\n bool isCentral = false;\n\n std::smatch base_match;\n std::regex integer_sys(\"L1_QuadJet([C]*)([0-9]+)\");\n std::regex integer_asys(\"L1_QuadJet([C]*)_([0-9]+)_([0-9]+)_([0-9]+)_([0-9]+)\");\n if (std::regex_match(SeedName, base_match, integer_sys))\n {\n isCentral = base_match.length(1) == 1;\n pt1 = std::stoi(base_match[2].str(), nullptr);\n pt2 = pt3 = pt4 = pt1;\n } else if (std::regex_match(SeedName, base_match, integer_asys))\n {\n isCentral = base_match.length(1) == 1;\n pt1 = std::stoi(base_match[2].str(), nullptr);\n pt2 = std::stoi(base_match[3].str(), nullptr);\n pt3 = std::stoi(base_match[4].str(), nullptr);\n pt4 = std::stoi(base_match[5].str(), nullptr);\n }\n\n if (pt1 != -10 && pt2 != -10 && pt3 != -10 && pt4 != -10)\n {\n L1SeedFun[SeedName] = std::bind(&L1AlgoFactory::QuadJet, this, pt1, pt2, pt3, pt4, isCentral);\n return true;\n }\n else return false;\n} // ----- end of function L1Menu2016::ParseQuadJet -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ParseDoubleEG\n// Description: \n// ===========================================================================\nbool L1Menu2016::ParseDoubleEG(const std::string& SeedName)\n{\n int pt1 = -10;\n int pt2 = -10;\n bool isIso = false;\n\n std::smatch base_match;\n std::regex integer_sys(\"L1_Double(Iso|)EG([0-9]+)\");\n std::regex integer_asys(\"L1_Double(Iso|)EG_([0-9]+)_([0-9]+)\");\n if (std::regex_match(SeedName, base_match, integer_sys))\n {\n isIso = base_match.length(1) == 3;\n pt1 = std::stoi(base_match[2].str(), nullptr);\n pt2 = pt1;\n }else if (std::regex_match(SeedName, base_match, integer_asys))\n {\n isIso = base_match.length(1) == 3;\n pt1 = std::stoi(base_match[2].str(), nullptr);\n pt2 = std::stoi(base_match[3].str(), nullptr);\n }\n\n if (pt1 != -10 && pt2 != -10)\n {\n L1SeedFun[SeedName] = std::bind(&L1AlgoFactory::DoubleEG, this, pt1, pt2, isIso);\n return true;\n }\n else\n return false;\n} // ----- end of function L1Menu2016::ParseDoubleEG -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ParseTripleEG\n// Description: \n// ===========================================================================\nbool L1Menu2016::ParseTripleEG(const std::string& SeedName)\n{\n int pt1 = -10;\n int pt2 = -10;\n int pt3 = -10;\n\n std::smatch base_match;\n std::regex integer_sys(\"L1_TripleEG([0-9]+)\");\n std::regex integer_asys(\"L1_TripleEG_([0-9]+)_([0-9]+)_([0-9]+)\");\n if (std::regex_match(SeedName, base_match, integer_sys))\n {\n pt1 = std::stoi(base_match[1].str(), nullptr);\n pt2 = pt1;\n pt3 = pt1;\n }else if (std::regex_match(SeedName, base_match, integer_asys))\n {\n pt1 = std::stoi(base_match[1].str(), nullptr);\n pt2 = std::stoi(base_match[2].str(), nullptr);\n pt3 = std::stoi(base_match[3].str(), nullptr);\n }\n\n if (pt1 != -10 && pt2 != -10 && pt3 != -10)\n {\n L1SeedFun[SeedName] = std::bind(&L1AlgoFactory::TripleEG, this, pt1, pt2, pt3);\n return true;\n }\n else\n return false;\n} // ----- end of function L1Menu2016::ParseTripleEG -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ParseEGSum\n// Description: \n// ===========================================================================\nbool L1Menu2016::ParseEGSum(const std::string& SeedName)\n{\n int EGpt = -10;\n int Sumpt = -10;\n bool isIsoEG= false;\n\n std::smatch base_match;\n std::regex integerEGerHTT(\"L1_(Iso|)EG([0-9]+)er_HTT([0-9]+)\");\n if (std::regex_match(SeedName, base_match, integerEGerHTT))\n {\n isIsoEG = base_match.length(1) == 3;\n EGpt = std::stoi(base_match[2].str(), nullptr);\n Sumpt = std::stoi(base_match[3].str(), nullptr);\n L1SeedFun[SeedName] = std::bind(&L1AlgoFactory::SingleEG_Eta2p1_HTT, this, EGpt, Sumpt, isIsoEG);\n return true;\n }\n\n return false;\n} // ----- end of function L1Menu2016::ParseEGSum -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ParseEGStrategy\n// Description: \n// ===========================================================================\nbool L1Menu2016::ParseEGStrategy(const std::string & SeedName)\n{\n int pt = -10;\n\n std::smatch base_match;\n std::regex EGStrategy(\"L1_StrategyEG([0-9]+)\");\n if (std::regex_match(SeedName, base_match, EGStrategy))\n {\n pt = std::stoi(base_match[1].str(), nullptr);\n L1SeedFun[SeedName] = \n boost::bind(&SingleObjPt, L1ObjectMap[\"EG\"], pt) ||\n boost::bind(&SingleObjPt, L1ObjectMap[\"IsoEG\"], pt-2) ||\n boost::bind(&SingleObjPt, L1ObjectMap[\"IsoEGer\"], pt-4);\n return true;\n }\n\n return false;\n} // ----- end of function L1Menu2016::ParseEGStrategy -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ParseETMJetdPhi\n// Description: \n// ===========================================================================\nbool L1Menu2016::ParseETMJetdPhi(const std::string & SeedName)\n{\n int ETMpt = -10;\n int Jetpt = -10;\n bool isCentral = false;\n\n std::smatch base_match;\n std::regex ETMJetdPhi(\"L1_ETM([0-9]+)_Jet([C]*)([0-9]+)_dPhi_Min0p4\");\n if (std::regex_match(SeedName, base_match, ETMJetdPhi))\n {\n ETMpt = std::stoi(base_match[1].str(), nullptr);\n isCentral = base_match.length(2) == 1;\n Jetpt = std::stoi(base_match[3].str(), nullptr);\n L1SeedFun[SeedName] = std::bind(&L1AlgoFactory::ETM_Jet, this, ETMpt, Jetpt, isCentral);\n return true;\n }\n\n return false;\n} // ----- end of function L1Menu2016::ParseETMJetdPhi -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ParseMultiEGMass\n// Description: \n// ===========================================================================\nbool L1Menu2016::ParseMultiEGMass(const std::string& SeedName)\n{\n \n int pts = -10;\n int pt1 = -10;\n int pt2 = -10;\n int pt3 = -10;\n int pt4 = -10;\n int Mcut = -10;\n bool isIso = false;\n bool isER = false;\n int EGcount = 0;\n\n std::map<std::string, int> CountMap;\n CountMap[\"Single\"] = 1;\n CountMap[\"Double\"] = 2;\n CountMap[\"Triple\"] = 3;\n CountMap[\"Quad\"] = 4;\n\n\n std::smatch base_match;\n std::regex integer(\"L1_(Single|Double|Triple|Quad)(Iso|)EG([0-9]*)(er|)(_{0,1}[0-9]*)(_{0,1}[0-9]*)(_{0,1}[0-9]*)(_{0,1}[0-9]*)_M([0-9]+)\");\n if (std::regex_match(SeedName, base_match, integer))\n {\n EGcount = CountMap[base_match[1].str()];\n isIso = base_match.length(2) != 0;\n if (base_match[3].str() != \"\")\n pts =std::stoi(base_match[3].str(), nullptr);\n isER = base_match.length(4) != 0;\n if (base_match[5].str() != \"\")\n pt1 = std::stoi(base_match[5].str().erase(0, 1), nullptr);\n if (base_match[6].str() != \"\")\n pt2 = std::stoi(base_match[6].str().erase(0, 1), nullptr);\n if (base_match[7].str() != \"\")\n pt3 = std::stoi(base_match[7].str().erase(0, 1), nullptr);\n if (base_match[8].str() != \"\")\n pt4 = std::stoi(base_match[8].str().erase(0, 1), nullptr);\n Mcut = std::stoi(base_match[9].str(), nullptr);\n }\n\n\n std::vector<int> Ptcuts;\n if (pts > 0) // Set to all legs\n {\n pt1 = pt2 = pt3 = pt4 = pts;\n for (int i = 0; i < 4; ++i)\n {\n if (i <= EGcount)\n Ptcuts.push_back(pts);\n else\n Ptcuts.push_back(-10);\n }\n } else{\n Ptcuts.push_back(pt1);\n Ptcuts.push_back(pt2);\n Ptcuts.push_back(pt3);\n Ptcuts.push_back(pt4);\n std::sort(Ptcuts.begin(), Ptcuts.end(), std::greater<int>());\n }\n\n assert(EGcount == std::count_if(Ptcuts.begin(), Ptcuts.end(), [](int i){return i > 0;}));\n L1SeedFun[SeedName] = std::bind(&L1AlgoFactory::MultiEGMass, this, Ptcuts.at(0), \n Ptcuts.at(1), Ptcuts.at(2), Ptcuts.at(3), Mcut, isIso, isER);\n\n return true;\n} // ----- end of function L1Menu2016::ParseMultiEGMass -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ParseCrossMu\n// Description: \n// ===========================================================================\nbool L1Menu2016::ParseCrossMu(const std::string& /*SeedName*/)\n{\n //std::smatch base_match;\n //std::regex integer(\"L1_QuadJet([C]*)([0-9]+)\");\n //if (std::regex_match(SeedName, base_match, integer))\n //{\n //if (base_match.size() != 2) return false;\n //bool isCentral = base_match.length(1) == 1;\n //unsigned int pt = std::stoi(base_match[2].str(), nullptr);\n //L1SeedFun[SeedName] = std::bind(&L1AlgoFactory::QuadJet, this, pt, pt, pt, pt, isCentral);\n //return true;\n //}\n //else return false;\n return false;\n} // ----- end of function L1Menu2016::ParseCrossMu -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ParseMuerTauer\n// Description: \n// ===========================================================================\nbool L1Menu2016::ParseMuerTauer(const std::string& SeedName)\n{\n int Mupt = -10;\n int Taupt = -10;\n bool isIsoTau = false;\n\n std::smatch base_match;\n std::regex integer(\"L1_Mu([0-9]+)er_(Iso|)Tau(Jet|)([0-9]+)er\");\n if (std::regex_match(SeedName, base_match, integer))\n {\n Mupt = std::stoi(base_match[1].str(), nullptr);\n isIsoTau = base_match.length(2) == 3;\n Taupt = std::stoi(base_match[4].str(), nullptr);\n L1SeedFun[SeedName] = std::bind(&L1AlgoFactory::Muer_TauJetEta2p17, this, Mupt, Taupt, isIsoTau);\n return true;\n }\n\n return false;\n} // ----- end of function L1Menu2016::ParseMuerTauer -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ParseMuEG\n// Description: \n// ===========================================================================\nbool L1Menu2016::ParseMuEG(const std::string& SeedName)\n{\n const int muonQual = 2;\n int Mupt = -10;\n int EGpt = -10;\n bool isIsoEG = false;\n\n std::smatch base_match;\n std::regex integer(\"L1_Mu([0-9]+)_(Iso|)EG([0-9]+)\");\n if (std::regex_match(SeedName, base_match, integer))\n {\n Mupt = std::stoi(base_match[1].str(), nullptr);\n isIsoEG = base_match.length(2) == 3;\n EGpt = std::stoi(base_match[3].str(), nullptr);\n L1SeedFun[SeedName] = std::bind(&L1AlgoFactory::Mu_EG, this, Mupt, EGpt, isIsoEG, muonQual);\n return true;\n }\n\n return false;\n} // ----- end of function L1Menu2016::ParseMuEG -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ParseMuSum\n// Description: \n// ===========================================================================\nbool L1Menu2016::ParseMuSum(const std::string& SeedName)\n{\n int Mupt = -10;\n int Sumpt = -10;\n\n std::smatch base_match;\n std::regex integerMuHTT(\"L1_Mu([0-9]+)_HTT([0-9]+)\");\n std::regex integerMuerETM(\"L1_Mu([0-9]+)er_ETM([0-9]+)\");\n if (std::regex_match(SeedName, base_match, integerMuHTT))\n {\n Mupt = std::stoi(base_match[1].str(), nullptr);\n Sumpt = std::stoi(base_match[2].str(), nullptr);\n L1SeedFun[SeedName] = std::bind(&L1AlgoFactory::Mu_HTT, this, Mupt, Sumpt);\n return true;\n }\n\n if (std::regex_match(SeedName, base_match, integerMuerETM))\n {\n Mupt = std::stoi(base_match[1].str(), nullptr);\n Sumpt = std::stoi(base_match[2].str(), nullptr);\n L1SeedFun[SeedName] = std::bind(&L1AlgoFactory::Muer_ETM, this, Mupt, Sumpt);\n return true;\n }\n\n return false;\n} // ----- end of function L1Menu2016::ParseMuSum -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ParseComplexSingleMu\n// Description: \n// ===========================================================================\nbool L1Menu2016::ParseComplexSingleMu(const std::string& SeedName) \n{\n // This function overlap wiht ParseSingleObject. The code shouldn't come\n // here for simple singleMu trigger. Check for safety\n if (L1SeedFun.find(SeedName)!= L1SeedFun.end())\n return false;\n\n std::smatch base_match;\n std::regex integer(\"L1_Single([^0-9_]+)([0-9]+)([^0-9_]*)(_(EMTF|OMTF|BMTF))*(_Bx([-+0-9]+))*(_(Open|LowQ|HighQ))*\");\n std::string L1object =\"\";\n std::string postfix = \"\";\n std::string muonType = \"\";\n std::string muonQual = \"\";\n int muonBx = 0;\n int imuonQual = 2;\n int imuonType = 0;\n float muonpt = -10;\n\n if (std::regex_match(SeedName, base_match, integer))\n {\n L1object = base_match[1];\n muonpt = std::stoi(base_match[2], nullptr);\n postfix = base_match[3];\n if (base_match[4] != \"\")\n {\n muonType = base_match[5];\n }\n if (base_match[6]!=\"\")\n {\n muonBx = std::stoi(base_match[7], nullptr);\n }\n if (base_match[8] != \"\")\n {\n muonQual = base_match[9];\n }\n } else return false;\n\n if (!muonQual.empty())\n {\n if (muonQual == \"Open\") imuonQual = 0;\n if (muonQual == \"LowQ\") imuonQual = 1;\n if (muonQual == \"HighQ\") imuonQual = 2;\n }\n\n if (!muonType.empty())\n {\n if (muonType == \"BMTF\") imuonType = 1;\n if (muonType == \"OMTF\") imuonType = 2;\n if (muonType == \"EMTF\") imuonType = 3;\n }\n assert(L1object == \"Mu\");\n bool isER = postfix==\"er\";\n L1SeedFun[SeedName] = std::bind(&L1AlgoFactory::ComplexSingleMu, this, muonpt, isER, imuonQual, imuonType, muonBx);\n return true;\n} // ----- end of function L1Menu2016::ParseComplexSingleMu -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::FillLumiSection\n// Description: \n// ===========================================================================\nbool L1Menu2016::FillLumiSection(int currentLumi)\n{\n if (currentLumi == -1) return false;\n\n for(auto l1 : mL1Seed)\n {\n if(L1LSCount[l1.first].find(currentLumi) == L1LSCount[l1.first].end())\n {\n L1LSCount[l1.first][currentLumi] = 0;\n }\n if (l1.second.eventfire)\n {\n L1LSCount[l1.first][currentLumi]++;\n }\n }\n\n L1LSCount[\"Count\"][currentLumi]++;\n \n return true;\n} // ----- end of function L1Menu2016::FillLumiSection -----\n\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::FillPileUpSec\n// Description: \n// ===========================================================================\nbool L1Menu2016::FillPileUpSec()\n{\n float pu = -1;\n //bool eFired = false;\n // Data\n if (event_->run > 1 && DataLSPU.find(event_->run) != DataLSPU.end())\n {\n if (DataLSPU[event_->run].find(event_->lumi) != DataLSPU[event_->run].end())\n {\n pu = DataLSPU[event_->run][event_->lumi];\n }\n }\n\n // MC\n if (event_->run == 1)\n {\n pu = event_->nPV;\n }\n\n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Fill Rate per PU ~~~~~\n for(auto col : ColumnMap)\n {\n col.second->FillPileUpSec(pu);\n }\n\n return true;\n} // ----- end of function L1Menu2016::FillPileUpSec -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::PrintCSV\n// Description: \n// ===========================================================================\nbool L1Menu2016::PrintCSV(std::ostream &out)\n{\n if (!writecsv) return false;\n\n // L1Seeds\n std::vector<std::string> csvout;\n std::stringstream ss;\n ss << \"L1Bit\" \n << \",\" << \"L1SeedName\"<< \",\" ;\n csvout.push_back(ss.str());\n for(auto sed : vL1Seed)\n {\n auto seed = mL1Seed[sed];\n ss.str(\"\");\n ss << seed.bit\n << \",\" << sed<< \",\" ;\n csvout.push_back(ss.str());\n }\n\n // POG\n ss.str(\"\");\n csvout.push_back(ss.str());\n\n int idx = 1000;\n for(auto pog : POGMap)\n {\n ss.str(\"\");\n ss << idx++ << \",\" << pog.first <<\",\";\n csvout.push_back(ss.str());\n }\n\n // PAG\n ss.str(\"\");\n csvout.push_back(ss.str());\n\n idx = 2000;\n for(auto pag : PAGMap)\n {\n ss.str(\"\");\n ss << idx++ << \",\" << pag.first <<\",\";\n csvout.push_back(ss.str());\n }\n\n // Total\n csvout.push_back(\"\");\n csvout.push_back(\"9999,Total rate,\");\n\n for(auto col : ColumnMap)\n {\n col.second->PrintCSV(csvout, scale);\n }\n\n \n//~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Writing out to file ~~~~~\n for(auto i : csvout)\n {\n out << i <<std::endl;\n }\n return true;\n} // ----- end of function L1Menu2016::PrintCSV -----\n\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ReadDataPU\n// Description: \n// ===========================================================================\nbool L1Menu2016::ReadDataPU() \n{\n const std::string pucsv = L1ConfigStr[\"Lumilist\"];\n std::ifstream csvfile(pucsv);\n if (!csvfile)\n {\n std::cout << \"Data PU CSV File \"<<pucsv<<\" is not found !\"<<std::endl;\n return false;\n }\n\n std::string line;\n DataLSPU.clear();\n std::getline(csvfile, line); // Skip the first line;\n while (std::getline(csvfile, line))\n {\n std::istringstream iss(line);\n std::string seed;\n char c;\n int Fill, Run, LS;\n float pileup;\n iss >> Fill >> c >> Run >> c >> LS >> c >> pileup;\n DataLSPU[Run][LS] = pileup;\n }\n\n return true;\n} // ----- end of function L1Menu2016::ReadDataPU -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::CalLocalHT\n// Description: \n// ===========================================================================\nvoid L1Menu2016::CalLocalHT(float &HTTcut, bool withHF)\n{\n float sumJetHt= 0;\n for(UInt_t ue=0; ue < upgrade_->nJets; ue++) {\n Int_t bx = upgrade_->jetBx.at(ue); \t\t\n if(bx != 0) continue;\n Float_t pt = upgrade_->jetEt.at(ue);\n Float_t eta = upgrade_->jetEta.at(ue);\n if (pt >= L1Config[\"SumJetET\"])\n {\n if (withHF)\n {\n sumJetHt += pt;\n }\n else{\n if ( fabs(eta) <= L1Config[\"SumJetEta\"] )\n sumJetHt += pt;\n }\n }\n }\n HTTcut = sumJetHt;\n return;\n\n} // ----- end of function L1Menu2016::CalLocalHT -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::CalLocalHTM\n// Description: \n// ===========================================================================\nvoid L1Menu2016::CalLocalHTM(float &HTMcut)\n{\n \n TLorentzVector temp(0, 0,0,0);\n for(UInt_t ue=0; ue < upgrade_->nJets; ue++) {\n Int_t bx = upgrade_->jetBx.at(ue); \t\t\n if(bx != 0) continue;\n Float_t pt = upgrade_->jetEt.at(ue);\n Float_t eta = upgrade_->jetEta.at(ue);\n if (pt >= L1Config[\"SumJetET\"] && fabs(eta) <= L1Config[\"SumJetEta\"] )\n {\n TLorentzVector jet(0, 0,0,0);\n jet.SetPtEtaPhiE(upgrade_->jetEt.at(ue),\n upgrade_->jetEta.at(ue),\n upgrade_->jetPhi.at(ue), \n 0);\n temp -= jet;\n }\n }\n HTMcut = temp.Pt();\n} // ----- end of function L1Menu2016::CalLocalHTM -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::ParseRanges\n// Description: \n// ===========================================================================\nbool L1Menu2016::ParseRanges(const std::string Config, std::vector<std::pair<unsigned int, unsigned int> >& Container)\n{\n if (L1ConfigStr[Config] == \"\") return false;\n \n std::regex pattern(\"\\\\[\\\\s*([0-9]+,\\\\s*[0-9]+)\\\\s*\\\\]\");\n std::regex bounds(\"([0-9]+),\\\\s*([0-9]+)\");\n std::smatch base_match;\n\n for (std::sregex_token_iterator i(L1ConfigStr[Config].begin(), L1ConfigStr[Config].end(), pattern, 1); \n i != std::sregex_token_iterator(); ++i) \n {\n\tstd::string match_str = i->str(); \n if (std::regex_match(match_str, base_match, bounds))\n {\n unsigned lead = std::stoi(base_match[1], nullptr);\n unsigned sec = std::stoi(base_match[2], nullptr);\n assert( sec >= lead );\n Container.push_back(std::make_pair(lead, sec));\n }\n }\n\n return true;\n} // ----- end of function L1Menu2016::ParseRanges -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::CheckLS\n// Description: Return whether to skip this LS\n// ===========================================================================\nbool L1Menu2016::CheckLS(unsigned int currentLumi) const\n{\n for(auto p : pLS)\n {\n if (currentLumi >= p.first && currentLumi <= p.second)\n {\n if (L1Config.at(\"doScanLS\"))\n std::cout << \"LS\"<<currentLumi <<\" % \"<< fChain->GetCurrentFile()->GetName() << std::endl;\n return false;\n }\n }\n return true;\n} // ----- end of function L1Menu2016::CheckLS -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::CheckBX\n// Description: Return whether to skip this BX\n// ===========================================================================\nbool L1Menu2016::CheckBX(unsigned int currentBX) const\n{\n for(auto p : pBX)\n {\n if (currentBX >= p.first && currentBX <= p.second)\n {\n return false;\n }\n }\n return true;\n} // ----- end of function L1Menu2016::CheckBX -----\n\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::CalLocalETM\n// Description: \n// ===========================================================================\nvoid L1Menu2016::CalLocalETM(float &ETMcut, bool withHF)\n{\n\n if (!l1CaloTower_) return;\n\n TVector2 revec(0,0);\n \n // Ignore Tower 28\n int ietamax = 29;\n if (withHF)\n ietamax = 99;\n float metX =0;\n float metY =0;\n\n\n for(int jTower=0; jTower< l1CaloTower_ ->nTower; ++jTower){\n Int_t ieta = l1CaloTower_->ieta[jTower];\n Int_t iphi = l1CaloTower_->iphi[jTower];\n Int_t iet = l1CaloTower_->iet[jTower];\n Double_t phi = (Double_t)iphi * TMath::Pi()/36.;\n Double_t et = 0.5 * (Double_t)iet;\n if (abs(ieta) == 28) continue;\n if(abs(ieta) < ietamax){\n metX -= et * TMath::Cos(phi);\n metY -= et * TMath::Sin(phi);\n }\n }\n\n revec.Set(metX, metY);\n ETMcut = revec.Mod();\n} // ----- end of function L1Menu2016::CalLocalETM -----\n\n// === FUNCTION ============================================================\n// Name: L1Menu2016::TokenGroups\n// Description: \n// ===========================================================================\nstd::vector<std::string> L1Menu2016::TokenGroups(std::string instring) const\n{\n std::vector<std::string> temp;\n if (instring.empty()) return temp;\n\n boost::char_separator<char> sep(\",.;|-\");\n tokenizer tokens(instring, sep);\n for(auto &t : tokens)\n {\n temp.push_back(t);\n }\n return temp;\n} // ----- end of function L1Menu2016::TokenGroups -----\n"
},
{
"alpha_fraction": 0.6336166262626648,
"alphanum_fraction": 0.6404626965522766,
"avg_line_length": 26.86842155456543,
"blob_id": "1421bcfb636318557049578404243a67569ba80b",
"content_id": "92de51a81372edab4de0c82e3e94d6dd0d07e6bc",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4236,
"license_type": "no_license",
"max_line_length": 172,
"num_lines": 152,
"path": "/scripts/getUnprescaledJson.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "#!/bin/env python\n#\n# Author: Takashi MATSUSHITA\n#\n# Usage:\n# python getUnprescaledJson.py --json <Cert_..._JSON.txt> --user <database account> --seed <L1 seed name>\n# to produce <L1 seed name>_unprescaled.json file\n#\n\nimport argparse\nimport itertools\nimport json\nimport cx_Oracle\n\n\ndef toRange(i):\n for a, b in itertools.groupby(enumerate(i), lambda (x, y): y - x):\n b = list(b)\n yield b[0][1], b[-1][1]\n\n\ndef getMenu(data):\n data.id2name = {}\n data.mask = {}\n data.name2id = {}\n\n query = \"\"\"select algo_index, algo_name, algo_mask from cms_ugt_mon.view_ugt_run_algo_setting where run_number = %s order by algo_index\"\"\" % data.run\n data.cursor.execute(query)\n rc = data.cursor.fetchall()\n\n for x in rc:\n name = x[1].replace('\"', '')\n data.id2name[x[0]] = name\n data.mask[x[0]] = x[2]\n data.name2id[name] = x[0]\n\n\ndef getPrescales(data):\n data.prescales = {}\n\n for idx in data.id2name.keys():\n query = \"\"\"select prescale_index, prescale from cms_ugt_mon.view_ugt_run_prescale where algo_index = %s and run_number = %s order by prescale_index\"\"\" % (idx, data.run)\n data.cursor.execute(query)\n rc = data.cursor.fetchall()\n\n data.prescales[idx] = {}\n for x in rc:\n data.prescales[idx][x[0]] = x[1] * data.mask[idx]\n\n\ndef getPrescaleColumnSequence(data):\n data.ps_sequence = {}\n\n query = \"\"\"select lumi_section, prescale_index from cms_ugt_mon.view_lumi_sections where run_number = %s order by lumi_section\"\"\" % (run,)\n data.cursor.execute(query)\n rc = data.cursor.fetchall()\n\n end = 0\n for x in rc:\n data.ps_sequence[x[0]] = x[1]\n end = max(end, x[0])\n\n # fix for missing lumi-section/ps column idx\n prev = data.ps_sequence[max(data.ps_sequence.keys())]\n for ii in range(end, 0, -1):\n if ii in data.ps_sequence:\n if data.ps_sequence[ii] != None:\n prev = data.ps_sequence[ii]\n else:\n data.ps_sequence[ii] = prev # fixing None\n else:\n data.ps_sequence[ii] = prev # setting missing ls\n\n\ndef getUnprescaled(data, ls_ranges, seed):\n data.unprescaled[run] = None\n\n prescaled = []\n unprescaled = []\n\n prev = data.ps_sequence[min(data.ps_sequence.keys())]\n for x in ls_ranges:\n begin, end = x\n for ls in range(begin, end+1):\n if ls not in data.ps_sequence:\n if data.prescales[data.name2id[seed]][prev] != 1:\n prescaled.append(ls)\n else:\n unprescaled.append(ls)\n else:\n prev = data.ps_sequence[ls]\n if data.prescales[data.name2id[seed]][data.ps_sequence[ls]] != 1:\n prescaled.append(ls)\n else:\n unprescaled.append(ls)\n\n data.unprescaled[run] = list(toRange(unprescaled))\n\n if len(prescaled):\n print ' prescaled in', list(toRange(prescaled))\n\n\nclass Object:\n def __init__(self):\n pass\n\n\nif __name__ == '__main__':\n database = 'cms_omds_lb'\n user = None\n passwd = None\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--json\", dest=\"json\", default=None, type=str, action=\"store\", required=True, help=\"json file\")\n parser.add_argument(\"--seed\", dest=\"seed\", default=None, type=str, action=\"store\", required=True, help=\"seed name\")\n parser.add_argument(\"--db\", dest=\"database\", default=database, type=str, action=\"store\", help=\"database connection\")\n parser.add_argument(\"--user\", dest=\"user\", default=user, type=str, action=\"store\", required=True, help=\"database account user name\")\n parser.add_argument(\"--passwd\", dest=\"passwd\", default=passwd, type=str, action=\"store\", help=\"password\")\n\n options = parser.parse_args()\n\n fp = file(options.json)\n run_ls = json.load(fp)\n\n if not options.passwd:\n import getpass\n options.passwd = getpass.getpass()\n\n\n data = Object()\n con = cx_Oracle.connect('%s/%s@%s' % (options.user, options.passwd, options.database))\n data.cursor = con.cursor()\n\n data.unprescaled = {}\n\n hasPrescaled = False\n print 'inf> checking %s in ...' % (options.seed,)\n for run in sorted(run_ls.keys()):\n print 'inf> run %s' % (run,)\n ls_ranges = run_ls[run]\n data.run = run\n\n getMenu(data)\n getPrescales(data)\n getPrescaleColumnSequence(data)\n getUnprescaled(data, ls_ranges, options.seed)\n\n fp = open(options.seed + '_unprescaled.json', 'w') \n json.dump(data.unprescaled, fp)\n\n# eof\n"
},
{
"alpha_fraction": 0.3020612299442291,
"alphanum_fraction": 0.4217109978199005,
"avg_line_length": 61.54081726074219,
"blob_id": "c4f6ff396a76d4cd278f771cab860874ded63b6c",
"content_id": "ab5b3233833226f33ec16ce99b04cf4df37973f1",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 18387,
"license_type": "no_license",
"max_line_length": 139,
"num_lines": 294,
"path": "/macros/menu/oldMenus/Lumi1p15E34.txt",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "## Start with 100kHz for 1.2e34\n## Assume 20kHz for ETM, and ETM with HF rates\n## Assume 1kHz for Zero bias (originally 10kHz)\n## Assume bptx trigger rates are PU independant, get them from WBM\n## Assume 1kHz for bxpt seeds (originally 2kHz)\n## Assume 5kHz for prescale rate (masked in this menu)\n## Menu rate = 100 - 20 - 1 - 1 - 5 = 73kHz\n\n## EG map from https://indico.cern.ch/event/493290/contribution/2/attachments/1221650/1786361/Zhenbin_Stage2_L1Menu.pdf\n## HT map from https://indico.cern.ch/event/502206/contribution/2/attachments/1233163/1809079/Zhenbin_Stage2_Calov0.pdf\n\n## Re-organize L1 bit up to 511\n## 1 -100 > Mu\n## 101-200 > EG\n## 201-300 > Jet & Tau\n## 301-400 > Sums\n## 401-500 > Cross\n## 500-511 > bptx\n\n#============================================================================#\n#------------------------------ Config ------------------------------#\n#============================================================================#\n## Run 259721: PU=22, nB=517, Lumi=1.5E33, Tau option 5\n## Using this run to tune 1.15E34 menu column, PU=30\n## Scale = 517 * 1E34/1.5E33 = 3446.67\n## ZB 1.7kHZ if possbile, minimum 1kHz\n# % nBunches = 3446.67\n\n#============================================================================#\n#------------------------------- Menu -------------------------------#\n#============================================================================#\n# L1Seed Bit Prescale POG PAG\n# L1_ZeroBias 0 20011 Tech\n### SingleMu 1-30\nL1_SingleMuOpen 2 20000 Mu\nL1_SingleMu3 3 10000 Mu HIGGS,EXO,SUSY\nL1_SingleMu5 4 0 Mu HIGGS,EXO,SUSY\nL1_SingleMu7 5 120 Mu HIGGS,EXO,BPH,SUSY\nL1_SingleMu12 6 0 Mu HIGGS,SUSY\nL1_SingleMu14 7 0 Mu\nL1_SingleMu16 8 0 Mu TOP,HIGGS,EXO,SMP,BPH,SUSY,B2G\nL1_SingleMu18 9 100 Mu TOP,HIGGS,EXO,SMP,BPH,SUSY,B2G\nL1_SingleMu20 10 1 Mu HIGGS,EXO\nL1_SingleMu22 11 1 Mu\nL1_SingleMu25 12 1 Mu TOP,HIGGS,EXO,SMP,BPH,B2G\nL1_SingleMu30 13 1 Mu TOP,HIGGS,EXO,SMP,BPH,B2G\nL1_SingleMu10_LowQ 21 250 Mu # 450 Andrea, 200 Ben\n### SingleMuer 31 - 60\nL1_SingleMu14er 31 0 Mu HIGGS,EXO,SMP,SUSY,B2G\nL1_SingleMu16er 32 100 Mu HIGGS,EXO,SMP\nL1_SingleMu18er 33 1 Mu\nL1_SingleMu20er 34 1 Mu HIGGS,EXO\nL1_SingleMu22er 35 1 Mu\nL1_SingleMu25er 36 1 Mu\nL1_SingleMu30er 37 1 Mu\n\n### DoubleMu 61-80\nL1_DoubleMuOpen 60 0 Mu BPH\nL1_DoubleMu0 61 300 Mu BPH\nL1_DoubleMu_10_Open 62 0 Mu\nL1_DoubleMu_10_3p5 63 0 Mu TOP,HIGGS,EXO,SMP,SUSY,B2G\nL1_DoubleMu_11_4 64 1 Mu\nL1_DoubleMu_12_5 65 1 Mu TOP,HIGGS,EXO,SMP,SUSY,B2G\nL1_DoubleMu_13_6 66 1 Mu\nL1_DoubleMu_15_5 67 1 Mu\nL1_DoubleMu_12_8 68 1 Mu\nL1_DoubleMu0er1p6_dEta_Max1p8 69 100 Mu BPH\nL1_DoubleMu0er1p6_dEta_Max1p8_OS 70 1 Mu BPH # 0 charge for OMTF, cause higher rate\nL1_DoubleMu0er1p4_dEta_Max1p8_OS 71 1 Mu BPH # 0 charge for OMTF, cause higher rate\nL1_DoubleMu_10_0_dEta_Max1p8 72 0 Mu BPH #1kHz pure rate, might go back if we have more rate\n### TripleMu 81-90\nL1_TripleMu0 81 1 Mu HIGGS,BPH\nL1_TripleMu_5_5_3 82 1 Mu HIGGS\nL1_TripleMu_5_0_0 83 1 Mu HIGGS\n### QuadMu 91-100\nL1_QuadMu0 91 1 Mu BPH\n\n### SingleEG 101-120\nL1_SingleEG5 101 50000 EG\nL1_SingleEG10 102 8000 EG # 10000 Andrea, 8000 SUSY\nL1_SingleEG15 103 1000 EG\nL1_SingleEG18 104 3000 EG # 6400 Andrea, 3000 SUSY\nL1_SingleEG24 105 2000 EG\nL1_SingleEG26 106 300 EG\nL1_SingleEG28 107 0 EG\nL1_SingleEG30 108 1 EG\nL1_SingleEG32 109 1 EG\nL1_SingleEG34 110 1 EG EXO,SMP #Stage1 EG30, Eff39\nL1_SingleEG36 111 1 EG EXO,SMP #Stage1 EG30, Eff39\nL1_SingleEG40 112 1 EG EXO #Stage1 EG35, Eff45\nL1_SingleEG45 113 1 EG HIGGS,SMP #Stage1 EG40, Eff51\n### SingleIsoEG 121-140\nL1_SingleIsoEG18 121 0 EG\nL1_SingleIsoEG20 122 0 EG\nL1_SingleIsoEG22 123 0 EG\nL1_SingleIsoEG24 124 0 EG #Stage1 EG20, Eff29\nL1_SingleIsoEG26 125 0 EG\nL1_SingleIsoEG28 126 1 EG\nL1_SingleIsoEG30 127 1 EG\nL1_SingleIsoEG32 128 1 EG\nL1_SingleIsoEG34 129 1 EG\nL1_SingleIsoEG36 130 1 EG\n### SingleIsoEGer 141-160\nL1_SingleIsoEG16er 140 0 EG #Stage1 EG15, Eff25\nL1_SingleIsoEG18er 141 0 EG #Stage1 EG15, Eff25\nL1_SingleIsoEG20er 142 0 EG\nL1_SingleIsoEG22er 143 0 EG HIGGS\nL1_SingleIsoEG24er 144 0 EG\nL1_SingleIsoEG26er 145 1 EG\nL1_SingleIsoEG28er 146 1 EG\nL1_SingleIsoEG30er 147 1 EG\nL1_SingleIsoEG32er 148 1 EG\nL1_SingleIsoEG34er 149 1 EG TOP,HIGGS,EXO,SMP,SUSY,B2G #Stage1 EG30, Eff39\n### DoubleEG 161 - 180\nL1_DoubleEG_15_10 161 0 EG #8kHz pure rate\nL1_DoubleEG_18_17 162 0 EG TOP,HIGGS,EXO,SMP,SUSY,B2G #map to Stage1 L1_DoubleEG_15_10\nL1_DoubleEG_20_18 163 0 EG\nL1_DoubleEG_22_10 165 0 EG\nL1_DoubleEG_23_10 166 1 EG #map to Stage1 L1_DoubleEG_22_10\nL1_DoubleEG_24_17 167 1 EG #map to Stage1 L1_DoubleEG_22_10\nL1_DoubleEG_22_12 168 0 EG # from Simone's menu,800Hz pure rate\nL1_DoubleEG_22_15 169 0 EG # created by ZW\nL1_DoubleEG_25_12 170 1 EG\n### TripleEG 181-190\nL1_TripleEG_14_10_8 181 1 EG HIGGS\nL1_TripleEG_18_17_8 182 1 EG HIGGS #map to Stage1 L1_TripleEG_15_10_8\n### QuadEG 191-200\n\n### SingleJet 201-220\nL1_SingleJet16 201 0 Jet\nL1_SingleJet20 202 0 Jet\nL1_SingleJet35 203 3000 Jet\nL1_SingleJet60 204 1000 Jet EXO,SMP # Prescale 840 from CMSHLT-725\nL1_SingleJet90 205 1200 Jet SMP\nL1_SingleJet120 206 100 Jet EXO,SMP,SUSY,B2G\nL1_SingleJet140 207 0 Jet EXO,SMP,SUSY,B2G\nL1_SingleJet150 208 1 Jet EXO,SMP,SUSY,B2G\nL1_SingleJet160 209 1 Jet EXO,SMP,SUSY,B2G\nL1_SingleJet170 210 1 Jet EXO,SMP,SUSY,B2G\nL1_SingleJet180 211 1 Jet EXO,SMP,SUSY,B2G\nL1_SingleJet200 212 1 Jet EXO,SMP,SUSY,B2G\n### DoubleJet 221-240\nL1_DoubleJetC40 221 0 Jet\nL1_DoubleJetC50 222 0 Jet\nL1_DoubleJetC60 223 0 Jet\nL1_DoubleJetC80 224 0 Jet\nL1_DoubleJetC100 225 1 Jet EXO,SUSY\nL1_DoubleJetC112 226 1 Jet EXO,SUSY\nL1_DoubleJetC120 227 1 Jet EXO,SUSY\nL1_DoubleJet8_ForwardBackward 231 0 Jet # CMSHLT-719\nL1_DoubleJet12_ForwardBackward 232 0 Jet # CMSHLT-719\nL1_DoubleJet16_ForwardBackward 233 0 Jet # CMSHLT-719\n\n### TripleJet 241-250\nL1_TripleJet_84_68_48_VBF 241 1 Jet HIGGS\nL1_TripleJet_88_72_56_VBF 242 1 Jet HIGGS\nL1_TripleJet_92_76_64_VBF 243 1 Jet HIGGS\n### QuadJet 251-260\nL1_QuadJetC40 251 0 Jet EXO,SUSY,B2G\nL1_QuadJetC50 252 1 Jet EXO,SUSY,B2G\nL1_QuadJetC60 253 1 Jet EXO,SUSY,B2G\n### SingleTau 261-270\nL1_SingleTau80er 261 0 Tau\nL1_SingleTau100er 262 1 Tau\nL1_SingleTau120er 263 1 Tau # No rate yet.\n### SingleIsoTau 271-280\n\n### DoubleTau 281-290\nL1_DoubleIsoTau26er 281 0 Tau HIGGS,EXO,SUSY\nL1_DoubleIsoTau27er 282 0 Tau HIGGS,EXO,SUSY\nL1_DoubleIsoTau28er 283 0 Tau HIGGS,EXO,SUSY\nL1_DoubleIsoTau29er 284 0 Tau HIGGS,EXO,SUSY\nL1_DoubleIsoTau30er 285 1 Tau HIGGS,EXO,SUSY\nL1_DoubleIsoTau32er 286 1 Tau HIGGS,EXO,SUSY\nL1_DoubleIsoTau33er 287 1 Tau HIGGS,EXO,SUSY\nL1_DoubleIsoTau34er 288 1 Tau HIGGS,EXO,SUSY\nL1_DoubleIsoTau35er 289 1 Tau HIGGS,EXO,SUSY\nL1_DoubleIsoTau36er 290 1 Tau HIGGS,EXO,SUSY\nL1_DoubleTau50er 291 1 Tau HIGGS,EXO,SUSY\n\n### HTT 301-320\nL1_HTT120 301 35000 Sum EXO,SUSY,B2G # 50000 Andrea, 30000 SUSY\nL1_HTT160 302 9500 Sum EXO,SUSY,B2G # 0 Andrea, 9000 SUSY\nL1_HTT200 303 0 Sum EXO,SUSY,B2G\nL1_HTT220 304 6500 Sum EXO,SUSY,B2G\nL1_HTT240 305 0 Sum EXO,SUSY,B2G\nL1_HTT255 306 0 Sum EXO,SUSY,B2G\nL1_HTT270 307 0 Sum EXO,SUSY,B2G\nL1_HTT280 308 1 Sum EXO,SUSY,B2G\nL1_HTT300 309 1 Sum EXO,SUSY,B2G\nL1_HTT320 310 1 Sum EXO,SUSY,B2G\n\n#### HTM 321-340\n# L1_HTM50 321 1 Sum EXO\n# L1_HTM70 322 1 Sum EXO\n# L1_HTM80 323 1 Sum EXO\n# L1_HTM100 324 1 Sum EXO\n# L1_HTM120 325 1 Sum EXO\n# L1_HTM130 326 1 Sum EXO\n# L1_HTM140 327 1 Sum EXO\n# L1_HTM150 328 1 Sum EXO\n#### ETT\n# L1_ETT40 341 1 Sum\n# L1_ETT60 342 1 Sum\n#### ETM\nL1_ETM30 361 0 Sum\nL1_ETM40 362 0 Sum\nL1_ETM50 363 0 Sum\nL1_ETM60 364 150 Sum\nL1_ETM70 365 0 Sum\nL1_ETM75 366 100 Sum\nL1_ETM80 367 1 Sum\nL1_ETM85 368 1 Sum\nL1_ETM90 369 1 Sum\nL1_ETM95 370 1 Sum\nL1_ETM100 371 1 Sum\nL1_ETM120 372 1 Sum\n\n### Cross 401-500\n## MuEG 401-415\nL1_Mu5_EG15 401 0 MuEG HIGGS\nL1_Mu5_EG20 402 1 MuEG HIGGS\nL1_Mu5_EG23 403 1 MuEG HIGGS # Map to Stage 1\nL1_Mu5_IsoEG18 404 1 MuEG HIGGS\nL1_Mu5_IsoEG20 405 1 MuEG HIGGS\nL1_Mu12_EG10 406 0 MuEG HIGGS\nL1_Mu20_EG15 407 1 MuEG HIGGS # L1_MU20_EG15 in v5 XML, to be corrected\nL1_Mu20_EG17 408 1 MuEG HIGGS\nL1_Mu23_IsoEG10 409 1 MuEG HIGGS\nL1_Mu23_EG10 410 1 MuEG HIGGS\nL1_Mu20_EG10 411 1 MuEG HIGGS\n## CrossTau 416-430\nL1_Mu16er_Tau20er 414 1 MuTau HIGGS\nL1_Mu16er_Tau24er 415 1 MuTau HIGGS\nL1_Mu18er_Tau20er 416 1 MuTau HIGGS\nL1_Mu18er_Tau24er 417 1 MuTau HIGGS\nL1_Mu18er_IsoTau26er 418 1 MuTau # Use same quarlity as SingleMuer\nL1_Mu20er_IsoTau26er 419 1 MuTau # Use same quarlity as SingleMuer\n\n## Rest\nL1_DoubleMu7_EG14 431 1 MuEG HIGGS #Like Stage1 L1_DoubleMu7_EG7\nL1_DoubleMu7_EG7 432 1 MuEG HIGGS #Like Stage1 L1_DoubleMu7_EG7\nL1_Mu6_DoubleEG17 433 1 MuEG HIGGS\nL1_Mu6_DoubleEG10 434 1 MuEG HIGGS\nL1_Mu3_JetC16_dEta_Max0p4_dPhi_Max0p4 435 400 MuJet # CMSHLT_707, prescale to 0.15kHz\nL1_Mu3_JetC60_dEta_Max0p4_dPhi_Max0p4 436 15 MuJet EXO # CMSHLT_707, prescale to 0.5kHz\nL1_Mu6_HTT200 437 1 MuSum EXO\nL1_Mu8_HTT150 438 0 MuSum SUSY\nL1_EG27er_HTT200 439 1 EGSum HIGGS #322 pure rate, masked for now\nL1_EG25er_HTT125 440 0 EGSum HIGGS #3kHz pure rate\nL1_DoubleEG6_HTT255 441 1 EGSum SUSY\nL1_QuadJetC36_Tau52 442 50 JetTau HIGGS\nL1_DoubleJetC60_ETM60 446 0 EGSum HIGGS\nL1_Mu0er_ETM40 447 0 MuSum HIGGS\nL1_Mu0er_ETM55 448 1 MuSum HIGGS\nL1_Mu10er_ETM30 449 0 MuSum HIGGS\nL1_Mu10er_ETM50 450 1 MuSum HIGGS\nL1_Mu14er_ETM30 451 0 MuSum HIGGS\nL1_Mu3_JetC120_dEta_Max0p4_dPhi_Max0p4 461 1 MuJet BTV\nL1_Mu3_JetC16 463 0 MuJet #BTV fallback\nL1_Mu3_JetC60 465 0 MuJet #BTV fallback\nL1_Mu3_JetC120 466 0 MuJet #BTV fallback\n\nL1_Jet32_DoubleMu_10_0_dPhi_Jet_Mu0_Max0p4_dPhi_Mu_Mu_Min1p0 444 70 MuJet SUSY #161Hz pure rate\nL1_Jet32_Mu0_EG10_dPhi_Jet_Mu_Max0p4_dPhi_Mu_EG_Min1p0 445 150 MuJet SUSY #Map to Stage1 L1_Jet32MuOpen_EG10_dPhiMu_EG1\nL1_DoubleMu0_ETM40 467 0 MuSum SUSY\nL1_DoubleMu0_ETM55 468 1 MuSum SUSY\n\nL1_IsoEG22er_Tau20er_dEta_Min0p2 443 0 EGTau HIGGS\nL1_IsoEG22er_IsoTau26er_dEta_Min0p2 469 1 EGTau HIGGS\nL1_IsoEG18er_IsoTau24er_dEta_Min0p2 471 1 EGTau HIGGS\nL1_IsoEG20er_IsoTau25er_dEta_Min0p2 473 1 EGTau HIGGS\nL1_ETM75_Jet60_dPhi_Min0p4 474 0 JetSum\nL1_Mu20_IsoEG6 476 1 JetSum\n#============================================================================#\n#---------------------------- Fixed Rate ----------------------------#\n#============================================================================#\n# # L1_AlwaysTrue\n# # L1_BptxPlus\n# # L1_BptxMinus\n# # L1_BptxOR\n# # L1_SingleMuOpen_NotBptxOR_3BX\n# # L1_SingleJetC20_NotBptxOR_3BX\n# # L1_SingleJetC32_NotBptxOR_3BX\n# # L1_SingleJetC36_NotBptxOR_3BX\n# # L1_SingleMuOpen_NotBptxOR 454 -1 Mu #Assume 1kHz for all bptx triggers\n# # L1_SingleJetC32_NotBptxOR 455 -1 Jet #Assume 1kHz for all bptx triggers\n# # L1_SingleJetC20_NotBptxOR 456 -1 Jet #Assume 1kHz for all bptx triggers\n# # L1_SingleEG2_BptxAND 457 -1 Jet #Assume 1kHz for all bptx triggers\n# # L1_ETT15_BptxAND 458 -1 Sum #Assume 1kHz for all bptx triggers\n# # L1_SingleJet8_BptxAND 459 -1 Jet #Assume 1kHz for all bptx triggers\n# # L1_SingleJet12_BptxAND 460 -1 Jet #Assume 1kHz for all bptx triggers\n\n# vim: ft=python:nolbr:cc=88\n"
},
{
"alpha_fraction": 0.3987836539745331,
"alphanum_fraction": 0.4370113015174866,
"avg_line_length": 27.774999618530273,
"blob_id": "51cebb6f54371db866b785c3f38c99833a223282",
"content_id": "ece5a920b53f1d9f01a0b776405bf6d27d2008e6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C++",
"length_bytes": 1151,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 40,
"path": "/macros/RunL1Menu2016.cc",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "// ===========================================================================\n// \n// Filename: RunL1Menu2015.cc\n// \n// Description: An executable for running the L1Menu2015\n// \n// Version: 1.0\n// Created: 12/22/2015 16:36:48\n// Compiler: g++ -std=c++11\n// \n// Author: Zhenbin Wu (benwu)\n// Email: [email protected]\n// Company: UIC, CMS@LPC, CDF@FNAL\n// \n// ===========================================================================\n\n\n#include <cstdlib>\n#include <iostream> \n#include <string>\n#include <vector>\n\n#include \"BasicRatePlots.C\"\n#include \"L1Menu2016_minbias_cross_section.C\"\n\n#include \"TSystem.h\"\n#include <FWCore/FWLite/interface/FWLiteEnabler.h>\n// === FUNCTION ============================================================\n// Name: main\n// Description: \n// ===========================================================================\nint main ( int argc, char *argv[] )\n{\n gSystem->Load(\"libFWCoreFWLite\");\n FWLiteEnabler::enable();\n\n //goRatePlots(\"RUN256843_Stage2\",0,0);\n RunL1(true, true, 5);\n return EXIT_SUCCESS;\n}\t\t\t\t// ---------- end of function main ----------\n"
},
{
"alpha_fraction": 0.6029826402664185,
"alphanum_fraction": 0.6690850257873535,
"avg_line_length": 31.220779418945312,
"blob_id": "8d07672e35360176d70f3f2f6e13df7ab2b64ae4",
"content_id": "a322779951f0db195263ebcb472f0daed91ddbed",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 2481,
"license_type": "no_license",
"max_line_length": 80,
"num_lines": 77,
"path": "/macros/do2Dplots.C",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "{\n\n gStyle->SetPalette(1);\n gStyle->SetOptStat(0);\n\n //TFile fIn(\"results/results_13TEV_40PU_50bx_2012GCT10GEV_RE-EMUL_RATE.root\");\n TFile fIn(\"results/results_13TEV_20PU_2015_RE-EMUL_RATE.root\");\n //TFile fIn(\"results/results_13TEV_40PU_2015_RE-EMUL_RATE.root\");\n fIn.cd();\n\n TH2F *nMuPtVsPt = (TH2F*)fIn.Get(\"nMuPtVsPt\");\n TH2F *nIsoElePtVsPt = (TH2F*)fIn.Get(\"nIsoEGPtVsPt\");\n TH2F *nEGPtVsPt = (TH2F*)fIn.Get(\"nEGPtVsPt\");\n TH2F *nOniaMuPtVsPt = (TH2F*)fIn.Get(\"nOniaMuPtVsPt\");\n TH2F *nMuVsHTT = (TH2F*)fIn.Get(\"nMuVsHTT\");\n TH2F *nAsymDiJetVsPt = (TH2F*)fIn.Get(\"nAsymDiJetVsPt\");\n TH2F *nAsymDiCenJetVsPt = (TH2F*)fIn.Get(\"nAsymDiCenJetVsPt\");\n TH2F *nMuVsEG = (TH2F*)fIn.Get(\"nMuVsEG\");\n TH2F *nEGIsoEGVsPt = (TH2F*)fIn.Get(\"nEGIsoEGVsPt\");\n\n nMuPtVsPt->GetXaxis()->SetRangeUser(6.5,20.);\n\n nEGPtVsPt->GetXaxis()->SetRangeUser(12.,30.);\n nEGPtVsPt->GetYaxis()->SetRangeUser(6.,30.);\n\n nOniaMuPtVsPt->GetXaxis()->SetRangeUser(3.,15.);\n\n nMuVsHTT->GetXaxis()->SetRangeUser(5.,15.);\n nMuVsHTT->GetYaxis()->SetRangeUser(60.,200.);\n\n nAsymDiJetVsPt->GetXaxis()->SetRangeUser(70.,120.);\n nAsymDiJetVsPt->GetYaxis()->SetRangeUser(40.,120.);\n\n nAsymDiCenJetVsPt->GetXaxis()->SetRangeUser(60.,120.);\n nAsymDiCenJetVsPt->GetYaxis()->SetRangeUser(30.,120.);\n\n nMuVsEG->GetXaxis()->SetRangeUser(3.,15.);\n nMuVsEG->GetYaxis()->SetRangeUser(16.,25.);\n\n TCanvas c1(\"c1\",\"c\",1200,600); c1.cd();\n nMuPtVsPt->Draw(\"COLZ\");\n c1.SaveAs(\"results/comparePlots/nMuPtVsPt.gif\");\n\n TCanvas c2; c2.cd();\n nIsoElePtVsPt->Draw(\"COLZ\");\n c2.SaveAs(\"results/comparePlots/nIsoEGPtVsPt.gif\");\n\n TCanvas c3; c3.cd();\n nEGPtVsPt->Draw(\"COLZ\");\n c3.SaveAs(\"results/comparePlots/nEGPtVsPt.gif\");\n\n TCanvas c4(\"c4\",\"c\",1200,600); c4.cd();\n nOniaMuPtVsPt->Draw(\"COLZ\");\n c4.SaveAs(\"results/comparePlots/nOniaMuPtVsPt.gif\");\n\n TCanvas c5; c5.cd();\n nMuVsHTT->Draw(\"COLZ\");\n c5.SaveAs(\"results/comparePlots/nMuVsHTT.gif\");\n\n TCanvas c6(\"c6\",\"c\",1200,600); c6.cd();\n nAsymDiJetVsPt->Draw(\"COLZ\");\n c6.SaveAs(\"results/comparePlots/nAsymDiJetVsPt.gif\");\n\n TCanvas c7(\"c7\",\"c\",1200,600); c7.cd();\n nAsymDiCenJetVsPt->Draw(\"COLZ\");\n c7.SaveAs(\"results/comparePlots/nAsymDiCenJetVsPt.gif\");\n\n TCanvas c8; c8.cd();\n nMuVsEG->Draw(\"COLZ\");\n c8.SaveAs(\"results/comparePlots/nMuVsEG.gif\");\n\n TCanvas c9(\"c9\",\"c\",1200,600); c9.cd();\n nEGIsoEGVsPt->Draw(\"COLZ\");\n c9.SaveAs(\"results/comparePlots/nEGIsoEGVsPt.gif\");\n\n\n}\n"
},
{
"alpha_fraction": 0.46748602390289307,
"alphanum_fraction": 0.5090502500534058,
"avg_line_length": 33.68992233276367,
"blob_id": "d2469d4927afb32aebe15efbddb5edc1bceebbb8",
"content_id": "3be0763acb77b4a532d805e48a29991c33840e79",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4475,
"license_type": "no_license",
"max_line_length": 97,
"num_lines": 129,
"path": "/macros/plot/GetRateStep.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n\n# File : GetRateStep.py\n# Author : Zhenbin Wu\n# Contact : [email protected]\n# Date : 2016 Feb 29\n#\n# Description : \n\n\nfrom ROOT import *\nimport ROOT\nfrom sys import argv\nimport os\nimport copy\nfrom Config import DualMap\nimport re\nimport matplotlib.pyplot as plt\n\nfilename = \"./r259721_tsgv3_rate_test.root\"\n# filename = \"./r259721_tsgv3_rate.root\"\nfolder = \"Rate\"\nmargin2D = 0.005\nfraction = [1, 0.55, 0.25, 0, -0.2, -0.35, -0.5, -0.6]\nobjectStart = {\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SingleEG ~~~~~\n \"nEGVsPt\" : 34, # SingleEG\n #\"nEGErVsPt\" : 100, # SingleEGer\n \"nIsoEGVsPt\" : 24, # SingleIsoEG\n \"nIsoEGerVsPt\" : 22, # SingleIsoEG\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SingleMu ~~~~~\n \"nMuVsPt\" : 25, # SingleMu\n \"nMuErVsPt\" : 18, # SingleMu |#eta|<2.1\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SingleJet ~~~~~\n # \"nJetCenVsPt\" : 100, # SingleJetCentral\n \"nJetVsPt\" : 150, # SingleJet\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ SingleTau ~~~~~\n # \"nIsoTauErVsPt\" : 100, # SingleIsoTauEr\n # \"nIsoTauVsPt\" : 100, # SingleIsoTau\n # \"nTauErVsPt\" : 100, # SingleTauer\n # \"nTauVsPt\" : 100, # SingleTau\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Sums ~~~~~\n # \"nETMVsETM\" : 100, # ETM\n # \"nETTVsETT\" : 100, # ETT\n # \"nHTMVsHTM\" : 100, # HTM\n \"nHTTVsHTT\" : 280, # HTT\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DoubleTrigger on the low pt leg ~~~~~\n # \"nDiCenJetVsPt\" : 100, # DiCenJet\n # \"nDiEGVsPt\" : 100, # DiEG\n # \"nDiIsoEGVsPt\" : 100, # DiIsoEG\n # \"nDiJetVsPt\" : 100, # DiJet\n # \"nDiTauVsPt\" : 100, # DiTau\n # \"nQuadCenJetVsPt\" : 100, # QuadCenJet\n # \"nQuadJetVsPt\" : 100, # QuadJet\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ DoubleTrigger in 2D ~~~~~\n \"nAsymDiCenJetVsPt\" : (100, 100), # DiCenJet\n # \"nAsymDiJetVsPt\" : (100, 100), # DiJet\n \"nEGPtVsPt\" : (18, 17), # DoubleEle\n # \"nIsoEGPtVsPt\" : (100, 100), # DoubleIsolEle\n \"nMuPtVsPt\" : (12, 5), # DoubleMu\n # \"nOniaMuPtVsPt\" : (100, 100), # DoubleMu_Er_HighQ_WdEta22 (Quarkonia)\n}\n\n\n\n\ndef GetRateVariation2D(h, value):\n if len(value) != 2:\n print \"Wrong value for 2D!\"\n return False\n orgrate = h.GetBinContent(h.FindBin(value[0], value[1]))\n\n for frac in fraction:\n ibins = GetRate2D(h, orgrate * (1+frac) )\n # at %d, with rate %d+-%d Hz\" % \\\n if len(ibins) == 0:\n print \"Varying %d%%(+-%d%%), thresholds and rates : None\" % (frac *100, margin2D*100)\n continue\n print \"Varying %d%%(+-%d%%), thresholds and rates :\" % (frac *100, margin2D*100),\n for ibin in ibins:\n print \"[%d, %d] with %d+-%d Hz\" % \\\n (h.GetXaxis().GetBinCenter(ibin[0]),h.GetYaxis().GetBinCenter(ibin[1]), \\\n h.GetBinContent(ibin[0], ibin[1]), h.GetBinError(ibin[0], ibin[1]))\n\n\n\n\n\ndef GetRateVariation1D(h, value):\n bVali = {}\n for i in range(1, h.GetNbinsX()):\n bVali[h.GetBinCenter(i)] = i\n # print h.GetBinCenter(i), h.GetBinContent(i), h.GetBinError(i)\n orgrate = h.GetBinContent(bVali[value])\n for frac in fraction:\n ibin = GetRate1D(h, orgrate * (1+frac) )\n print \"Varying %d%%, threshold at %d, with rate %d+-%d Hz\" % \\\n (frac *100, h.GetBinCenter(ibin), h.GetBinContent(ibin), h.GetBinError(ibin))\n\n\ndef GetRate2D(h, rate):\n matchbin = []\n for i in range(1, h.GetNbinsX()):\n for j in range(1, h.GetNbinsY()):\n bincont = h.GetBinContent(i, j)\n if fabs(float(bincont) / rate - 1 ) <= margin2D:\n matchbin.append([i, j])\n return matchbin\n\ndef GetRate1D(h, rate):\n valueMap = {}\n for i in range(1, h.GetNbinsX()):\n valueMap[h.GetBinContent(i)] = i\n minValue = min(valueMap.keys(), key=lambda x:abs(x-rate))\n return valueMap[minValue]\n\ndef GetRateVariation(h, value):\n if isinstance(value, tuple):\n return GetRateVariation2D(h, value)\n else:\n pass\n return GetRateVariation1D(h, value)\n\nif __name__ == \"__main__\":\n file = ROOT.TFile(filename, \"OPEN\")\n for k,v in objectStart.items():\n f = file.Get(\"Rate/%s\" % k)\n print \"------- for %s\" % f.GetTitle()\n GetRateVariation(f, v)\n"
},
{
"alpha_fraction": 0.6698994040489197,
"alphanum_fraction": 0.6793283224105835,
"avg_line_length": 50.55555725097656,
"blob_id": "5a5545be0e4cad1b36eb05321fbd9bbb7d899f65",
"content_id": "d4b6f2ff0e50a9aa9922dd9665d383b259f328ed",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11136,
"license_type": "no_license",
"max_line_length": 140,
"num_lines": 216,
"path": "/python/reEmulation_cff.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "import FWCore.ParameterSet.Config as cms\n\ndef reEmulation(process, reEmulMuons=True, reEmulCalos=True, patchNtuple=True, runOnPostLS1 = True, useStage1Layer2=True, reEmulRCT = True):\n\n print \"[L1Menu]: Setting up overall re-emulation\" \n\n if patchNtuple and hasattr(process,'l1NtupleProducer') and hasattr(process,'l1ExtraTreeProducer') :\n print \"[L1Menu]:\\tConfiguring Ntuple to use re-emulated information\" \n ntuple = getattr(process,'l1NtupleProducer')\n l1ExtraNtuple = getattr(process,'l1ExtraTreeProducer')\n elif patchNtuple :\n print \"[L1Menu]:\\tERROR: FAILED to find ntuple! switching patchNtuple to False\" \n patchNtuple=False\n\n process.l1ExtraReEmul = cms.EDProducer(\n \"L1ExtraParticlesProd\",\n muonSource = cms.InputTag(\"gtDigis\"),\n isolatedEmSource = cms.InputTag(\"gctDigis\",\"isoEm\"),\n nonIsolatedEmSource = cms.InputTag(\"gctDigis\",\"nonIsoEm\"),\n \n forwardJetSource = cms.InputTag(\"gctDigis\",\"forJets\"),\n centralJetSource = cms.InputTag(\"gctDigis\",\"cenJets\"),\n tauJetSource = cms.InputTag(\"gctDigis\",\"tauJets\"),\n isoTauJetSource = cms.InputTag(\"gctDigis\",\"isoTauJets\"),\n \n etTotalSource = cms.InputTag(\"gctDigis\"),\n etHadSource = cms.InputTag(\"gctDigis\"),\n etMissSource = cms.InputTag(\"gctDigis\"),\n htMissSource = cms.InputTag(\"gctDigis\"),\n \n hfRingEtSumsSource = cms.InputTag(\"gctDigis\"),\n hfRingBitCountsSource = cms.InputTag(\"gctDigis\"),\n \n produceMuonParticles = cms.bool(True),\n produceCaloParticles = cms.bool(True),\n centralBxOnly = cms.bool(True),\n ignoreHtMiss = cms.bool(False)\n )\n \n if reEmulMuons :\n print \"[L1Menu]:\\tSetting up muon re-emulation\" \n \n from L1Trigger.DTTrackFinder.dttfDigis_cfi import dttfDigis\n process.dttfReEmulDigis = dttfDigis.clone()\n process.dttfReEmulDigis.DTDigi_Source = cms.InputTag(\"dttfDigis\")\n process.dttfReEmulDigis.CSCStub_Source = cms.InputTag(\"csctfReEmulTrackDigis\")\n\n from L1Trigger.RPCTrigger.rpcTriggerDigis_cfi import rpcTriggerDigis\n process.rpcTriggerReEmulDigis = rpcTriggerDigis.clone()\n\n if not runOnPostLS1 :\n from L1Trigger.CSCTrackFinder.csctfTrackDigis_cfi import csctfTrackDigis\n from L1Trigger.CSCTrackFinder.csctfDigis_cfi import csctfDigis\n \n process.csctfReEmulTrackDigis = csctfTrackDigis.clone()\n process.csctfReEmulDigis = csctfDigis.clone()\n \n process.csctfReEmulTrackDigis.readDtDirect = True\n process.csctfReEmulTrackDigis.SectorReceiverInput = cms.untracked.InputTag(\"csctfDigis\")\n process.csctfReEmulTrackDigis.DtDirectProd = cms.untracked.InputTag(\"csctfDigis\",\"DT\")\n process.csctfReEmulDigis.CSCTrackProducer = cms.untracked.InputTag(\"csctfReEmulTrackDigis\")\n \n process.csctfReEmulSequence = cms.Sequence(\n process.csctfReEmulTrackDigis\n * process.csctfReEmulDigis\n )\n else :\n from SLHCUpgradeSimulations.Configuration.muonCustoms import customise_csc_L1Emulator_sim\n from L1Trigger.CSCTrackFinder.csctfDigis_cfi import csctfDigis\n\n customise_csc_L1Emulator_sim(process) \n\n process.csctfReEmulTrackDigis = process.simCsctfTrackDigis.clone()\n process.csctfReEmulDigis = csctfDigis.clone()\n\n process.csctfReEmulTrackDigis.DTproducer = cms.untracked.InputTag(\"dttfDigis\")\n process.csctfReEmulDigis.CSCTrackProducer = cms.untracked.InputTag(\"csctfReEmulTrackDigis\")\n\n process.csctfReEmulTrackDigis.SectorProcessor.PTLUT.PtMethod = cms.untracked.uint32(34) # no triple ganging in ME11a\n process.csctfReEmulTrackDigis.SectorProcessor.gangedME1a = cms.untracked.bool(False)\n process.csctfReEmulTrackDigis.SectorProcessor.firmwareSP = cms.uint32(20140515) #core 20120730\n process.csctfReEmulTrackDigis.SectorProcessor.initializeFromPSet = cms.bool(True) \n\n process.csctfReEmulSequence = cms.Sequence(\n process.simCscTriggerPrimitiveDigis\n * process.csctfReEmulTrackDigis\n * process.csctfReEmulDigis\n )\n\n process.load('L1TriggerConfig.GMTConfigProducers.L1MuGMTParameters_cfi')\n process.L1MuGMTParameters.MergeMethodPtBrl=cms.string(\"byCombi\")\n process.L1MuGMTParameters.MergeMethodPtFwd=cms.string(\"byCombi\")\n process.L1MuGMTParameters.VersionSortRankEtaQLUT = cms.uint32(1043)\n process.L1MuGMTParameters.VersionLUTs = cms.uint32(1)\n\n\n from L1Trigger.GlobalMuonTrigger.gmtDigis_cfi import gmtDigis\n process.gmtReEmulDigis = gmtDigis.clone()\n\n process.gmtReEmulDigis.DTCandidates = cms.InputTag(\"dttfReEmulDigis\",\"DT\")\n process.gmtReEmulDigis.CSCCandidates = cms.InputTag(\"csctfReEmulDigis\",\"CSC\")\n process.gmtReEmulDigis.RPCbCandidates = cms.InputTag(\"rpcTriggerReEmulDigis\",\"RPCb\")\n process.gmtReEmulDigis.RPCfCandidates = cms.InputTag(\"rpcTriggerReEmulDigis\",\"RPCf\")\n process.gmtReEmulDigis.MipIsoData = cms.InputTag(\"none\")\n \n process.l1ExtraReEmul.muonSource = cms.InputTag(\"gmtReEmulDigis\") \n\n if patchNtuple :\n ntuple.gmtSource = cms.InputTag(\"gmtReEmulDigis\")\n ntuple.dttfSource = cms.InputTag(\"dttfReEmulDigis\")\n ntuple.csctfTrkSource = cms.InputTag(\"csctfReEmulTrackDigis\")\n ntuple.csctfStatusSource = cms.InputTag(\"csctfReEmulTrackDigis\")\n\n l1ExtraNtuple.muonLabel = cms.untracked.InputTag(\"l1ExtraReEmul\")\n\n process.reEmulMuonChain = cms.Sequence(\n process.rpcTriggerReEmulDigis\n *process.csctfReEmulSequence\n *process.dttfReEmulDigis\n *process.gmtReEmulDigis\n )\n\n if reEmulCalos :\n print \"[L1Menu]:\\tSetting up calo re-emulation\" \n\n ## redo ECAL TP's\n ##\n #from SimCalorimetry.EcalTrigPrimProducers.ecalTriggerPrimitiveDigis_cff import simEcalTriggerPrimitiveDigis\n #process.ecalReEmulDigis = simEcalTriggerPrimitiveDigis.clone()\n #process.ecalReEmulDigis.InstanceEB = cms.string('ebDigis')\n #process.ecalReEmulDigis.InstanceEE = cms.string('eeDigis')\n #process.ecalReEmulDigis.Label = cms.string('ecalDigis')\n \n if reEmulRCT :\n from L1Trigger.Configuration.SimL1Emulator_cff import simRctDigis\n process.rctReEmulDigis = process.simRctDigis.clone()\n process.rctReEmulDigis.ecalDigis = cms.VInputTag( cms.InputTag( 'ecalDigis:EcalTriggerPrimitives' ) )\n ##process.rctReEmulDigis.ecalDigis = cms.VInputTag( cms.InputTag( 'ecalReEmulDigis' ) )\n process.rctReEmulDigis.hcalDigis = cms.VInputTag( cms.InputTag( 'hcalDigis' ) )\n\n from L1Trigger.GlobalCaloTrigger.gctDigis_cfi import gctDigis\n\n process.gctReEmulDigis = gctDigis.clone() \n process.gctReEmulDigis.inputLabel = cms.InputTag(\"gctDigis\")\n\n process.l1ExtraReEmul.isolatedEmSource = cms.InputTag(\"gctReEmulDigis\",\"isoEm\")\n process.l1ExtraReEmul.nonIsolatedEmSource = cms.InputTag(\"gctReEmulDigis\",\"nonIsoEm\")\n\n process.l1ExtraReEmul.forwardJetSource = cms.InputTag(\"gctReEmulDigis\",\"forJets\")\n process.l1ExtraReEmul.centralJetSource = cms.InputTag(\"gctReEmulDigis\",\"cenJets\")\n process.l1ExtraReEmul.tauJetSource = cms.InputTag(\"gctReEmulDigis\",\"tauJets\")\n process.l1ExtraReEmul.isoTauJetSource = cms.InputTag(\"gctReEmulDigis\",\"isoTauJets\") \n\n process.l1ExtraReEmul.etTotalSource = cms.InputTag(\"gctReEmulDigis\")\n process.l1ExtraReEmul.etHadSource = cms.InputTag(\"gctReEmulDigis\")\n process.l1ExtraReEmul.etMissSource = cms.InputTag(\"gctReEmulDigis\")\n process.l1ExtraReEmul.htMissSource = cms.InputTag(\"gctReEmulDigis\")\n\n process.l1ExtraReEmul.hfRingEtSumsSource = cms.InputTag(\"gctReEmulDigis\")\n process.l1ExtraReEmul.hfRingBitCountsSource = cms.InputTag(\"gctReEmulDigis\")\n\n if patchNtuple :\n ntuple.gctCentralJetsSource = cms.InputTag(\"gctReEmulDigis\",\"cenJets\")\n ntuple.gctNonIsoEmSource = cms.InputTag(\"gctReEmulDigis\",\"nonIsoEm\")\n ntuple.gctForwardJetsSource = cms.InputTag(\"gctReEmulDigis\",\"forJets\")\n ntuple.gctIsoEmSource = cms.InputTag(\"gctReEmulDigis\",\"isoEm\")\n ntuple.gctEnergySumsSource = cms.InputTag(\"gctReEmulDigis\",\"\")\n ntuple.gctTauJetsSource = cms.InputTag(\"gctReEmulDigis\",\"tauJets\")\n if useStage1Layer2:\n ntuple.gctIsoTauJetsSource = cms.InputTag(\"gctReEmulDigis\",\"isoTauJets\")\n else:\n ntuple.gctIsoTauJetsSource = cms.InputTag(\"none\",\"isoTauJets\")\n\n l1ExtraNtuple.nonIsoEmLabel = cms.untracked.InputTag(\"l1ExtraReEmul:NonIsolated\")\n l1ExtraNtuple.isoEmLabel = cms.untracked.InputTag(\"l1ExtraReEmul:Isolated\")\n l1ExtraNtuple.tauJetLabel = cms.untracked.InputTag(\"l1ExtraReEmul:Tau\")\n l1ExtraNtuple.isoTauJetLabel = cms.untracked.InputTag(\"l1ExtraReEmul:IsoTau\")\n l1ExtraNtuple.cenJetLabel = cms.untracked.InputTag(\"l1ExtraReEmul:Central\")\n l1ExtraNtuple.fwdJetLabel = cms.untracked.InputTag(\"l1ExtraReEmul:Forward\")\n l1ExtraNtuple.metLabel = cms.untracked.InputTag(\"l1ExtraReEmul:MET\")\n l1ExtraNtuple.mhtLabel = cms.untracked.InputTag(\"l1ExtraReEmul:MHT\")\n\n\n if reEmulRCT :\n process.gctReEmulDigis.inputLabel = cms.InputTag(\"rctReEmulDigis\")\n process.reEmulCaloChain = cms.Sequence(\n #process.hcalReEmulDigis\n #process.ecalReEmulDigis\n process.rctReEmulDigis\n *process.gctReEmulDigis\n )\n else :\n process.reEmulCaloChain = cms.Sequence(\n process.gctReEmulDigis\n )\n\n from L1Trigger.GlobalTrigger.gtDigis_cfi import gtDigis\n process.gtReEmulDigis = gtDigis.clone()\n\n if reEmulMuons :\n process.gtReEmulDigis.GmtInputTag = cms.InputTag(\"gmtReEmulDigis\")\n\n if reEmulCalos :\n process.gtReEmulDigis.GctInputTag = cms.InputTag(\"gctReEmulDigis\")\n\n if patchNtuple :\n ntuple.gtSource = cms.InputTag(\"gtReEmulDigis\")\n \n if reEmulMuons and reEmulCalos :\n process.reEmul = cms.Sequence(process.reEmulCaloChain + process.reEmulMuonChain + process.gtReEmulDigis + process.l1ExtraReEmul)\n elif reEmulMuons :\n process.reEmul = cms.Sequence(process.reEmulMuonChain + process.gtReEmulDigis + process.l1ExtraReEmul)\n elif reEmulCalos :\n process.reEmul = cms.Sequence(process.reEmulCaloChain + process.gtReEmulDigis + process.l1ExtraReEmul)\n else :\n process.reEmul = cms.Sequence(process.gtReEmulDigis + process.l1ExtraReEmul)\n"
},
{
"alpha_fraction": 0.5267386436462402,
"alphanum_fraction": 0.5800843238830566,
"avg_line_length": 32.008697509765625,
"blob_id": "c4926df385cd0b0b7753b99f0078f267ed5d23f5",
"content_id": "b32a9a4de3df8d938a9589b1c74f4c2d67acd6e8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7592,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 230,
"path": "/macros/batch/SubmitLPC.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "#!/bin/env python\n# Example PBS cluster job submission in Python\n\nimport os\nimport time\nimport glob\nimport re\nimport subprocess\nimport tarfile\nimport time\n\n###############################\nDelDir = None #Auto pick up by CMSSW_BASE\ntempdir =None\nProjectName = None\nDryRun = False\nDelExe = 'testMenu2016'\nOutDir = '/store/user/benwu/L1MenuStage2/TSGv4'\nAnalysis = 'test'\nMenuFile = [\n #\"menu/Menu_MuonStudy.txt\",\n #\"menu/Menu_None.txt\"\n #\"menu/Menu_259721_TSGv4_Riccardo.txt\"\n # \"menu/Menu_259721_TSGv4_Prescales.txt\",\n # \"menu/Menu_259721_TSGv3_FixPre_EG.txt\",\n \"menu/Menu_259721_TSGv4_FixPre.txt\",\n # \"menu/Menu_ETMStudy.txt\",\n]\nNtuplelist = [\n #\"ntuple/r259721_tsgv4Latest.list\"\n # \"ntuple/r259721_tsgv3.list\",\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TSG-v4 ~~~~~\n #\"ntuple/MC10PU_tsgv4.list\",\n #\"ntuple/MC20PU_tsgv4.list\",\n #\"ntuple/MC30PU_tsgv4.list\",\n #\"ntuple/MC40PU_tsgv4.list\",\n #\"ntuple/MC50PU_tsgv4.list\",\n #\"ntuple/r258425_tsgv4.list\",\n #\"ntuple/r258427_tsgv4.list\",\n #\"ntuple/r258428_tsgv4.list\",\n #\"ntuple/r258434_tsgv4.list\",\n #\"ntuple/r258440_tsgv4.list\",\n #\"ntuple/r258445_tsgv4.list\",\n #\"ntuple/r258448_tsgv4.list\",\n #\"ntuple/r259626_tsgv4.list\",\n #\"ntuple/r259721_tsgv4.list\",\n \"ntuple/r259721_tsgv4ZB1.list\",\n # \"ntuple/SingleMuZmu_tsgv4.list\",\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TSGv4-METFix ~~~~~\n #\"ntuple/r259721_tsgv4METfix.list\",\n #\"ntuple/r259721_tsgv4.list\",\n #\"ntuple/r259721_gomber.list\",\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Integration v19 ~~~~~\n #\"ntuple/r258440_itgv19Layer1.list\",\n #\"ntuple/r258440_itgv19.list\",\n #\"ntuple/r259626_itgv19Layer1.list\",\n #\"ntuple/r259626_itgv19.list\",\n #\"ntuple/r259721_itgv19Layer1.list\",\n # \"ntuple/r259721_itgv19.list\",\n # \"ntuple/SingleMuZmu_itgv19Layer1.list\",\n # \"ntuple/SingleMuZmu_itgv19.list\",\n]\nGlobalOpt = \" \"\nGlobalOpt += \" --doPlotEff\"\nGlobalOpt += \" --doPlotRate\"\nGlobalOpt += \" --doPlotTest\"\n#GlobalOpt += \" --doPlotRate --doPrintPU\"\n# GlobalOpt = \" --doPrintPU\"\nOptions = {\n #None:\"\"\n \"test\" : \"-n 10000\"\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Muon ER Study ~~~~~\n #\"MuER0p8\" : \"--SetMuonER 0.8\",\n #\"MuER1p2\" : \"--SetMuonER 1.25\",\n #\"MuER1p5\" : \"--SetMuonER 1.5\",\n #\"MuER1p8\" : \"--SetMuonER 1.8\",\n #\"MuER2p0\" : \"--SetMuonER 2.0\",\n #\"MuER2p1\" : \"--SetMuonER 2.1\",\n #\"MuER2p2\" : \"--SetMuonER 2.2\",\n #\"MuER2p3\" : \"--SetMuonER 2.3\",\n #\"MuER2p4\" : \"--SetMuonER 2.4\",\n #\"MuER2p5\" : \"--SetMuonER 2.5\",\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Muon Turn on Study ~~~~~\n #\"r258425\" : \"--SelectRun 258425\",\n #\"r258427\" : \"--SelectRun 258427\",\n #\"r258428\" : \"--SelectRun 258428\",\n #\"r258434\" : \"--SelectRun 258434\",\n #\"r258440\" : \"--SelectRun 258440\",\n #\"r258445\" : \"--SelectRun 258445\",\n #\"r258448\" : \"--SelectRun 258448\",\n #\"r259626\" : \"--SelectRun 259626\",\n #\"r259721\" : \"--SelectRun 259721\",\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MET Cross Check ~~~~~\n #\"Default\" : \"\",\n #\"Bitwise\" : \"--UseUpgradeLyr1\",\n #\"CaloTower\" : \"--UseL1CaloTower\",\n\n}\nnBunches = 3963.7\n\ndef CondorSub(Analysis, Menu, Ntuple, Option):\n npro =[ \"%s/ntuple.tgz\" % tempdir, \"%s/menu.tgz\" % tempdir]\n npro.append( DelExe )\n\n ## Update RunHT.csh with DelDir and pileups\n RunHTFile = tempdir + \"/\" + \"RunExe.csh\"\n with open(RunHTFile, \"wt\") as outfile:\n for line in open(\"%s/RunExe.csh\" % os.path.dirname(os.path.realpath(__file__)), \"r\"):\n #line = line.replace(\"DELDIR\", os.environ['PWD'])\n line = line.replace(\"DELDIR\", os.environ['CMSSW_BASE'])\n line = line.replace(\"DELEXE\", DelExe.split('/')[-1])\n line = line.replace(\"OUTDIR\", OutDir)\n outfile.write(line)\n\n\n stripMenu = os.path.splitext(os.path.basename(Menu))[0]\n stripNtuple = os.path.splitext(os.path.basename(Ntuple))[0]\n job_name = \"%s_%s_%s_%s\" % (Analysis, stripMenu, stripNtuple, Option[0])\n if len(MenuFile) == 1:\n out_name = \"_\".join(filter(None, (stripNtuple, Option[0])))\n else:\n out_name = \"_\".join(filter(None, (stripMenu, stripNtuple, Option[0])))\n\n arg = \" %s -m %s -l %s -o %s -b %f %s\" % (Option[1], Menu, Ntuple,out_name, nBunches, GlobalOpt)\n cmd = \"./%s %s\" % (os.path.basename(DelExe), arg )\n if DryRun:\n print cmd\n return\n\n tranferfiles = \", \".join(npro)\n arg = \"\\nArguments = %s \\n Queue\\n\" % arg\n ## Prepare the condor file\n condorfile = tempdir + \"/\" + \"condor_\" + ProjectName\n with open(condorfile, \"wt\") as outfile:\n for line in open(\"%s/condor_template\" % os.path.dirname(os.path.realpath(__file__)), \"r\"):\n line = line.replace(\"EXECUTABLE\", os.path.abspath(RunHTFile))\n #line = line.replace(\"DELDIR\", os.environ['CMSSW_BASE'])\n line = line.replace(\"TARFILES\", tranferfiles)\n line = line.replace(\"TEMPDIR\", tempdir)\n line = line.replace(\"PROJECTNAME\", ProjectName)\n line = line.replace(\"ARGUMENTS\", arg)\n outfile.write(line)\n\n Condor_Sub(condorfile)\n time.sleep(1)\n\ndef my_process():\n global OutDir\n global tempdir\n global ProjectName\n ## Some checking first\n my_CheckFile()\n\n ## Create the output directory\n try:\n os.makedirs(OutDir)\n except OSError:\n pass\n\n ProjectName = time.strftime('%b%d') + Analysis\n tempdir = '/tmp/' + os.getlogin() + \"/\" + ProjectName + \"/\"\n try:\n os.makedirs(tempdir)\n except OSError:\n pass\n ## Create the output directory\n OutDir = OutDir + \"/\" + ProjectName + \"/\"\n try:\n os.makedirs(OutDir)\n except OSError:\n pass\n\n curdir = os.path.abspath(os.path.curdir)\n os.chdir(os.path.dirname(os.path.realpath(__file__)))\n os.chdir(\"../\")\n subprocess.call(\"tar -czf %s/ntuple.tgz ntuple/\" % tempdir, shell=True)\n subprocess.call(\"tar -czf %s/menu.tgz menu/\" % tempdir, shell=True)\n os.chdir(curdir)\n\n for menu in MenuFile:\n for ntuple in Ntuplelist:\n for opt in Options.items():\n #print Analysis, menu, ntuple, opt\n CondorSub(Analysis, menu, ntuple, opt)\n\ndef my_CheckFile():\n global DelDir\n global DelExe\n ## Check the Delphes Dir\n DelDir = \"%s/src/L1TriggerDPG/L1Menu/macros/\" % os.environ['CMSSW_BASE']\n\n ## Check DelFill to be execute\n DelExe = DelDir + \"/\" + DelExe\n if os.path.isfile(DelExe) and os.access(DelExe, os.X_OK):\n #print \"Found DelFill\"\n pass\n else:\n DelExe = DelDir + \"/\" + DelExe.split(\"/\")[-1]\n if os.path.isfile(DelExe) and os.access(DelExe, os.X_OK):\n #print \"Found DelFill\"\n pass\n else:\n print \"Please locate %s\" % DelExe\n quit()\n\n\ndef Condor_Sub(condor_file):\n ## Since we run with xrootd, setup proxy\n #hasproxy = False\n #proxyfile = ''\n #if os.environ.has_key('X509_USER_PROXY'):\n #proxyfile = os.path.abspath(os.environ['X509_USER_PROXY'])\n #else:\n #hasproxy = False\n #if not hasproxy or not os.path.exists(proxyfile) or (time.time() - os.stat(proxyfile).st_ctime) / 60/24 > 1:\n #print \"Proxy file is at least one day old. Requesting new proxy\"\n #os.system(\"voms-proxy-init -valid 168:00 -voms cms\")\n\n curdir = os.path.abspath(os.path.curdir)\n os.chdir(os.path.dirname(condor_file))\n print \"To submit condor with \" + condor_file\n os.system(\"condor_submit \" + condor_file)\n os.chdir(curdir)\n\n\n\nif __name__ == \"__main__\":\n my_process()\n"
},
{
"alpha_fraction": 0.534254789352417,
"alphanum_fraction": 0.5628004670143127,
"avg_line_length": 29.5321102142334,
"blob_id": "a6fe897a32b7010856e3d450bb1429a967925e39",
"content_id": "7f4d5ef4e5c2602c0be327e1afb29089a3d81862",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3328,
"license_type": "no_license",
"max_line_length": 234,
"num_lines": 109,
"path": "/macros/ntuple/GetFileList.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n\n# File : GetFileList.py\n# Author : Ben Wu\n# Contact : [email protected]\n# Date : 2016 Apr 02\n#\n# Description :\n\nimport subprocess\nimport re\nfrom makeFileList import EOS\nfrom collections import defaultdict\n\nntupleMap = {\n # \"r271336_itgv42p1\" : \"~/eos/cms/store/group/dpg_trigger/comm_trigger/L1Trigger/L1Menu2016/Stage2/l1t-integration-v42p1/ZeroBias1/crab_l1t-integration-v42p1__271336_ZeroBias1/160426_220107/0000/\",\n \"r*_v78Calo\" : \"/eos/uscms/store/group/lpctrig/apana/L1Menu_2016/Stage2/Collision2016-noRECO-l1t-integration-v78p0_CaloStage2Params_v2_2/ZeroBias/crab_Collision2016-noRECO-l1t-integration-v78p0_CaloStage2Params_v2_2__*_ZeroBias/\",\n}\n\ndef GetEOSdir(v):\n redir =\"\"\n if v.find(\"/eos\") != -1:\n findstore = v.find(\"/store\", v.find(\"/eos\"))\n redir = v[findstore:]\n else:\n redir = v\n return redir\n\ndef GetList(k, v, opt='w+'):\n f = open(k+\".list\", opt)\n eosdir = GetEOSdir(v)\n print eosdir\n p = subprocess.Popen('./makeFileList.py %s' % eosdir, shell=True, stdout=f, close_fds=True)\n rec_code = p.wait()\n f.flush()\n return rec_code\n\ndef GetNtuleList():\n for k,v in ntupleMap.items():\n if '*' in k:\n GetZBLists(k , v)\n else:\n GetList(k, v)\n\ndef EOSls(eosdir):\n cmd = \" \".join( [EOS, \"ls\", eosdir] )\n p1 = subprocess.Popen(cmd, shell=True, stdout=subprocess.PIPE)\n stdout, stderr= p1.communicate()\n if stderr is not None:\n print \"Trouble executing the srmls command\"\n sys.exit(1)\n return stdout.split()\n\ndef GetZBlist(k, v):\n tempvlist = []\n for tempv in v:\n jdate = EOSls(tempv)\n if len(jdate) ==1:\n tempv +=\"/\"+jdate[0]\n else:\n print \"Multiple jobs: \",\n for i in range(len(jdate)):\n print \"(%d) %s\" % (i, jdate[i]),\n print \"\"\n # job = input(\"Which one?\")\n # tempv += \"/\"+jdate[job]\n print max(jdate)\n tempv += \"/\"+max(jdate)\n jbatch = EOSls(tempv)\n for j in jbatch:\n tempvlist.append(tempv+\"/\"+j)\n for i in range(len(tempvlist)):\n if i==0:\n GetList(k, tempvlist[i])\n else:\n GetList(k, tempvlist[i], 'a')\n\ndef GetZBLists(k, v):\n import re\n rsearch = re.search('ZeroBias|ParkingZeroBias', v)\n if rsearch is None:\n return None\n zbhomedir = GetEOSdir(v[:rsearch.start()])\n lsdir = EOSls(zbhomedir)\n runmap = defaultdict(list)\n for zbdir in lsdir:\n if \"ZeroBias\" not in zbdir:\n continue\n dirpattern = GetEOSdir(v).replace(\"ZeroBias\", zbdir).replace(\"*\", \"(\\d+)\")\n if dirpattern[-1] == \"/\":\n dirpattern = dirpattern[:-1] + \"/*\"\n else:\n dirpattern = dirpattern + \"/*\"\n pat = re.compile(dirpattern)\n\n rundirs = EOSls(zbhomedir+\"/\"+zbdir)\n for rundir in rundirs:\n thisdir =\"/\".join([zbhomedir, zbdir, rundir])\n thisdir = thisdir.replace(\"//\", \"/\")\n mat = pat.match(thisdir)\n if mat is not None:\n run = mat.group(1)\n runmap[k.replace(\"*\", run)].append(thisdir)\n for k, v in runmap.items():\n GetZBlist(k, v)\n\nif __name__ == \"__main__\":\n GetNtuleList()\n"
},
{
"alpha_fraction": 0.5894378423690796,
"alphanum_fraction": 0.6127200722694397,
"avg_line_length": 27.8360652923584,
"blob_id": "5219cc77bbee2b735bf9da67363dc4a990eb9cb4",
"content_id": "6b7740d996f90b912bbaef93f3ac845ca68dcb6d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 1761,
"license_type": "no_license",
"max_line_length": 95,
"num_lines": 61,
"path": "/macros/Makefile",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "######### GENERAL STUFF: DON NOT CONSIDER\nODIR = objs\nCXX = g++\nCXXFLAGS = -std=c++11\nCXXFLAGS += -Wall -fPIC -O3\n#CXXFLAGS += -g -pg\n#CXXFLAGS += -Wextra\n#CXXFLAGS += -Wextra -Weffc++ #Asking for troubles\n#CXXFLAGS += -Wno-reorder #Dirty fix\nCXXFLAGS += $(subst -I, -isystem , $(shell root-config --cflags))\n\nLD = g++\nLDFLAGS =\nLIBS = $(shell root-config --libs) -lTable\n\nifneq ($(shell echo $$CMSSW_BASE), )\n CXXFLAGS += -isystem $(CMSSW_BASE)/src/\n CXXFLAGS += -isystem $(CMSSW_RELEASE_BASE)/src\n CXXFLAGS += -isystem $(shell scram tool info boost | awk -F\"=\" '/INCLUDE=(.*)/{print $$NF}')\n LIBS += -L$(CMSSW_BASE)/lib/$(SCRAM_ARCH)/ -L$(CMSSW_RELEASE_BASE)/lib/$(SCRAM_ARCH)/ \\\n\t\t -lFWCoreFWLite -lDataFormatsL1TGlobal\n LIBS += -L$(shell scram tool info boost | awk -F\"=\" '/LIBDIR=(.*)/{print $$NF}') \\\n\t\t -lboost_program_options -lboost_filesystem\nendif\n\nTestOBJS = L1Ntuple L1AlgoFactory L1Menu2016 L1Plot L1TnP L1uGT PreColumn\n\nifeq ($(wildcard menulib.cc)$(wildcard menulib.hh), menulib.ccmenulib.hh)\n CXXFLAGS += -DUTM_MENULIB\n TestOBJS += menulib\nendif\n\nOBJS := $(TestOBJS:%=$(ODIR)/%.o)\n\nPROGRAM = testMenu2016 RunL1Menu2016\n\nMKBIN = $(CXX) $(CXXFLAGS) `root-config --libs --cflags` -lMinuit -lGenVector\n\n$(ODIR)/%.o : %.C\n\t$(CXX) $(CXXFLAGS) $(CXXDEPFLAGS) -o $@ -c $<\n\n$(ODIR)/%.o : %.cc\n\t$(CXX) $(CXXFLAGS) $(CXXDEPFLAGS) -o $@ -c $<\n\nall : $(PROGRAM)\n\ncomparePlots : comparePlots.cc \n\t$(MKBIN) $< -o $@ \n\nRunL1Menu2016 : $(ODIR)/RunL1Menu2016.o $(OBJS)\n\t@echo \"Linking $(PROGRAM) ...\"\n\t$(LD) $^ $(LIBS) -o $@\n\t@echo \"done\"\n\ntestMenu2016 : $(ODIR)/testMenu2016.o $(OBJS)\n\t@echo \"Linking $(PROGRAM) ...\"\n\t$(LD) $^ $(LIBS) -o $@\n\t@echo \"done\"\n\nclean:\n\trm -f *exe *.o $(PROGRAM) $(OBJS) $(ODIR)/*.o\n\n\n"
},
{
"alpha_fraction": 0.4975094199180603,
"alphanum_fraction": 0.5643773674964905,
"avg_line_length": 25.606426239013672,
"blob_id": "d363277b2d32bae1dd45dd51c25a10c5be44c373",
"content_id": "7dcf03634b7da7307b6876fda5dbbe074dac4d50",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6625,
"license_type": "no_license",
"max_line_length": 113,
"num_lines": 249,
"path": "/macros/plot/CompPUDep.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# encoding: utf-8\n\n# File : CompHLT.py\n# Author : Zhenbin Wu\n# Contact : [email protected]\n# Date : 2016 Aug 25\n#\n# Description :\n\nimport pandas as pd\nimport numpy as np\nimport glob\nimport math\nimport ROOT\nimport collections\nimport os\nimport re\nimport tdrstyle\nimport rootpy\nfrom rootpy.interactive import wait\nfrom rootpy.io import root_open\nfrom matplotlib import pyplot as plt\nfrom Config import DualMap, S1S2Map, S2S1Map\n\n\nlabel = \"ZeroBias\"\nPU = 35\nfreq = 11245.6\nconfig = 2017\nfiledir = \"Nov192017EGTT28_v2/*CaloTower_PU.csv\"\nmaxy = 40\nif config == 2016:\n nBunches = 2208\n unit = \"kHz\"\nif config == 2017:\n nBunches = 2592\n unit = \"kHz\"\n\nif config == 1:\n nBunches = 1\n unit = \"Hz\"\n\npubins = np.arange(11,60, 1)\npumap = collections.defaultdict(list)\n\nPatMap = { \n # \"EG\" : \"L1_StrategyEG[34]\\d+\",\n \"ETM\" : \"L1_ETM\\d+\",\n # \"HTT\" : \"L1_HTT[23]\\d+\",\n # \"DEGHTT\" : \"L1_DoubleEG6_HTT.*\",\n # \"dPhi80\" : \"L1_ETM\\d+_Jet80_dPhi_Min0p4\",\n # \"dPhi60\" : \"L1_ETM\\d+_Jet60_dPhi_Min0p4\",\n # \"dETM80\" : \"L1_ETM80_Jet\\d+_dPhi_Min0p4\",\n # \"dETM100\" : \"L1_ETM100_Jet\\d+_dPhi_Min0p4\",\n # 'Mu6HTT': 'L1_Mu6_HTT2\\d+',\n # 'Mu8HTT': 'L1_Mu8_HTT2\\d+',\n # 'Mu5EG': 'L1_Mu5_EG2\\d+',\n # 'Mu6EG': 'L1_Mu6_EG2\\d+',\n # 'DMu': 'L1_DoubleMu0er.*_dEta_Max1p8_OS',\n # 'DEG12': 'L1_DoubleEG_\\d+_12',\n # 'DEG25': 'L1_DoubleEG_25_\\d+',\n # 'DTau': 'L1_DoubleIsoTau\\d+er',\n}\n\ndef DrawPU(canvas, f, l1seed, count, key=None):\n df = f[(f.L1Seed == l1seed )]\n RetVar = None\n\n for i in range(0, len(pubins) -1):\n pumap[pubins[i]] = []\n pumap[pubins[i]].append(df[np.logical_and(df.PileUp > pubins[i], df.PileUp <= pubins[i+1])].Fired0.sum())\n pumap[pubins[i]].append(df[np.logical_and(df.PileUp > pubins[i], df.PileUp <= pubins[i+1])].Total.sum())\n\n x = []\n y = []\n yerr = []\n for k, v in pumap.iteritems():\n if v[1] != 0:\n x.append(k)\n if unit == \"Hz\":\n y.append(float(v[0])/v[1] * freq * nBunches )\n yerr.append( math.sqrt(float(v[0]))/v[1] * freq * nBunches )\n if unit == \"kHz\":\n y.append(float(v[0])/v[1] * freq * nBunches / 1000)\n yerr.append( math.sqrt(float(v[0]))/v[1] * freq * nBunches / 1000)\n\n ## Draw the plot\n graph = ROOT.TGraphErrors(len(x))\n minx = min(x)\n maxx = max(x)\n\n for i, (xx, yy, yee) in enumerate(zip(x, y, yerr)):\n # if yy != 0 and yee/yy >0.3:\n # continue\n graph.SetPoint(i, xx, yy)\n graph.SetPointError(i, 0, yee)\n\n graph.SetMarkerStyle(20+count)\n graph.SetMarkerSize(1.5)\n graph.SetMarkerColor(1+count)\n graph.SetLineColor(1+count)\n graph.SetLineWidth(2)\n tdrstyle.setTDRStyle()\n canvas.cd()\n canvas.Update()\n if count == 0:\n graph.Draw(\"AP\")\n graph.GetXaxis().SetTitle(\"PileUp\")\n graph.GetXaxis().SetLimits(10, 70)\n graph.GetYaxis().SetRangeUser(0, maxy)\n graph.GetYaxis().SetTitle(\"Rate (nBunches = %d) [%s]\" % (nBunches, unit))\n else:\n graph.Draw(\"P\")\n canvas.Update()\n leg.AddEntry(graph, l1seed, \"p\")\n\n ## Pol2\n fitname = \"pol2\"\n graph.Fit(fitname, \"Q\", \"\", minx, max(x))\n f2 = graph.GetFunction(fitname).Clone()\n f2.SetLineColor(1+count)\n f2.SetLineWidth(2)\n fun = \"Fit = %.2f + %.2f*x + %.3f*x^2\" % (f2.GetParameter(0), f2.GetParameter(1), f2.GetParameter(2) )\n # f2.Draw(\"same\")\n f2_2 = f2.Clone(\"dashline2\")\n f2_2.SetRange(minx, 70)\n f2_2.SetLineStyle(5)\n # f2_2.Draw(\"same\")\n key = \"Rate(PU=%d): %.1f\" % (PU, f2_2.Eval(PU))\n tex = ROOT.TLatex(0.15, 0.75, fun)\n tex.SetNDC()\n tex.SetTextAlign(13)\n tex.SetTextFont(61)\n tex.SetTextSize(0.04)\n tex.SetTextColor(ROOT.kBlue)\n tex.SetLineWidth(2)\n # tex.Draw()\n\n\n if key is not None:\n tex = ROOT.TLatex(0.55, 0.85, key)\n tex.SetNDC()\n tex.SetTextFont(61)\n tex.SetTextSize(0.045)\n tex.SetTextColor(ROOT.kGreen+2)\n tex.SetLineWidth(2)\n # tex.Draw()\n\n # leg.Draw()\n canvas.Update()\n\n\ndef DrawL1(key, pattern):\n c1.Clear()\n leg.Clear()\n\n inputlist = []\n pat = re.compile('^%s$' % pattern)\n\n for x in [x for x in pd.unique(df.L1Seed)]:\n if pat.match(x):\n inputlist.append(x)\n print key, \" : \", inputlist\n\n for i, seed in enumerate(inputlist):\n DrawPU(c1, df, seed, i)\n leg.Draw()\n\n if config == 2016:\n l37 = ROOT.TLine(37, 0, 37, maxy)\n l37.SetLineColor(2)\n l37.SetLineWidth(2)\n l37.Draw()\n l40 = ROOT.TLine(40, 0, 40, maxy)\n l40.SetLineColor(2)\n l40.SetLineWidth(2)\n l40.Draw()\n l47 = ROOT.TLine(47, 0, 47, maxy)\n l47.SetLineColor(2)\n l47.SetLineWidth(2)\n l47.Draw()\n l52 = ROOT.TLine(52, 0, 52, maxy)\n l52.SetLineColor(2)\n l52.SetLineWidth(2)\n l52.Draw()\n\n if config == 2017:\n l47 = ROOT.TLine(47, 0, 47, maxy)\n l47.SetLineColor(2)\n l47.SetLineWidth(2)\n l47.Draw()\n l55 = ROOT.TLine(55, 0, 55, maxy)\n l55.SetLineColor(2)\n l55.SetLineWidth(2)\n l55.Draw()\n l60 = ROOT.TLine(60, 0, 60, maxy)\n l60.SetLineColor(2)\n l60.SetLineColor(2)\n l60.SetLineWidth(2)\n l60.Draw()\n\n tex = ROOT.TLatex(0.2, 0.3, \"%d Thresholds\" % config)\n tex.SetNDC()\n tex.SetTextAlign(13)\n tex.SetTextFont(61)\n tex.SetTextSize(0.04)\n tex.SetTextColor(ROOT.kBlue)\n tex.SetLineWidth(2)\n # tex.Draw()\n c1.SetGrid()\n\n\n box = ROOT.TBox(10, 8, 70, 12)\n box.SetFillColor(38)\n box.SetFillStyle(3002)\n\n c1.Update()\n c1.SaveAs(\"plots/%s_%d.root\" % (key, config))\n c1.SaveAs(\"plots/%s_%d.png\" % (key, config))\n c1.SaveAs(\"plots/%s_%d.pdf\" % (key, config))\n\nif __name__ == \"__main__\":\n allfiles = glob.glob(filedir)\n if not os.path.exists(\"plots\"):\n os.mkdir(\"plots\")\n\n df = pd.DataFrame()\n flist = [ ]\n for file_ in allfiles:\n df_ = pd.read_csv(file_, index_col=None, header=0)\n flist.append(df_)\n df = pd.concat(flist)\n\n ## Redefine PatMap for each L1Seed in the dataframe\n # PatMap = {k:k for k in pd.unique(df.L1Seed)}\n\n ROOT.gStyle.SetOptStat(000000000)\n tdrstyle.setTDRStyle()\n c1 = ROOT.TCanvas(\"fd\",\"Fdf\", 1200, 1000)\n leg = ROOT.TLegend(0.1711409,0.5412262,0.4714765,0.9238901)\n leg.SetFillColor(0)\n leg.SetBorderSize(0)\n leg.SetBorderSize(0)\n leg.SetFillStyle(0)\n leg.SetTextFont(62)\n for k, v in PatMap.items():\n DrawL1(k, v)\n # wait()\n"
},
{
"alpha_fraction": 0.6168041229248047,
"alphanum_fraction": 0.6281280517578125,
"avg_line_length": 30.235807418823242,
"blob_id": "b57a94bb40e551677c638f82eede9f8da9360567",
"content_id": "0fb6285c005992433ff0513e7f1a0d73b430d546",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7153,
"license_type": "no_license",
"max_line_length": 213,
"num_lines": 229,
"path": "/scripts/makeRateTuple.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "#!/bin/env python\n#\n# Author: Takashi MATSUSHITA\n#\n# Usage:\n# python makeRateTuple.py --runs 278986 278976 --user <database account>\n# for x in convert*.cc; do root -l -b -q $x; done # in bash\n#\n\nimport argparse\nimport sys\n\nimport cx_Oracle\n\n\ndef getLumiSections(options, run):\n query = \"\"\"select lhcfill, lumisection, instlumi, pileup, physics_flag from cms_runtime_logger.lumi_sections where runnumber = {0} order by lumisection\"\"\".format(run)\n \n options.cursor.execute(query)\n rc = options.cursor.fetchall()\n lumi_section = {}\n lhc_fill = 99999999\n for x in rc:\n fill, ls, lumi, pu, flag = x\n data = {'lumi': lumi, 'pu': pu, 'flag': flag}\n lumi_section.update({ls : data})\n lhc_fill = min(lhc_fill, fill)\n\n return lhc_fill, lumi_section\n\n\n\ndef getFillInfo(options, fill):\n fill_summary = {}\n query = \"\"\"select nbunchesbeam1, nbunchesbeam2, ncollidingbunches, ntargetbunches from cms_runtime_logger.runtime_summary where lhcfill = {0}\"\"\".format(fill)\n options.cursor.execute(query)\n rc = options.cursor.fetchall()\n for x in rc:\n nb1, nb2, ncolliding, ntarget = x\n fill_summary.update({'fill': fill, 'nb1': nb1, 'nb2': nb2, 'ncolliding': ncolliding, 'ntarget': ntarget})\n\n return fill_summary\n\n\n\ndef setTcdsCounts(options, run, lumi_section):\n query = \"\"\"select section_number, trg_cnt_total, trg_cnt_tt1, sup_trg_cnt_total, sup_trg_cnt_tt1 from cms_tcds_monitoring.tcds_cpm_counts_v where run_number = {0} order by section_number\"\"\".format(run)\n \n options.cursor.execute(query)\n rc = options.cursor.fetchall()\n for x in rc:\n try:\n ls, total, ugt, sup_total, sup_ugt = x\n lumi_section[ls]['total'] = total\n lumi_section[ls]['ugt'] = ugt\n lumi_section[ls]['sup_total'] = sup_total\n lumi_section[ls]['sup_ugt'] = sup_ugt\n except:\n e = sys.exc_info()[0]\n v = sys.exc_info()[1]\n print \"warning> {0}: {1} at LS={2} of Run={3}\".format(e.__name__, v, ls, run)\n \n\n\ndef setPrescaleIndex(options, run, lumi_section):\n query = \"\"\"select lumi_section, prescale_index from cms_ugt_mon.view_lumi_sections where run_number = {0} order by lumi_section\"\"\".format(run)\n options.cursor.execute(query)\n rc = options.cursor.fetchall()\n for x in rc:\n ls, ps = x\n lumi_section[ls]['ps'] = ps\n\n\n\ndef dumpText(run, fill_info, lumi_section, algo_counts):\n fp = open('{0}.txt'.format(run), 'wb')\n for ls, data in lumi_section.iteritems():\n try:\n text = \"{fill} {nb1} {nb2} {ncolliding} {ntarget} \".format(**fill_info)\n text += \"{0} {1} \".format(run, ls)\n text += \"{flag} {ps} {lumi} {pu} {total} {ugt} {sup_total} {sup_ugt}\".format(**data)\n counts = algo_counts[ls]\n for name in sorted(counts.keys()):\n text += \" {0}\".format(counts[name])\n text += \"\\n\";\n fp.write(text)\n except:\n e = sys.exc_info()[0]\n v = sys.exc_info()[1]\n print \"warning> {0}: {1} at LS={2} of Run={3}\".format(e.__name__, v, ls, run)\n fp.close()\n\n\n\ndef getMenu(options, run):\n query = \"\"\"select algo_index, algo_name from cms_ugt_mon.view_ugt_run_algo_setting where run_number = {0} order by algo_index\"\"\".format(run)\n options.cursor.execute(query)\n rc = options.cursor.fetchall()\n l1menu = {}\n for x in rc:\n index, name = x\n l1menu[index] = name.strip('\"')\n return l1menu\n\n\n\ndef getAlgoRates(options, run, l1menu):\n algo_counts = {}\n for index in l1menu.keys():\n print \" fetching algo rate for %s...\" % l1menu[index]\n query = \"\"\"select lumi_sections_id, algo_count from cms_ugt_mon.view_algo_scalers where lumi_sections_id like '%07d_' || '%%' and algo_index = %s and scaler_type = 1 order by lumi_sections_id\"\"\" % (run, index)\n options.cursor.execute(query)\n rc = options.cursor.fetchall()\n for x in rc:\n lumi_sections_id, algo_count = x\n n, ls = map(int, lumi_sections_id.split('_'))\n if ls not in algo_counts.keys():\n algo_counts.update({ls: {}})\n algo_counts[ls].update({l1menu[index]: algo_count})\n\n return algo_counts\n\n\n\ndef makeConverter(run, algo_counts):\n fp = open('convert%s.cc' % run, 'wb')\n line = \"\"\"\n void convert%s()\n {\n TFile *tfile = new TFile(\"%s.root\", \"RECREATE\");\n ttree = new TTree(\"rate\", \"\");\n \n int fill;\n int nb1;\n int nb2;\n int ncolliding;\n int ntarget;\n int run;\n int ls;\n int flag;\n int ps;\n float lumi;\n float pu;\n int total;\n int ugt;\n int sup_total;\n int sup_ugt;\n \n ttree->Branch(\"lhcFill\", &fill);\n ttree->Branch(\"nBunchesBeam1\", &nb1);\n ttree->Branch(\"nBunchesBeam2\", &nb2);\n ttree->Branch(\"nCollidingBunches\", &ncolliding);\n ttree->Branch(\"nTargetBunches\", &ntarget);\n ttree->Branch(\"runNumber\", &run);\n ttree->Branch(\"lumiSection\", &ls);\n ttree->Branch(\"physicsFlag\", &flag);\n ttree->Branch(\"prescaleColumnIndex\", &ps);\n ttree->Branch(\"luminosity\", &lumi);\n ttree->Branch(\"pileUp\", &pu);\n ttree->Branch(\"totalL1a\", &total);\n ttree->Branch(\"l1aByUgt\", &ugt);\n ttree->Branch(\"suppressedTotal\", &sup_total);\n ttree->Branch(\"suppressedUgt\", &sup_ugt);\n \"\"\"\n fp.write(line % (run, run))\n\n declare = \"\";\n for name in sorted(algo_counts[1].keys()):\n declare += 'int {0}; ttree->Branch(\"{0}\", &{0});\\n'.format(name)\n fp.write(declare);\n \n read = \"\";\n for name in sorted(algo_counts[1].keys()):\n read += ' >> {0}'.format(name)\n\n line = \"\"\"\n std::ifstream input(\"%s.txt\");\n std::string line;\n while (std::getline(input, line))\n {\n std::istringstream iss(line);\n iss >> fill >> nb1 >> nb2 >> ncolliding >> ntarget >> run >> ls >> flag >> ps >> lumi >> pu >> total >> ugt >> sup_total >> sup_ugt\n %s;\n ttree->Fill();\n }\n \n tfile->Write();\n tfile->Close();\n }\n \"\"\" % (run, read)\n fp.write(line)\n fp.close()\n\n\n\nif __name__ == '__main__':\n runs = None\n database = 'cms_omds_lb'\n user = None\n passwd = None\n\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--runs\", dest=\"runs\", default=runs, nargs=\"+\", type=int, action=\"store\", required=True, help=\"run numbers to process [separated with space]\")\n parser.add_argument(\"--db\", dest=\"database\", default=database, type=str, action=\"store\", help=\"database connection\")\n parser.add_argument(\"--user\", dest=\"user\", default=user, type=str, action=\"store\", required=True, help=\"database account user name\")\n parser.add_argument(\"--passwd\", dest=\"passwd\", default=passwd, type=str, action=\"store\", help=\"password\")\n\n options = parser.parse_args()\n\n if not options.passwd:\n import getpass\n options.passwd = getpass.getpass()\n\n options.connection = cx_Oracle.connect('%s/%s@%s' % (options.user, options.passwd, options.database))\n options.cursor = options.connection.cursor()\n\n for run in options.runs:\n print \"inf> processing run %s\" % run\n fill, lumi_sections = getLumiSections(options, run)\n fill_info = getFillInfo(options, fill)\n setTcdsCounts(options, run, lumi_sections)\n setPrescaleIndex(options, run, lumi_sections)\n l1menu = getMenu(options, run)\n algo_counts = getAlgoRates(options, run, l1menu)\n dumpText(run, fill_info, lumi_sections, algo_counts)\n makeConverter(run, algo_counts)\n\n# eof\n"
},
{
"alpha_fraction": 0.5821237564086914,
"alphanum_fraction": 0.5900177955627441,
"avg_line_length": 42.63333511352539,
"blob_id": "c1274fca1e3d4d1cdeac0aa2077c3606e8410b7f",
"content_id": "3821fa8bf849d07ca1d2987980d272d3f0b8d34d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 7854,
"license_type": "no_license",
"max_line_length": 153,
"num_lines": 180,
"path": "/python/customL1Ntuple_cfg.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "import FWCore.ParameterSet.Config as cms\n\n# General config options\nimport FWCore.ParameterSet.VarParsing as VarParsing\nimport sys\n\noptions = VarParsing.VarParsing()\n\noptions.register('globalTag',\n 'GR_P_V41_AN1', #default value\n VarParsing.VarParsing.multiplicity.singleton,\n VarParsing.VarParsing.varType.string,\n \"Global Tag\")\n\noptions.register('reEmulation',\n False, #default value\n VarParsing.VarParsing.multiplicity.singleton,\n VarParsing.VarParsing.varType.bool,\n \"Run re-emulation\")\n\noptions.register('reEmulMuons',\n False, #default value\n VarParsing.VarParsing.multiplicity.singleton,\n VarParsing.VarParsing.varType.bool,\n \"Run re-emulation of L1 muons\")\n\noptions.register('reEmulCalos',\n False, #default value\n VarParsing.VarParsing.multiplicity.singleton,\n VarParsing.VarParsing.varType.bool,\n \"Run re-emulation of L1 calos\")\n\noptions.register('reEmulRCT',\n False, #default value\n VarParsing.VarParsing.multiplicity.singleton,\n VarParsing.VarParsing.varType.bool,\n \"Run re-emulation of L1 RCT\")\n\noptions.register('patchNtuple',\n False, #default value\n VarParsing.VarParsing.multiplicity.singleton,\n VarParsing.VarParsing.varType.bool,\n \"Patch ntuple inputs to use re-emulation ones\")\n\noptions.register('jetSeedThr10GeV',\n False, #default value\n VarParsing.VarParsing.multiplicity.singleton,\n VarParsing.VarParsing.varType.bool,\n \"Switches on 10 GeV jet Seed Thresholds for 2012 GCT\")\n\noptions.register('runOnMC',\n False, #default value\n VarParsing.VarParsing.multiplicity.singleton,\n VarParsing.VarParsing.varType.bool,\n \"Set to True when running on MC\")\n\noptions.register('runOnPostLS1',\n True, #default value\n VarParsing.VarParsing.multiplicity.singleton,\n VarParsing.VarParsing.varType.bool,\n \"Set to True when running on MC and this postLS1\")\n\noptions.register('whichPU',\n 40, #default value\n VarParsing.VarParsing.multiplicity.singleton,\n VarParsing.VarParsing.varType.int,\n \"Number of average PU interactions for UCT PU subtractions\")\n\noptions.register('keepEDMOutput',\n False, #default value\n VarParsing.VarParsing.multiplicity.singleton,\n VarParsing.VarParsing.varType.bool,\n \"When True keeps also EDM GMT/GT skimmmed collections\")\n\noptions.register('customDTTF',\n False, #default value\n VarParsing.VarParsing.multiplicity.singleton,\n VarParsing.VarParsing.varType.bool,\n \"Enables usage of new DTTF LUTs\")\n\noptions.register('dttfLutsFile',\n 'sqlite:../data/dttf_config.db', #default value\n VarParsing.VarParsing.multiplicity.singleton,\n VarParsing.VarParsing.varType.string,\n \"DTTF LUTs sqlite input file\")\n\noptions.register('customCSCTF',\n False, #default value\n VarParsing.VarParsing.multiplicity.singleton,\n VarParsing.VarParsing.varType.bool,\n \"Enables usage of new CSCTF FW and LUTs (actually does nothing right now)\")\n\noptions.register('customPACT',\n False, #default value\n VarParsing.VarParsing.multiplicity.singleton,\n VarParsing.VarParsing.varType.bool,\n \"Enables usage of new RPC PACT patterns\")\n\noptions.register('customGMT',\n False, #default value\n VarParsing.VarParsing.multiplicity.singleton,\n VarParsing.VarParsing.varType.bool,\n \"Switches to minPT for the GMT\")\n\noptions.register('useStage1Layer2',\n False, #default value\n VarParsing.VarParsing.multiplicity.singleton,\n VarParsing.VarParsing.varType.bool,\n \"Enables new Stage1Layer2 emulation for calos\")\n\noptions.register('puReweightingFile',\n 'none', #default value\n VarParsing.VarParsing.multiplicity.singleton,\n VarParsing.VarParsing.varType.string,\n \"InputFile to be used for PU reweighting (for example to scale luminosity)\")\n\noptions.parseArguments()\n\n\n#L1 ntuple\nfrom L1TriggerDPG.L1Ntuples.l1Ntuple_cfg import *\n\nif options.runOnMC and hasattr(process,'l1NtupleProducer') :\n print \"[L1Menu]: Running on MC reading also PileUpSummary info\"\n ntuple = getattr(process,'l1NtupleProducer')\n ntuple.simulationSource = cms.InputTag(\"addPileupInfo\")\n\n\nprint \"[L1Menu]: Using GlobalTag\", options.globalTag\nprocess.GlobalTag.globaltag = options.globalTag\nprocess.GlobalTag.toGet = cms.VPSet()\n\n# make ntuples from RAW (ie. remove RECO)\nif options.reEmulMuons :\n process.p.remove(process.muonDTDigis)\n\n# re-emulation customisations\n\nif options.reEmulation :\n from L1TriggerDPG.L1Menu.reEmulation_cff import *\n reEmulation(process, options.reEmulMuons, options.reEmulCalos, options.patchNtuple, options.runOnPostLS1, options.useStage1Layer2, options.reEmulRCT)\n process.p.replace(process.l1NtupleProducer, process.reEmul + process.l1NtupleProducer)\n\nif options.reEmulCalos and options.jetSeedThr10GeV :\n from L1TriggerDPG.L1Menu.customiseL1Calos_cff import *\n set10GCTtreshold(process)\n\nif options.reEmulation and (options.customDTTF or options.customCSCTF or options.customPACT or options.customGMT ) :\n from L1TriggerDPG.L1Menu.customiseL1Muons_cff import *\n customiseL1Muons(process, options.customDTTF, options.customCSCTF, options.customPACT, options.customGMT, options.dttfLutsFile)\n\nif options.reEmulation and options.useStage1Layer2 :\n from L1TriggerDPG.L1Menu.customiseL1Calos_cff import *\n if options.useStage1Layer2:\n customiseStage1(process, options.runOnMC, options.runOnPostLS1, options.whichPU)\n\nif options.puReweightingFile != \"none\" :\n from L1TriggerDPG.L1Menu.pileUpReweighting_cff import *\n pileUpReweighting(process,options.puReweightingFile, \"productionPileUpHisto\", \"targetPileUpHisto\")\n\n\n# EDM keep statement\n\nif options.keepEDMOutput :\n \n process.output = cms.OutputModule(\"PoolOutputModule\",\n fileName = cms.untracked.string('L1GmtGt.root'),\n outputCommands = cms.untracked.vstring('drop *',\n 'keep *_gtDigis_*_*',\n 'keep *_gtReEmulDigis_*_*',\n 'keep *_gmtReEmulDigis_*_*',\n 'keep *_rpcTriggerReEmulDigis_*_*',\n 'keep *_csctfReEmulDigis_*_*',\n 'keep *_dttfReEmulDigis_*_*',\n 'keep *_caloStage1LegacyFormatDigis_*_*',\n 'keep *BXVector_*__L1TEMULATION',\n 'keep *_gctDigis_*_*')\n )\n\n process.out = cms.EndPath(process.output)\n"
},
{
"alpha_fraction": 0.5747485160827637,
"alphanum_fraction": 0.5924384593963623,
"avg_line_length": 49.578948974609375,
"blob_id": "790e4edb2d6ef96cef0082661650b2893a236eed",
"content_id": "09b73ff07273a5264e2922ac470201b9f8155433",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2883,
"license_type": "no_license",
"max_line_length": 144,
"num_lines": 57,
"path": "/python/customiseL1Muons_cff.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "import FWCore.ParameterSet.Config as cms\n\ndef customiseL1Muons(process, customDTTF=True, customCSCTF=True, customPACT=True, customGMT=True, dttfFile = \"sqlite_file:crab/dttf_config.db\"):\n\n print \"[L1Menu]: Customising muon chain with 2015 improvements\"\n\n if customDTTF and hasattr(process,\"dttfReEmulDigis\") :\n \n print \"[L1Menu]:\\tCustomising DTTF LUTs\"\n \n\n process.GlobalTag.toGet.extend(\n cms.VPSet(cms.PSet(record = cms.string(\"L1MuDTEtaPatternLutRcd\"),\n tag = cms.string(\"L1MuDTEtaPatternLut_CRAFT09_hlt\"),\n connect = cms.untracked.string(dttfFile)\n ),\n cms.PSet(record = cms.string(\"L1MuDTExtLutRcd\"),\n tag = cms.string(\"L1MuDTExtLut_CRAFT09_hlt\"),\n connect = cms.untracked.string(dttfFile)\n ),\n cms.PSet(record = cms.string(\"L1MuDTPhiLutRcd\"),\n tag = cms.string(\"L1MuDTPhiLut_CRAFT09_hlt\"),\n connect = cms.untracked.string(dttfFile)\n ),\n cms.PSet(record = cms.string(\"L1MuDTPtaLutRcd\"),\n tag = cms.string(\"L1MuDTPtaLut_CRAFT09_hlt\"),\n connect = cms.untracked.string(dttfFile)\n ),\n cms.PSet(record = cms.string(\"L1MuDTQualPatternLutRcd\"),\n tag = cms.string(\"L1MuDTQualPatternLut_CRAFT09_hlt\"),\n connect = cms.untracked.string(dttfFile)\n )\n )\n )\n\n if customPACT and hasattr(process,\"rpcTriggerReEmulDigis\") :\n\n print \"[L1Menu]:\\tCustomising PACT patterns\"\n\n patternDirectory = \"L1TriggerDPG/L1Menu/data/rpc_patterns/xml/\"\n \n process.load(\"L1TriggerConfig.RPCTriggerConfig.RPCConeDefinition_cff\")\n process.load(\"L1TriggerConfig.RPCTriggerConfig.L1RPCConfig_cff\")\n process.load(\"L1Trigger.RPCTrigger.RPCConeConfig_cff\")\n process.rpcconf.filedir = cms.untracked.string(patternDirectory)\n process.es_prefer_rpcPats = cms.ESPrefer(\"RPCTriggerConfig\",\"rpcconf\")\n\n if customGMT and hasattr(process,\"gmtReEmulDigis\") :\n\n print \"[L1Menu]:\\tCustomising GMT to use min-pt\"\n\n process.load('L1TriggerConfig.GMTConfigProducers.L1MuGMTParameters_cfi')\n process.L1MuGMTParameters.MergeMethodPtBrl=cms.string(\"byMinPt\")\n process.L1MuGMTParameters.MergeMethodPtFwd=cms.string(\"byMinPt\")\n process.L1MuGMTParameters.VersionSortRankEtaQLUT = cms.uint32(275)\n process.L1MuGMTParameters.VersionLUTs = cms.uint32(1) \n process.es_prefer_gmtConfig = cms.ESPrefer(\"L1MuGMTParametersProducer\",\"L1MuGMTParameters\")\n"
},
{
"alpha_fraction": 0.5630986094474792,
"alphanum_fraction": 0.6247269511222839,
"avg_line_length": 33.184776306152344,
"blob_id": "fcb8f00f1535fd32c58b8f7f83cff750dda25c18",
"content_id": "8ee98756b981ed78f71bfd74aebadf2c1c35aee9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "C",
"length_bytes": 71412,
"license_type": "no_license",
"max_line_length": 266,
"num_lines": 2089,
"path": "/macros/L1Menu2016_minbias_cross_section.C",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "//#include \"L1Ntuple.h\"\n#include \"L1AlgoFactory.h\"\n\n#include \"TString.h\"\n//#include \"Style.C\"\n#include \"TH1F.h\"\n#include \"TH2F.h\"\n\n#include <fstream>\n#include <iostream>\n#include <sstream>\n#include <map>\n#include <set>\n\n// huge prescale value for seeds changed on-the-fly\n#define INFTY 262139\n\nTH1F *h_Cross;\nTH1F *h_MultiCross;\nTH1F *h_Jets;\nTH1F *h_MultiJets;\nTH1F *h_Sums;\nTH1F *h_Egamma;\nTH1F *h_MultiEgamma;\nTH1F *h_Muons;\nTH1F *h_MultiMuons;\nTH1F *h_Technical;\n\nTH1F *h_Block;\nTH2F *cor_Block;\n\nconst Int_t NPAGS = 7;\nTH2F *cor_PAGS;\nTH1F *h_PAGS_pure;\nTH1F *h_PAGS_shared;\n\nconst Int_t NTRIGPHYS = 6;\nTH2F *cor_TRIGPHYS;\nTH1F *h_TRIGPHYS_pure;\nTH1F *h_TRIGPHYS_shared;\n\nconst Int_t N128 = 128;\t\t\t// could be > 128 for \"test seeds\"\nInt_t kOFFSET = 0;\nBool_t TheTriggerBits[N128];\t// contains the emulated triggers for each event\nTH1F *h_All;\t\t// one bin for each trigger. Fill bin i if event fires trigger i.\nTH1F *h_Pure;\t\t// one bin for each trigger. Fill bin i if event fires trigger i and NO OTHER TRIGGER.\n\n// set the errors properly\nvoid CorrectScale(TH1F* h, Float_t scal) {\n\n Int_t nbins = h -> GetNbinsX();\n\n for (Int_t i=1; i<= nbins; i++) {\n Float_t val = h -> GetBinContent(i);\n Float_t er = sqrt(val);\n val = val * scal;\n er = er * scal;\n h -> SetBinContent(i,val);\n h -> SetBinError(i,er);\n }\n}\n\nDouble_t convertRegionEta(int iEta) {\n static const double rgnEtaValues[11] = {\n 0.174, // HB and inner HE bins are 0.348 wide\n 0.522,\n 0.870,\n 1.218,\n 1.566,\n 1.956, // Last two HE bins are 0.432 and 0.828 wide\n 2.586,\n 3.250, // HF bins are 0.5 wide\n 3.750,\n 4.250,\n 4.750\n };\n if(iEta < 11) {\n return -rgnEtaValues[-(iEta - 10)]; // 0-10 are negative eta values\n }\n else if (iEta < 22) {\n return rgnEtaValues[iEta - 11]; // 11-21 are positive eta values\n }\n return -9;\n}\n\nclass L1Menu2015 : public L1AlgoFactory {\n\n public :\n\n L1Menu2015(std::string menufile, Float_t aNumberOfBunches, Bool_t anoHF, Bool_t aisTauInJet, Int_t AveragePU) : L1AlgoFactory()\n {\n themenufilename = menufile;\n theNumberOfBunches =aNumberOfBunches;\n noHF = anoHF;\n noTauInJet = aisTauInJet;\n theAveragePU = AveragePU; \n isOneSeedNotDefined = false;\n }\n\n ~L1Menu2015() {}\n\n // the setting below are/will be specific for each L1Ntuple file used\n std::string themenufilename;\n Float_t theNumberOfBunches;\n Bool_t noHF;\n Bool_t noTauInJet;\n Int_t theAveragePU;\n\n std::stringstream output;\n TString GetPrintout() { return output.str(); };\n\n void MyInit();\n // void FilL1Bits();\n\n //L1AlgoFactory *algoFactory;\n\n std::map<std::string, int> Counts;\n std::map<std::string, int> Prescales;\n std::map<std::string, bool> Biased;\n\n std::map<std::string, int> BitMapping;\n\n std::map<std::string, float> WeightsPAGs;\n std::map<std::string, float> WeightsTRIGPHYS;\n\n void InsertInMenu(std::string L1name, Bool_t value);\n\n Int_t L1BitNumber(std::string l1name);\n\n Bool_t Cross();\n Bool_t MultiCross();\n Bool_t Jets();\n Bool_t MultiJets();\n Bool_t EGamma();\n Bool_t MultiEGamma();\n Bool_t Muons();\n Bool_t MultiMuons();\n Bool_t Sums();\n Bool_t Technical();\n\n void Loop();\n\nprivate :\n\n Bool_t PhysicsBits[N128];\n Bool_t first;\n\n Int_t insert_ibin;\n Bool_t insert_val[100];\n std::string insert_names[100];\n\n Int_t NBITS_MUONS;\n Int_t NBITS_MULTIMUONS;\n Int_t NBITS_EGAMMA;\n Int_t NBITS_MULTIEGAMMA;\n Int_t NBITS_JETS;\n Int_t NBITS_MULTIJETS;\n Int_t NBITS_SUMS;\n Int_t NBITS_CROSS;\n Int_t NBITS_MULTICROSS;\n\n std::set<std::string> setTOP;\n std::set<std::string> setHIGGS;\n std::set<std::string> setEXO;\n std::set<std::string> setSMP;\n std::set<std::string> setBPH;\n std::set<std::string> setSUSY;\n std::set<std::string> setB2G;\n\n std::set<std::string> setMuon;\n std::set<std::string> setEG;\n std::set<std::string> setHadronic;\n std::set<std::string> setMuonEG;\n std::set<std::string> setMuonHadronic;\n std::set<std::string> setEGHadronic;\n\n Bool_t isOneSeedNotDefined;\n Int_t MissingBits[N128];\n\n};\n\nvoid L1Menu2015::InsertInMenu(std::string L1name, Bool_t value) {\n\n Bool_t post_prescale = false;\n\n Int_t prescale = 1;\n\n std::map<std::string, int>::const_iterator it = Prescales.find(L1name);\n if (it == Prescales.end() ) {\n isOneSeedNotDefined = true;\n MissingBits[L1BitNumber(L1name)] = 1;\n std::cout << \" --- NO PRESCALE DEFINED FOR \" << L1name << \" --- SET P = 1 \" << std::endl;\n }\n else {\n prescale = Prescales[L1name];\n }\n\n if(prescale > 0){\n Counts[L1name] ++;\n Int_t n = Counts[L1name];\n if ( n % prescale == 0) post_prescale = value; \n }\n\n insert_names[insert_ibin] = L1name;\n insert_val[insert_ibin] = post_prescale ;\n\n insert_ibin++;\n\n return;\n}\n\nInt_t L1Menu2015::L1BitNumber(std::string l1name) {\n\n std::map<std::string, int>::const_iterator it = BitMapping.find(l1name);\n if (it == BitMapping.end() ) {\n std::cout << \" Wrong L1 name, not in BitMapping \" << l1name << std::endl;\n return -1;\n }\n\n return BitMapping[l1name];\n}\n/*\nvoid L1Menu2015::FilL1Bits() {\n for (Int_t ibit=0; ibit < N128; ibit++) {\n PhysicsBits[ibit] = 0;\n if (ibit<64) {\n PhysicsBits[ibit] = (gt_->tw1[2]>>ibit)&1;\n }\n else {\n PhysicsBits[ibit] = (gt_->tw2[2]>>(ibit-64))&1;\n }\n }\n\n return;\n} \n*/\nvoid L1Menu2015::MyInit() {\n\n \n for (Int_t ibit=0; ibit < N128; ibit++) MissingBits[ibit] = 0;\n\n // the seeds per PAG\n setHIGGS.insert(\"L1_SingleMu5\");\n setHIGGS.insert(\"L1_SingleMu7\");\n setHIGGS.insert(\"L1_SingleMu12\");\n setHIGGS.insert(\"L1_SingleMu16\");\n setHIGGS.insert(\"L1_SingleMu20\");\n setHIGGS.insert(\"L1_SingleMu25\");\n setHIGGS.insert(\"L1_SingleMu30\");\n setHIGGS.insert(\"L1_SingleMu14er\");\n setHIGGS.insert(\"L1_SingleMu16er\");\n setHIGGS.insert(\"L1_SingleMu20er\");\n setHIGGS.insert(\"L1_DoubleMu_10_3p5\");\n setHIGGS.insert(\"L1_DoubleMu_12_5\");\n setHIGGS.insert(\"L1_TripleMu0\");\n setHIGGS.insert(\"L1_TripleMu_5_5_3\");\n setHIGGS.insert(\"L1_SingleEG2_BptxAND\");\n setHIGGS.insert(\"L1_SingleEG5\");\n setHIGGS.insert(\"L1_SingleEG10\");\n setHIGGS.insert(\"L1_SingleEG15\");\n setHIGGS.insert(\"L1_SingleEG20\");\n setHIGGS.insert(\"L1_SingleEG25\");\n setHIGGS.insert(\"L1_SingleEG40\");\n setHIGGS.insert(\"L1_SingleIsoEG18er\");\n setHIGGS.insert(\"L1_SingleIsoEG22er\");\n setHIGGS.insert(\"L1_SingleIsoEG25er\");\n setHIGGS.insert(\"L1_SingleIsoEG30er\");\n setHIGGS.insert(\"L1_DoubleEG_15_10\");\n setHIGGS.insert(\"L1_DoubleEG_22_10\");\n setHIGGS.insert(\"L1_TripleEG_14_10_8\");\n setHIGGS.insert(\"L1_ETM50\");\n setHIGGS.insert(\"L1_ETM60\");\n setHIGGS.insert(\"L1_ETM70\");\n setHIGGS.insert(\"L1_ETM100\");\n setHIGGS.insert(\"L1_Mu12_EG10\");\n setHIGGS.insert(\"L1_Mu20_EG10\");\n setHIGGS.insert(\"L1_Mu4_EG18\");\n setHIGGS.insert(\"L1_Mu5_EG15\");\n setHIGGS.insert(\"L1_Mu5_EG20\");\n setHIGGS.insert(\"L1_Mu5_IsoEG18\");\n setHIGGS.insert(\"L1_Mu5_DoubleEG5\");\n setHIGGS.insert(\"L1_Mu6_DoubleEG10\");\n setHIGGS.insert(\"L1_DoubleMu6_EG6\");\n setHIGGS.insert(\"L1_DoubleMu7_EG7\");\n setHIGGS.insert(\"L1_Mu16er_TauJet20er\");\n setHIGGS.insert(\"L1_IsoEG20er_TauJet20er_NotWdEta0\");\n setHIGGS.insert(\"L1_DoubleIsoTau28er\");\n setHIGGS.insert(\"L1_DoubleIsoTau32er\");\n setHIGGS.insert(\"L1_DoubleIsoTau36er\");\n setHIGGS.insert(\"L1_DoubleIsoTau40er\");\n setHIGGS.insert(\"L1_QuadJetC36_TauJet52\");\n setHIGGS.insert(\"L1_DoubleJetC56_ETM60\");\n setHIGGS.insert(\"L1_TripleJet_92_76_64_VBF\");\n setHIGGS.insert(\"L1_TripleJet_84_68_48_VBF\");\n setHIGGS.insert(\"L1_EG25er_HTT100\");\n\n setEXO.insert(\"L1_SingleMuOpen\");\n setEXO.insert(\"L1_SingleMuOpen_NotBptxOR\");\n setEXO.insert(\"L1_SingleMu5\");\n setEXO.insert(\"L1_SingleMu7\");\n setEXO.insert(\"L1_SingleMu16\");\n setEXO.insert(\"L1_SingleMu20\");\n setEXO.insert(\"L1_SingleMu25\");\n setEXO.insert(\"L1_SingleMu30\");\n setEXO.insert(\"L1_SingleMu14er\");\n setEXO.insert(\"L1_SingleMu16er\");\n setEXO.insert(\"L1_SingleMu20er\");\n setEXO.insert(\"L1_DoubleMu_10_3p5\");\n setEXO.insert(\"L1_DoubleMu_12_5\");\n setEXO.insert(\"L1_SingleEG25\");\n setEXO.insert(\"L1_SingleEG30\");\n setEXO.insert(\"L1_SingleEG35\");\n setEXO.insert(\"L1_SingleIsoEG22er\");\n setEXO.insert(\"L1_SingleIsoEG30er\");\n setEXO.insert(\"L1_DoubleEG_15_10\");\n setEXO.insert(\"L1_DoubleEG_22_10\");\n setEXO.insert(\"L1_SingleJet52\");\n setEXO.insert(\"L1_SingleJet128\");\n setEXO.insert(\"L1_SingleJet176\");\n setEXO.insert(\"L1_SingleJet200\");\n setEXO.insert(\"L1_DoubleIsoTau28er\");\n setEXO.insert(\"L1_DoubleIsoTau32er\");\n setEXO.insert(\"L1_DoubleIsoTau36er\");\n setEXO.insert(\"L1_DoubleIsoTau40er\");\n setEXO.insert(\"L1_DoubleJetC84\");\n setEXO.insert(\"L1_DoubleJetC100\");\n setEXO.insert(\"L1_DoubleJetC112\");\n setEXO.insert(\"L1_QuadJetC40\");\n setEXO.insert(\"L1_QuadJetC60\");\n setEXO.insert(\"L1_ETM30\");\n setEXO.insert(\"L1_ETM50\");\n setEXO.insert(\"L1_ETM60\");\n setEXO.insert(\"L1_ETM70\");\n setEXO.insert(\"L1_ETM100\");\n setEXO.insert(\"L1_HTT75\");\n setEXO.insert(\"L1_HTT100\");\n setEXO.insert(\"L1_HTT125\");\n setEXO.insert(\"L1_HTT150\");\n setEXO.insert(\"L1_HTT175\");\n setEXO.insert(\"L1_HTT200\");\n setEXO.insert(\"L1_HTT250\");\n setEXO.insert(\"L1_Mu20_EG10\");\n setEXO.insert(\"L1_Mu4_EG18\");\n setEXO.insert(\"L1_Mu5_EG20\");\n setEXO.insert(\"L1_Mu5_IsoEG18\");\n setEXO.insert(\"L1_Mu6_HTT100\");\n setEXO.insert(\"L1_Mu10er_ETM30\");\n setEXO.insert(\"L1_Mu10er_ETM50\");\n setEXO.insert(\"L1_Mu14er_ETM30\");\n setEXO.insert(\"L1_Mu3_JetC52_WdEtaPhi2\");\n\n setSMP.insert(\"L1_SingleMu16\");\n setSMP.insert(\"L1_SingleMu25\");\n setSMP.insert(\"L1_SingleMu30\");\n setSMP.insert(\"L1_SingleMu14er\");\n setSMP.insert(\"L1_SingleMu16er\");\n setSMP.insert(\"L1_DoubleMu_10_3p5\");\n setSMP.insert(\"L1_DoubleMu_12_5\");\n setSMP.insert(\"L1_SingleEG25\");\n setSMP.insert(\"L1_SingleEG30\");\n setSMP.insert(\"L1_SingleEG40\");\n setSMP.insert(\"L1_SingleIsoEG22er\");\n setSMP.insert(\"L1_SingleIsoEG25er\");\n setSMP.insert(\"L1_SingleIsoEG30er\");\n setSMP.insert(\"L1_DoubleEG_15_10\");\n setSMP.insert(\"L1_DoubleEG_22_10\");\n setSMP.insert(\"L1_SingleJet52\");\n setSMP.insert(\"L1_SingleJet68\");\n setSMP.insert(\"L1_SingleJet92\");\n setSMP.insert(\"L1_SingleJet128\");\n setSMP.insert(\"L1_SingleJet176\");\n setSMP.insert(\"L1_SingleJet200\");\n setSMP.insert(\"L1_Mu20_EG10\");\n setSMP.insert(\"L1_Mu4_EG18\");\n setSMP.insert(\"L1_Mu5_EG20\");\n setSMP.insert(\"L1_Mu5_IsoEG18\");\n\n setBPH.insert(\"L1_SingleMu7\");\n setBPH.insert(\"L1_SingleMu16\");\n setBPH.insert(\"L1_SingleMu25\");\n setBPH.insert(\"L1_SingleMu30\");\n setBPH.insert(\"L1_DoubleMu0\");\n setBPH.insert(\"L1_TripleMu0\");\n setBPH.insert(\"L1_DoubleMu0_Eta1p6_WdEta18_OS\");\n setBPH.insert(\"L1_DoubleMu0_Eta1p6_WdEta18\");\n setBPH.insert(\"L1_DoubleMu_10_0_WdEta18\");\n setBPH.insert(\"L1_QuadMu0\");\n\n setTOP.insert(\"L1_SingleMu16\");\n setTOP.insert(\"L1_SingleMu25\");\n setTOP.insert(\"L1_SingleMu30\");\n setTOP.insert(\"L1_DoubleMu_10_3p5\");\n setTOP.insert(\"L1_DoubleMu_12_5\");\n setTOP.insert(\"L1_SingleIsoEG20er\");\n setTOP.insert(\"L1_SingleIsoEG22er\");\n setTOP.insert(\"L1_SingleIsoEG30er\");\n setTOP.insert(\"L1_DoubleEG_15_10\");\n setTOP.insert(\"L1_DoubleEG_22_10\");\n setTOP.insert(\"L1_Mu20_EG10\");\n setTOP.insert(\"L1_Mu4_EG18\");\n setTOP.insert(\"L1_Mu5_EG20\");\n setTOP.insert(\"L1_Mu5_IsoEG18\");\n\n setB2G.insert(\"L1_SingleMu16\");\n setB2G.insert(\"L1_SingleMu25\");\n setB2G.insert(\"L1_SingleMu30\");\n setB2G.insert(\"L1_SingleMu14er\");\n setB2G.insert(\"L1_DoubleMu_10_3p5\");\n setB2G.insert(\"L1_DoubleMu_12_5\");\n setB2G.insert(\"L1_SingleEG25\");\n setB2G.insert(\"L1_SingleIsoEG22er\");\n setB2G.insert(\"L1_SingleIsoEG30er\");\n setB2G.insert(\"L1_DoubleEG_15_10\");\n setB2G.insert(\"L1_DoubleEG_22_10\");\n setB2G.insert(\"L1_SingleJet128\");\n setB2G.insert(\"L1_SingleJet176\");\n setB2G.insert(\"L1_SingleJet200\");\n setB2G.insert(\"L1_QuadJetC40\");\n setB2G.insert(\"L1_QuadJetC60\");\n setB2G.insert(\"L1_ETM50\");\n setB2G.insert(\"L1_ETM70\");\n setB2G.insert(\"L1_ETM100\");\n setB2G.insert(\"L1_HTT75\");\n setB2G.insert(\"L1_HTT100\");\n setB2G.insert(\"L1_HTT125\");\n setB2G.insert(\"L1_HTT150\");\n setB2G.insert(\"L1_HTT175\");\n setB2G.insert(\"L1_HTT200\");\n setB2G.insert(\"L1_HTT250\");\n setB2G.insert(\"L1_Mu4_EG18\");\n setB2G.insert(\"L1_Mu5_EG20\");\n setB2G.insert(\"L1_Mu5_IsoEG18\");\n setB2G.insert(\"L1_Mu20_EG10\");\n\n setSUSY.insert(\"L1_SingleMu5\");\n setSUSY.insert(\"L1_SingleMu7\");\n setSUSY.insert(\"L1_SingleMu12\");\n setSUSY.insert(\"L1_SingleMu16\");\n setSUSY.insert(\"L1_SingleMu14er\");\n setSUSY.insert(\"L1_DoubleMu_10_3p5\");\n setSUSY.insert(\"L1_DoubleMu_12_5\");\n setSUSY.insert(\"L1_SingleIsoEG22er\");\n setSUSY.insert(\"L1_SingleIsoEG30er\");\n setSUSY.insert(\"L1_DoubleEG_15_10\");\n setSUSY.insert(\"L1_DoubleEG_22_10\");\n setSUSY.insert(\"L1_SingleJet128\");\n setSUSY.insert(\"L1_SingleJet176\");\n setSUSY.insert(\"L1_SingleJet200\");\n setSUSY.insert(\"L1_DoubleIsoTau28er\");\n setSUSY.insert(\"L1_DoubleIsoTau32er\");\n setSUSY.insert(\"L1_DoubleIsoTau36er\");\n setSUSY.insert(\"L1_DoubleIsoTau40er\");\n setSUSY.insert(\"L1_DoubleJetC84\");\n setSUSY.insert(\"L1_DoubleJetC100\");\n setSUSY.insert(\"L1_DoubleJetC112\");\n setSUSY.insert(\"L1_QuadJetC40\");\n setSUSY.insert(\"L1_QuadJetC60\");\n setSUSY.insert(\"L1_ETM50\");\n setSUSY.insert(\"L1_ETM70\");\n setSUSY.insert(\"L1_ETM100\");\n setSUSY.insert(\"L1_HTT75\");\n setSUSY.insert(\"L1_HTT100\");\n setSUSY.insert(\"L1_HTT125\");\n setSUSY.insert(\"L1_HTT150\");\n setSUSY.insert(\"L1_HTT175\");\n setSUSY.insert(\"L1_HTT200\");\n setSUSY.insert(\"L1_HTT250\");\n setSUSY.insert(\"L1_Mu20_EG10\");\n setSUSY.insert(\"L1_Mu4_EG18\");\n setSUSY.insert(\"L1_Mu5_EG20\");\n setSUSY.insert(\"L1_Mu5_IsoEG18\");\n setSUSY.insert(\"L1_DoubleJetC56_ETM60\");\n setSUSY.insert(\"L1_Mu0er_ETM40\");\n setSUSY.insert(\"L1_Mu0er_ETM55\");\n setSUSY.insert(\"L1_Mu8_HTT50\");\n setSUSY.insert(\"L1_DoubleEG6_HTT150\");\n setSUSY.insert(\"L1_Jet32MuOpen_Mu10_dPhiMu_Mu1\");\n setSUSY.insert(\"L1_Jet32MuOpen_EG10_dPhiMu_EG1\");\n\n // the seeds per physics triggers (TRIGPHYS));\n setMuon.insert(\"L1_SingleMuOpen\");\n setMuon.insert(\"L1_SingleMuOpen_NotBptxOR\");\n setMuon.insert(\"L1_SingleMu5\");\n setMuon.insert(\"L1_SingleMu7\");\n setMuon.insert(\"L1_SingleMu12\");\n setMuon.insert(\"L1_SingleMu16\");\n setMuon.insert(\"L1_SingleMu20\");\n setMuon.insert(\"L1_SingleMu25\");\n setMuon.insert(\"L1_SingleMu30\");\n setMuon.insert(\"L1_SingleMu14er\");\n setMuon.insert(\"L1_SingleMu16er\");\n setMuon.insert(\"L1_DoubleMuOpen\");\n setMuon.insert(\"L1_DoubleMu0\");\n setMuon.insert(\"L1_DoubleMu0_Eta1p6_WdEta18_OS\");\n setMuon.insert(\"L1_DoubleMu0_Eta1p6_WdEta18\");\n setMuon.insert(\"L1_DoubleMu_10_0_WdEta18\");\n setMuon.insert(\"L1_DoubleMu_10_Open\");\n setMuon.insert(\"L1_DoubleMu_10_3p5\");\n setMuon.insert(\"L1_DoubleMu_12_5\");\n setMuon.insert(\"L1_TripleMu0\");\n setMuon.insert(\"L1_TripleMu_5_5_3\");\n setMuon.insert(\"L1_SingleMu6_NotBptxOR\");\n setMuon.insert(\"L1_QuadMu0\");\n setMuonHadronic.insert(\"L1_Mu3_JetC16_WdEtaPhi2\");\n setMuonHadronic.insert(\"L1_Mu3_JetC52_WdEtaPhi2\");\n setMuonHadronic.insert(\"L1_Mu6_HTT100\");\n setMuonHadronic.insert(\"L1_Mu8_HTT50\");\n setMuonHadronic.insert(\"L1_Mu0er_ETM40\");\n setMuonHadronic.insert(\"L1_Mu0er_ETM55\");\n setMuonHadronic.insert(\"L1_Mu10er_ETM30\");\n setMuonHadronic.insert(\"L1_Mu10er_ETM50\");\n setMuonHadronic.insert(\"L1_Mu14er_ETM30\");\n setMuonHadronic.insert(\"L1_Mu16er_TauJet20er\");\n setMuonHadronic.insert(\"L1_Mu16er_IsoTau28er\");\n setMuonHadronic.insert(\"L1_Mu16er_IsoTau32er\");\n setMuonEG.insert(\"L1_Mu4_EG18\");\n setMuonEG.insert(\"L1_Mu5_EG15\");\n setMuonEG.insert(\"L1_Mu5_EG20\");\n setMuonEG.insert(\"L1_Mu5_IsoEG18\");\n setMuonEG.insert(\"L1_Mu12_EG10\");\n setMuonEG.insert(\"L1_Mu20_EG10\");\n setMuonEG.insert(\"L1_Mu5_DoubleEG5\");\n setMuonEG.insert(\"L1_Mu6_DoubleEG10\");\n setMuonEG.insert(\"L1_DoubleMu6_EG6\");\n setMuonEG.insert(\"L1_DoubleMu7_EG7\");\n setEG.insert(\"L1_SingleEG2_BptxAND\");\n setEG.insert(\"L1_SingleEG5\");\n setEG.insert(\"L1_SingleEG10\");\n setEG.insert(\"L1_SingleEG15\");\n setEG.insert(\"L1_SingleEG20\");\n setEG.insert(\"L1_SingleEG25\");\n setEG.insert(\"L1_SingleEG30\");\n setEG.insert(\"L1_SingleEG35\");\n setEG.insert(\"L1_SingleEG40\");\n setEG.insert(\"L1_SingleIsoEG20\");\n setEG.insert(\"L1_SingleIsoEG25\");\n setEG.insert(\"L1_SingleIsoEG18er\");\n setEG.insert(\"L1_SingleIsoEG20er\");\n setEG.insert(\"L1_SingleIsoEG22er\");\n setEG.insert(\"L1_SingleIsoEG25er\");\n setEG.insert(\"L1_SingleIsoEG30er\");\n setEG.insert(\"L1_DoubleEG_15_10\");\n setEG.insert(\"L1_DoubleEG_22_10\");\n setEG.insert(\"L1_TripleEG_14_10_8\");\n setHadronic.insert(\"L1_SingleJet36\");\n setHadronic.insert(\"L1_SingleJet52\");\n setHadronic.insert(\"L1_SingleJet68\");\n setHadronic.insert(\"L1_SingleJet92\");\n setHadronic.insert(\"L1_SingleJet128\");\n setHadronic.insert(\"L1_SingleJet176\"); \n setHadronic.insert(\"L1_SingleJet200\"); \n setHadronic.insert(\"L1_DoubleJetC52\");\n setHadronic.insert(\"L1_DoubleJetC84\");\n setHadronic.insert(\"L1_DoubleJetC100\");\n setHadronic.insert(\"L1_DoubleJetC112\");\n setHadronic.insert(\"L1_DoubleIsoTau28er\");\n setHadronic.insert(\"L1_DoubleIsoTau32er\");\n setHadronic.insert(\"L1_DoubleIsoTau36er\");\n setHadronic.insert(\"L1_DoubleIsoTau40er\");\n setHadronic.insert(\"L1_DoubleTauJet40er\");\n setHadronic.insert(\"L1_TripleJet_92_76_64_VBF\");\n setHadronic.insert(\"L1_TripleJet_84_68_48_VBF\");\n setHadronic.insert(\"L1_QuadJetC40\");\n setHadronic.insert(\"L1_QuadJetC60\");\n setHadronic.insert(\"L1_HTT75\");\n setHadronic.insert(\"L1_HTT100\");\n setHadronic.insert(\"L1_HTT125\");\n setHadronic.insert(\"L1_HTT150\");\n setHadronic.insert(\"L1_HTT175\");\n setHadronic.insert(\"L1_HTT200\");\n setHadronic.insert(\"L1_HTT250\");\n setHadronic.insert(\"L1_ETT15_BptxAND\");\n setHadronic.insert(\"L1_ETT40\");\n setHadronic.insert(\"L1_ETT60\");\n setHadronic.insert(\"L1_ETM30\");\n setHadronic.insert(\"L1_ETM40\");\n setHadronic.insert(\"L1_ETM50\");\n setHadronic.insert(\"L1_ETM60\");\n setHadronic.insert(\"L1_ETM70\");\n setHadronic.insert(\"L1_ETM100\");\n setHadronic.insert(\"L1_QuadJetC36_TauJet52\");\n setHadronic.insert(\"L1_DoubleJetC56_ETM60\");\n setEGHadronic.insert(\"L1_IsoEG20er_TauJet20er_NotWdEta0\");\n setEGHadronic.insert(\"L1_DoubleEG6_HTT150\");\n setEGHadronic.insert(\"L1_EG25er_HTT100\");\n setEGHadronic.insert(\"L1_Jet32MuOpen_Mu10_dPhiMu_Mu1\");\n setEGHadronic.insert(\"L1_Jet32MuOpen_EG10_dPhiMu_EG1\");\n\n BitMapping[\"L1_ZeroBias\"] = 0;\n BitMapping[\"L1_AlwaysTrue\"] = 1;\n BitMapping[\"L1_SingleEG2_BptxAND\"] = 2;\n BitMapping[\"L1_SingleMu7\"] = 3;\n BitMapping[\"L1_SingleEG15\"] = 4;\n BitMapping[\"L1_ETT15_BptxAND\"] = 5;\n BitMapping[\"L1_ETT40\"] = 6;\n BitMapping[\"L1_ETT60\"] = 7;\n BitMapping[\"L1_HTT75\"] = 8;\n BitMapping[\"L1_Mu12_EG10\"] = 9;\n BitMapping[\"L1_Mu5_EG15\"] = 10;\n BitMapping[\"L1_DoubleTauJet40er\"] = 11;\n BitMapping[\"L1_IsoEG20er_TauJet20er_NotWdEta0\"] = 12;\n BitMapping[\"L1_Mu16er_TauJet20er\"] = 13;\n BitMapping[\"FREE14\"] = 14;\n BitMapping[\"L1_HTT100\"] = 15;\n BitMapping[\"FREE16\"] = 16;\n BitMapping[\"L1_SingleJet52\"] = 17;\n BitMapping[\"L1_SingleJet68\"] = 18;\n BitMapping[\"L1_SingleJet92\"] = 19;\n BitMapping[\"L1_SingleJet128\"] = 20;\n BitMapping[\"L1_SingleJet176\"] = 21;\n BitMapping[\"L1_SingleJet200\"] = 22;\n BitMapping[\"L1_SingleJet36\"] = 23;\n BitMapping[\"L1_DoubleIsoTau32er\"] = 24;\n //BitMapping[\"L1_Mu16er_IsoTau28er\"] = 25;\n BitMapping[\"L1_DoubleMu0\"] = 26;\n BitMapping[\"FREE27\"] = 27;\n BitMapping[\"FREE28\"] = 28;\n BitMapping[\"L1_Mu3_JetC16_WdEtaPhi2\"] = 29;\n BitMapping[\"L1_Mu3_JetC52_WdEtaPhi2\"] = 30;\n BitMapping[\"L1_EG25er_HTT100\"] = 31;\n BitMapping[\"L1_DoubleMuOpen\"] = 32;\n BitMapping[\"L1_SingleIsoEG25er\"] = 33;\n BitMapping[\"L1_SingleIsoEG25\"] = 34;\n BitMapping[\"L1_SingleIsoEG20\"] = 16;\n BitMapping[\"L1_SingleIsoEG30er\"] = 36;\n BitMapping[\"L1_SingleEG10\"] = 37;\n BitMapping[\"L1_SingleIsoEG22er\"] = 38;\n BitMapping[\"FREE39\"] = 39;\n BitMapping[\"L1_DoubleJetC52\"] = 40;\n BitMapping[\"L1_DoubleJetC84\"] = 41;\n BitMapping[\"L1_SingleMu14er\"] = 42 ;\n BitMapping[\"L1_DoubleJetC112\"] = 43;\n BitMapping[\"L1_DoubleMu_10_Open\"] = 44 ;\n BitMapping[\"L1_DoubleMu_10_3p5\"] = 45 ;\n BitMapping[\"L1_QuadJetC40\"] = 46;\n BitMapping[\"L1_SingleEG5\"] = 47;\n BitMapping[\"L1_SingleEG25\"] = 48;\n BitMapping[\"L1_SingleEG40\"] = 49;\n BitMapping[\"L1_SingleIsoEG18er\"] = 50;\n BitMapping[\"L1_SingleIsoEG20er\"] = 51;\n BitMapping[\"L1_SingleEG20\"] = 52;\n BitMapping[\"L1_SingleEG30\"] = 53;\n BitMapping[\"L1_SingleEG35\"] = 54;\n BitMapping[\"L1_SingleMuOpen\"] = 55;\n BitMapping[\"L1_SingleMu16\"] = 56;\n BitMapping[\"FREE57\"] = 57;\n BitMapping[\"L1_SingleMu5\"] = 58;\n BitMapping[\"FREE59\"] = 59;\n BitMapping[\"L1_SingleMu20er\"] = 60;\n //BitMapping[\"FREE60\"] = 60;\n BitMapping[\"L1_SingleMu12\"] = 61;\n BitMapping[\"L1_SingleMu20\"] = 62;\n //BitMapping[\"FREE63\"] = 63;\n BitMapping[\"L1_Mu8_HTT50\"] = 63;\n BitMapping[\"L1_SingleMu25\"] = 64;\n BitMapping[\"L1_SingleMu30\"] = 65;\n BitMapping[\"L1_ETM30\"] = 66;\n BitMapping[\"L1_ETM50\"] = 67;\n BitMapping[\"L1_ETM70\"] = 68;\n BitMapping[\"L1_ETM100\"] = 69;\n BitMapping[\"L1_HTT125\"] = 70;\n BitMapping[\"L1_HTT150\"] = 71;\n BitMapping[\"L1_HTT175\"] = 72;\n BitMapping[\"L1_HTT200\"] = 73;\n BitMapping[\"L1_Mu20_EG10\"] = 74;\n BitMapping[\"L1_Mu5_EG20\"] = 75;\n BitMapping[\"L1_Mu5_IsoEG18\"] = 76;\n BitMapping[\"L1_Mu6_DoubleEG10\"] = 77;\n BitMapping[\"L1_SingleJetC32_NotBptxOR\"] = 78;\n BitMapping[\"L1_ETM40\"] = 79;\n BitMapping[\"L1_HTT250\"] = 80;\n BitMapping[\"FREE81\"] = 81;\n //BitMapping[\"L1_Mu6_HTT100\"] = 82;\n BitMapping[\"L1_Mu10er_ETM30\"] = 82;\n BitMapping[\"L1_Mu10er_ETM50\"] = 83;\n //BitMapping[\"L1_Mu10er_ETM30\"] = 84;\n BitMapping[\"L1_Mu14er_ETM30\"] = 84;\n BitMapping[\"L1_DoubleMu7_EG7\"] = 85;\n BitMapping[\"L1_SingleMu16er\"] = 86;\n BitMapping[\"L1_Mu6_HTT100\"] = 87;\n //BitMapping[\"L1_Mu8_HTT50\"] = 87;\n BitMapping[\"L1_Mu4_EG18\"] = 88;\n BitMapping[\"L1_SingleMuOpen_NotBptxOR\"] = 89;\n //BitMapping[\"L1_SingleMu6_NotBptxOR\"] = 89;\n BitMapping[\"L1_DoubleMu6_EG6\"] = 90;\n BitMapping[\"L1_Mu5_DoubleEG5\"] = 91;\n BitMapping[\"L1_DoubleEG6_HTT150\"] = 92;\n BitMapping[\"L1_QuadJetC36_TauJet52\"] = 93;\n BitMapping[\"L1_Mu0er_ETM40\"] = 94;\n BitMapping[\"FREE95\"] = 95;\n BitMapping[\"L1_Mu16er_IsoTau28er\"] = 96; \n BitMapping[\"L1_Mu16er_IsoTau32er\"] = 25; // 96\n BitMapping[\"L1_TripleMu0\"] = 97;\n BitMapping[\"L1_TripleMu_5_5_3\"] = 98;\n BitMapping[\"FREE99\"] = 99;\n BitMapping[\"L1_TripleEG_14_10_8\"] = 100;\n BitMapping[\"L1_DoubleEG_15_10\"] = 101;\n BitMapping[\"L1_DoubleEG_22_10\"] = 102;\n BitMapping[\"FREE103\"] = 103;\n BitMapping[\"L1_Mu0er_ETM55\"] = 104;\n BitMapping[\"FREE105\"] = 105;\n BitMapping[\"FREE106\"] = 106;\n BitMapping[\"L1_Jet32MuOpen_Mu10_dPhiMu_Mu1\"] = 107;\n BitMapping[\"L1_Jet32MuOpen_EG10_dPhiMu_EG1\"] = 108;\n BitMapping[\"L1_ETM60\"] = 109;\n BitMapping[\"L1_DoubleJetC100\"] = 110;\n BitMapping[\"L1_QuadJetC60\"] = 111;\n BitMapping[\"L1_SingleJetC20_NotBptxOR\"] = 112;\n BitMapping[\"L1_DoubleJetC56_ETM60\"] = 113;\n BitMapping[\"L1_DoubleMu0_Eta1p6_WdEta18\"] = 114;\n BitMapping[\"FREE115\"] = 115;\n //BitMapping[\"FREE116\"] = 116;\n BitMapping[\"L1_DoubleIsoTau28er\"] = 116;\n BitMapping[\"L1_DoubleIsoTau36er\"] = 117;\n BitMapping[\"L1_DoubleIsoTau40er\"] = 118;\n BitMapping[\"L1_TripleJet_84_68_48_VBF\"] = 120; // 119\n //BitMapping[\"L1_DoubleIsoTau28er\"] = 120;\n BitMapping[\"L1_QuadMu0\"] = 121;\n BitMapping[\"FREE122\"] = 122;\n BitMapping[\"L1_DoubleMu0_Eta1p6_WdEta18_OS\"] = 123;\n BitMapping[\"L1_DoubleMu_12_5\"] = 124;\n BitMapping[\"L1_TripleJet_92_76_64_VBF\"] = 119; //125\n BitMapping[\"L1_DoubleMu_10_0_WdEta18\"] = 126;\n BitMapping[\"L1_SingleMuBeamHalo\"] = 127;\n\n //Read the prescales table\n std::ifstream menufile;\n menufile.open(themenufilename);\n char path_name[50];\n Int_t prescale_value = -1;\n\n while(menufile >> path_name >> prescale_value){\n if(prescale_value < 0) Prescales[path_name] = INFTY;\n else Prescales[path_name] = prescale_value;\n }\n\n for (std::map<std::string, int>::iterator it=Prescales.begin(); it != Prescales.end(); it++) {\n std::string name = it -> first;\n\n // each seed gets a \"weight\" according to how many PAGS are using it\n Int_t UsedPernPAG = 0;\n if(setTOP.count(name) > 0) UsedPernPAG ++;\n if(setHIGGS.count(name) > 0) UsedPernPAG ++;\n if(setSUSY.count(name) > 0) UsedPernPAG ++;\n if(setEXO.count(name) > 0) UsedPernPAG ++;\n if(setSMP.count(name) > 0) UsedPernPAG ++;\n if(setBPH.count(name) > 0) UsedPernPAG ++;\n if(setB2G.count(name) > 0) UsedPernPAG ++;\n WeightsPAGs[name] = 1./(float)UsedPernPAG;\n\n // each seed gets a \"weight\" according to how many trigger groups are using it\n Int_t UsedPernTrigPhyGroup = 0;\n if(setMuon.count(name) > 0) UsedPernTrigPhyGroup ++;\n if(setEG.count(name) > 0) UsedPernTrigPhyGroup ++;\n if(setHadronic.count(name) > 0) UsedPernTrigPhyGroup ++;\n if(setMuonEG.count(name) > 0) UsedPernTrigPhyGroup ++;\n if(setMuonHadronic.count(name) > 0) UsedPernTrigPhyGroup ++;\n if(setEGHadronic.count(name) > 0) UsedPernTrigPhyGroup ++;\n WeightsTRIGPHYS[name] = 1./(float)UsedPernTrigPhyGroup;\n }\n\n // The \"Biased\" table is only used for the final print-out set true for seeds for which the rate estimation is biased by the sample (because of the seeds enabled in the high PU run)\n for (std::map<std::string, int>::iterator it=Prescales.begin(); it != Prescales.end(); it++) {\n std::string name = it -> first;\n Counts[name] = 0;\n Biased[name] = false; \n }\n\n\n}\n\nBool_t L1Menu2015::Muons() {\n\n insert_ibin = 0;\n\n Float_t SingleMuPtCut = -10.;\n SingleMuPt(SingleMuPtCut,false,0);\n\n InsertInMenu(\"L1_SingleMuOpen\",SingleMu(0.,false,0));\n InsertInMenu(\"L1_SingleMuOpen_NotBptxOR\",SingleMu(0.,false,0));\n InsertInMenu(\"L1_SingleMu5\",SingleMuPtCut >= 5.);\n InsertInMenu(\"L1_SingleMu7\",SingleMuPtCut >= 7.);\n InsertInMenu(\"L1_SingleMu12\",SingleMuPtCut >= 12.);\n InsertInMenu(\"L1_SingleMu16\",SingleMuPtCut >= 16.);\n InsertInMenu(\"L1_SingleMu20\",SingleMuPtCut >= 20.);\n InsertInMenu(\"L1_SingleMu25\",SingleMuPtCut >= 25.);\n InsertInMenu(\"L1_SingleMu30\",SingleMuPtCut >= 30.);\n\n Float_t SingleMuEta2p1Pt = -10.;\n SingleMuPt(SingleMuEta2p1Pt, true,0);\n\n InsertInMenu(\"L1_SingleMu14er\",SingleMuEta2p1Pt >= 14.);\n InsertInMenu(\"L1_SingleMu16er\",SingleMuEta2p1Pt >= 16.);\n InsertInMenu(\"L1_SingleMu20er\",SingleMuEta2p1Pt >= 20.);\n\n Int_t NN = insert_ibin;\n\n Int_t kOFFSET_old = kOFFSET;\n for (Int_t k=0; k < NN; k++) {\n TheTriggerBits[k + kOFFSET_old] = insert_val[k];\n }\n kOFFSET += insert_ibin;\n\n if(first){\n\n NBITS_MUONS = NN;\n\n for (Int_t ibin=0; ibin < insert_ibin; ibin++) {\n TString l1name = (TString)insert_names[ibin];\n h_Muons -> GetXaxis() -> SetBinLabel(ibin+1, l1name );\n }\n h_Muons -> GetXaxis() -> SetBinLabel(NN+1, \"MUONS\") ;\n\n for (Int_t k=1; k <= kOFFSET - kOFFSET_old ; k++) {\n h_All -> GetXaxis() -> SetBinLabel(k +kOFFSET_old , h_Muons -> GetXaxis() -> GetBinLabel(k) );\n }\n }\n\n Bool_t res = false;\n for (Int_t i=0; i < NN; i++) {\n res = res || insert_val[i] ;\n if (insert_val[i]) h_Muons -> Fill(i);\n }\n if (res) h_Muons -> Fill(NN);\n\n return res;\n}\n\nBool_t L1Menu2015::MultiMuons() {\n\n insert_ibin = 0;\n InsertInMenu(\"L1_DoubleMu0_Eta1p6_WdEta18_OS\",Onia2015(0.,0.,true,true,18));\n InsertInMenu(\"L1_DoubleMu0_Eta1p6_WdEta18\",Onia2015(0.,0.,true,false,18));\n InsertInMenu(\"L1_DoubleMu_10_0_WdEta18\",Onia2015(10.,0.,false,false,18));\n\n InsertInMenu(\"L1_DoubleMu0\",DoubleMu(0.,0.,true, false));\n InsertInMenu(\"L1_DoubleMuOpen\",DoubleMuXOpen(0.));\n InsertInMenu(\"L1_DoubleMu_10_Open\",DoubleMuXOpen(10.));\n //InsertInMenu(\"L1_DoubleMu_10_0\",DoubleMu(10.,0.,true, false));\n InsertInMenu(\"L1_DoubleMu_10_3p5\",DoubleMu(10.,3.5,true, false));\n InsertInMenu(\"L1_DoubleMu_12_5\",DoubleMu(12.,5.,true,false));\n\n InsertInMenu(\"L1_TripleMu0\",TripleMu(0.,0.,0.,4));\n InsertInMenu(\"L1_TripleMu_5_5_3\",TripleMu(5.,5.,3.,4));\n\n InsertInMenu(\"L1_QuadMu0\",QuadMu(0.,0.,0.,0.,4));\n\n Int_t NN = insert_ibin;\n\n Int_t kOFFSET_old = kOFFSET;\n for (Int_t k=0; k < NN; k++) {\n TheTriggerBits[k + kOFFSET_old] = insert_val[k];\n }\n kOFFSET += insert_ibin;\n\n if(first){\n\n NBITS_MULTIMUONS = NN;\n\n for (Int_t ibin=0; ibin < insert_ibin; ibin++) {\n TString l1name = (TString)insert_names[ibin];\n h_MultiMuons -> GetXaxis() -> SetBinLabel(ibin+1, l1name );\n }\n h_MultiMuons -> GetXaxis() -> SetBinLabel(NN+1, \"MULTIMUONS\") ;\n\n for (Int_t k=1; k <= kOFFSET - kOFFSET_old ; k++) {\n h_All -> GetXaxis() -> SetBinLabel(k +kOFFSET_old , h_MultiMuons -> GetXaxis() -> GetBinLabel(k) );\n }\n }\n\n Bool_t res = false;\n for (Int_t i=0; i < NN; i++) {\n res = res || insert_val[i] ;\n if (insert_val[i]) h_MultiMuons -> Fill(i);\n }\n if (res) h_MultiMuons -> Fill(NN);\n\n return res;\n}\n\nBool_t L1Menu2015::Cross() {\n\n insert_ibin = 0;\n\n InsertInMenu(\"L1_Mu6_HTT100\", Mu_HTT(6.,100.));\n InsertInMenu(\"L1_Mu8_HTT50\", Mu_HTT(8.,50.));\n InsertInMenu(\"L1_Mu0er_ETM40\", Muer_ETM(0.,40.));\n InsertInMenu(\"L1_Mu0er_ETM55\", Muer_ETM(0.,55.));\n InsertInMenu(\"L1_Mu10er_ETM30\", Muer_ETM(10.,30.));\n InsertInMenu(\"L1_Mu10er_ETM50\", Muer_ETM(10.,50.));\n InsertInMenu(\"L1_Mu14er_ETM30\", Muer_ETM(14.,30.));\n InsertInMenu(\"L1_EG25er_HTT100\", SingleEG_Eta2p1_HTT(25., 100.,false));\n InsertInMenu(\"L1_Mu16er_TauJet20er\", Muer_TauJetEta2p17(16.,20.));\n InsertInMenu(\"L1_Mu16er_IsoTau28er\", Muer_TauJetEta2p17(16.,28.,true));\n InsertInMenu(\"L1_Mu16er_IsoTau32er\", Muer_TauJetEta2p17(16.,32.,true));\n InsertInMenu(\"L1_IsoEG20er_TauJet20er_NotWdEta0\", IsoEGer_TauJetEta2p17(20.,20.));\n InsertInMenu(\"L1_Mu12_EG10\", Mu_EG(12.,10.));\n InsertInMenu(\"L1_Mu20_EG10\", Mu_EG(20.,10.));\n InsertInMenu(\"L1_Mu4_EG18\", Mu_EG(4.,18.));\n InsertInMenu(\"L1_Mu5_EG15\", Mu_EG(5.,15.));\n InsertInMenu(\"L1_Mu5_EG20\", Mu_EG(5.,20.));\n InsertInMenu(\"L1_Mu5_IsoEG18\", Mu_EG(5.,18.,true));\n InsertInMenu(\"L1_DoubleMu6_EG6\", DoubleMu_EG(6.,6.,true));\n InsertInMenu(\"L1_DoubleMu7_EG7\", DoubleMu_EG(7,7.,true));\n InsertInMenu(\"L1_Mu5_DoubleEG5\", Mu_DoubleEG(5., 5.));\n InsertInMenu(\"L1_Mu6_DoubleEG10\", Mu_DoubleEG(6., 10.));\n\n Int_t NN = insert_ibin;\n Int_t kOFFSET_old = kOFFSET;\n for (Int_t k=0; k < NN; k++) {\n TheTriggerBits[k + kOFFSET_old] = insert_val[k];\n }\n kOFFSET += NN;\n\n if (first) {\n\n NBITS_CROSS = NN;\n\n for (Int_t ibin=0; ibin < insert_ibin; ibin++) {\n TString l1name = (TString)insert_names[ibin];\n h_Cross -> GetXaxis() -> SetBinLabel(ibin+1, l1name );\n }\n h_Cross-> GetXaxis() -> SetBinLabel(NN+1,\"CROSS\");\n\n for (Int_t k=1; k <= kOFFSET - kOFFSET_old; k++) {\n h_All -> GetXaxis() -> SetBinLabel(k +kOFFSET_old , h_Cross -> GetXaxis() -> GetBinLabel(k) );\n }\n\n }\n\n Bool_t res = false;\n for (Int_t i=0; i < NN; i++) {\n res = res || insert_val[i] ;\n if (insert_val[i]) h_Cross -> Fill(i);\n }\n if (res) h_Cross -> Fill(NN);\n\n return res;\n}\n\nBool_t L1Menu2015::MultiCross() {\n\n insert_ibin = 0;\n\n InsertInMenu(\"L1_Mu3_JetC16_WdEtaPhi2\", Mu_JetCentral_delta(3.,16.));\n InsertInMenu(\"L1_Mu3_JetC52_WdEtaPhi2\", Mu_JetCentral_delta(3.,52.));\n\n InsertInMenu(\"L1_DoubleJetC56_ETM60\", DoubleJetCentral_ETM(56.,56.,60.));\n\n InsertInMenu(\"L1_DoubleEG6_HTT150\", DoubleEG_HT(6., 150.));\n\n InsertInMenu(\"L1_Jet32MuOpen_Mu10_dPhiMu_Mu1\", Jet_MuOpen_Mu_dPhiMuMu1(32.,10.));\n InsertInMenu(\"L1_Jet32MuOpen_EG10_dPhiMu_EG1\", Jet_MuOpen_EG_dPhiMuEG1(32.,10.));\n\n Int_t NN = insert_ibin;\n Int_t kOFFSET_old = kOFFSET;\n for (Int_t k=0; k < NN; k++) {\n TheTriggerBits[k + kOFFSET_old] = insert_val[k];\n }\n kOFFSET += NN;\n\n if (first) {\n\n NBITS_MULTICROSS = NN;\n\n for (Int_t ibin=0; ibin < insert_ibin; ibin++) {\n TString l1name = (TString)insert_names[ibin];\n h_MultiCross -> GetXaxis() -> SetBinLabel(ibin+1, l1name );\n }\n h_MultiCross-> GetXaxis() -> SetBinLabel(NN+1,\"MULTICROSS\");\n\n for (Int_t k=1; k <= kOFFSET - kOFFSET_old; k++) {\n h_All -> GetXaxis() -> SetBinLabel(k +kOFFSET_old , h_MultiCross -> GetXaxis() -> GetBinLabel(k) );\n }\n\n }\n\n Bool_t res = false;\n for (Int_t i=0; i < NN; i++) {\n res = res || insert_val[i] ;\n if (insert_val[i]) h_MultiCross -> Fill(i);\n }\n if (res) h_MultiCross -> Fill(NN);\n\n return res;\n}\n\nBool_t L1Menu2015::Jets() {\n\n insert_ibin = 0;\n\n Float_t SingleJetPtCut = -10.;\n //Float_t SingleTauPtCut = -10.;\n Float_t SingleJetCPtCut = -10.;\n //SingleTauPt(SingleTauPtCut, false);\n SingleJetPt(SingleJetPtCut, false);\n SingleJetPt(SingleJetCPtCut, true);\n\n InsertInMenu(\"L1_SingleJet36\",SingleJetPtCut >= 36.);\n InsertInMenu(\"L1_SingleJet52\",SingleJetPtCut >= 52.);\n //InsertInMenu(\"L1_SingleTau52\",SingleTauPtCut >= 52.);\n InsertInMenu(\"L1_SingleJet68\",SingleJetPtCut >= 68.);\n InsertInMenu(\"L1_SingleJet92\",SingleJetPtCut >= 92.);\n InsertInMenu(\"L1_SingleJet128\",SingleJetPtCut >= 128.);\n InsertInMenu(\"L1_SingleJet176\",SingleJetPtCut >= 176.);\n InsertInMenu(\"L1_SingleJet200\",SingleJetPtCut >= 200.);\n\n InsertInMenu(\"L1_SingleJetC32_NotBptxOR\",SingleJetCPtCut >= 32.);\n InsertInMenu(\"L1_SingleJetC20_NotBptxOR\",SingleJetCPtCut >= 20.);\n Int_t NN = insert_ibin;\n\n Int_t kOFFSET_old = kOFFSET;\n for (Int_t k=0; k < NN; k++) {\n TheTriggerBits[k + kOFFSET_old] = insert_val[k];\n }\n kOFFSET += insert_ibin;\n\n\n if (first) {\n\n NBITS_JETS = NN;\n\n for (Int_t ibin=0; ibin < insert_ibin; ibin++) {\n TString l1name = (TString)insert_names[ibin];\n h_Jets -> GetXaxis() -> SetBinLabel(ibin+1, l1name );\n }\n\n h_Jets-> GetXaxis() -> SetBinLabel(NN+1,\"JETS\");\n\n for (Int_t k=1; k <= kOFFSET -kOFFSET_old; k++) {\n h_All -> GetXaxis() -> SetBinLabel(k +kOFFSET_old , h_Jets -> GetXaxis() -> GetBinLabel(k) );\n }\n\n }\n\n Bool_t res = false;\n for (Int_t i=0; i < NN; i++) {\n res = res || insert_val[i] ;\n if (insert_val[i]) h_Jets -> Fill(i);\n }\n if (res) h_Jets -> Fill(NN);\n\n return res;\n}\n\nBool_t L1Menu2015::MultiJets() {\n\n insert_ibin = 0;\n\n Float_t DoubleJet1 = -10.;\n Float_t DoubleJet2 = -10.;\n\n //NOT Clear how the isolation works ...\n DoubleJetPt(DoubleJet1,DoubleJet2,true);\n\n InsertInMenu(\"L1_DoubleJetC52\",DoubleJet1 >= 52. && DoubleJet2 >= 52.);\n InsertInMenu(\"L1_DoubleJetC84\",DoubleJet1 >= 84. && DoubleJet2 >= 84.);\n InsertInMenu(\"L1_DoubleJetC100\",DoubleJet1 >= 100. && DoubleJet2 >= 100.);\n InsertInMenu(\"L1_DoubleJetC112\",DoubleJet1 >= 112. && DoubleJet2 >= 112.);\n\n InsertInMenu(\"L1_DoubleIsoTau28er\", DoubleTauJetEta2p17(28.,28.,true));\n InsertInMenu(\"L1_DoubleIsoTau32er\", DoubleTauJetEta2p17(32.,32.,true));\n InsertInMenu(\"L1_DoubleIsoTau36er\", DoubleTauJetEta2p17(36.,36.,true));\n InsertInMenu(\"L1_DoubleIsoTau40er\", DoubleTauJetEta2p17(40.,40.,true));\n InsertInMenu(\"L1_DoubleTauJet40er\", DoubleTauJetEta2p17(40.,40.,false));\n //Not clear the logic for VBF and what jetclass variable is all about\n InsertInMenu(\"L1_TripleJet_92_76_64_VBF\", TripleJet_VBF(92.,76.,64.,1));\n InsertInMenu(\"L1_TripleJet_84_68_48_VBF\", TripleJet_VBF(84.,68.,48.,1));\n\n InsertInMenu(\"L1_QuadJetC40\", QuadJet(40.,40.,40.,40.,true));\n InsertInMenu(\"L1_QuadJetC60\", QuadJet(60.,60.,60.,60.,true));\n\n InsertInMenu(\"L1_QuadJetC36_TauJet52\", QuadJetCentral_TauJet(36.,52.));\n\n Int_t NN = insert_ibin;\n\n Int_t kOFFSET_old = kOFFSET;\n for (Int_t k=0; k < NN; k++) {\n TheTriggerBits[k + kOFFSET_old] = insert_val[k];\n }\n kOFFSET += insert_ibin;\n\n\n if (first) {\n\n NBITS_MULTIJETS = NN;\n\n for (Int_t ibin=0; ibin < insert_ibin; ibin++) {\n TString l1name = (TString)insert_names[ibin];\n h_MultiJets -> GetXaxis() -> SetBinLabel(ibin+1, l1name );\n }\n\n h_MultiJets-> GetXaxis() -> SetBinLabel(NN+1,\"MULTIJETS\");\n\n for (Int_t k=1; k <= kOFFSET -kOFFSET_old; k++) {\n h_All -> GetXaxis() -> SetBinLabel(k +kOFFSET_old , h_MultiJets -> GetXaxis() -> GetBinLabel(k) );\n }\n\n }\n\n Bool_t res = false;\n for (Int_t i=0; i < NN; i++) {\n res = res || insert_val[i] ;\n if (insert_val[i]) h_MultiJets -> Fill(i);\n }\n if (res) h_MultiJets -> Fill(NN);\n\n return res;\n}\n\nBool_t L1Menu2015::Sums() {\n\n insert_ibin = 0;\n\n InsertInMenu(\"L1_ETT15_BptxAND\",ETT(15.));\n InsertInMenu(\"L1_ETT40\",ETT(40.));\n InsertInMenu(\"L1_ETT60\",ETT(60.));\n\n Float_t ETM_value = -10.;\n ETMVal(ETM_value);\n\n InsertInMenu(\"L1_ETM30\", ETM_value >= 30.);\n InsertInMenu(\"L1_ETM40\", ETM_value >= 40.);\n InsertInMenu(\"L1_ETM50\", ETM_value >= 50.);\n InsertInMenu(\"L1_ETM60\", ETM_value >= 60.);\n InsertInMenu(\"L1_ETM70\", ETM_value >= 70.);\n InsertInMenu(\"L1_ETM100\",ETM_value >= 100.);\n\n Float_t HTT_value = -10.;\n HTTVal(HTT_value);\n\n InsertInMenu(\"L1_HTT75\", HTT_value >= 75.);\n InsertInMenu(\"L1_HTT100\", HTT_value >= 100.);\n InsertInMenu(\"L1_HTT125\", HTT_value >= 125.);\n InsertInMenu(\"L1_HTT150\", HTT_value >= 150.);\n InsertInMenu(\"L1_HTT175\", HTT_value >= 175.);\n InsertInMenu(\"L1_HTT200\", HTT_value >= 200.);\n InsertInMenu(\"L1_HTT250\", HTT_value >= 250.);\n\n Int_t NN = insert_ibin;\n\n Int_t kOFFSET_old = kOFFSET;\n for (Int_t k=0; k < NN; k++) {\n TheTriggerBits[k + kOFFSET_old] = insert_val[k];\n }\n kOFFSET += insert_ibin;\n\n\n if (first) {\n\n NBITS_SUMS = NN;\n\n for (Int_t ibin=0; ibin < insert_ibin; ibin++) {\n TString l1name = (TString)insert_names[ibin]; \n h_Sums -> GetXaxis() -> SetBinLabel(ibin+1, l1name );\n }\n\n h_Sums -> GetXaxis() -> SetBinLabel(NN+1,\"SUMS\");\n\n for (Int_t k=1; k <= kOFFSET -kOFFSET_old; k++) {\n h_All -> GetXaxis() -> SetBinLabel(k +kOFFSET_old , h_Sums -> GetXaxis() -> GetBinLabel(k) );\n }\n }\n\n Bool_t res = false; \n for (Int_t i=0; i < NN; i++) {\n res = res || insert_val[i] ; \n if (insert_val[i]) h_Sums -> Fill(i);\n }\n if (res) h_Sums -> Fill(NN);\n\n return res;\n}\n\nBool_t L1Menu2015::EGamma() {\n\n insert_ibin = 0;\n\n Float_t SingleEGPtCut = -10.;\n SingleEGPt(SingleEGPtCut,false, false);\n\n Float_t SingleIsoEGerPtCut = -10.;\n SingleEGPt(SingleIsoEGerPtCut,true,true);\n\n\n InsertInMenu(\"L1_SingleEG2_BptxAND\",SingleEGPtCut >= 2.);\n InsertInMenu(\"L1_SingleEG5\",SingleEGPtCut >= 5.);\n InsertInMenu(\"L1_SingleEG10\",SingleEGPtCut >= 10.);\n InsertInMenu(\"L1_SingleEG15\",SingleEGPtCut >= 15.);\n InsertInMenu(\"L1_SingleEG20\",SingleEGPtCut >= 20.);\n InsertInMenu(\"L1_SingleEG25\",SingleEGPtCut >= 25.);\n InsertInMenu(\"L1_SingleEG30\",SingleEGPtCut >= 30.);\n InsertInMenu(\"L1_SingleEG35\",SingleEGPtCut >= 35.);\n InsertInMenu(\"L1_SingleEG40\",SingleEGPtCut >= 40.);\n InsertInMenu(\"L1_SingleIsoEG20\", SingleEG(20.,true,false) );\n InsertInMenu(\"L1_SingleIsoEG25\", SingleEG(25.,true,false) );\n InsertInMenu(\"L1_SingleIsoEG18er\",SingleIsoEGerPtCut >= 18.);\n InsertInMenu(\"L1_SingleIsoEG20er\",SingleIsoEGerPtCut >= 20.);\n InsertInMenu(\"L1_SingleIsoEG22er\",SingleIsoEGerPtCut >= 22.);\n InsertInMenu(\"L1_SingleIsoEG25er\",SingleIsoEGerPtCut >= 25.);\n InsertInMenu(\"L1_SingleIsoEG30er\",SingleIsoEGerPtCut >= 30.);\n\n Int_t NN = insert_ibin;\n\n Int_t kOFFSET_old = kOFFSET;\n for (Int_t k=0; k < NN; k++) {\n TheTriggerBits[k + kOFFSET_old] = insert_val[k];\n }\n kOFFSET += insert_ibin;\n\n if (first) {\n\n NBITS_EGAMMA = NN;\n\n for (Int_t ibin=0; ibin < insert_ibin; ibin++) {\n TString l1name = (TString)insert_names[ibin];\n h_Egamma -> GetXaxis() -> SetBinLabel(ibin+1, l1name );\n }\n h_Egamma-> GetXaxis() -> SetBinLabel(NN+1,\"EGAMMA\");\n\n for (Int_t k=1; k <= kOFFSET -kOFFSET_old; k++) {\n h_All -> GetXaxis() -> SetBinLabel(k +kOFFSET_old , h_Egamma -> GetXaxis() -> GetBinLabel(k) );\n }\n } \n\n Bool_t res = false; \n for (Int_t i=0; i < NN; i++) {\n res = res || insert_val[i] ;\n if (insert_val[i]) h_Egamma -> Fill(i);\n } \n if (res) h_Egamma -> Fill(NN);\n\n return res;\n} \n\nBool_t L1Menu2015::MultiEGamma() {\n\n insert_ibin = 0;\n\n InsertInMenu(\"L1_DoubleEG_15_10\", DoubleEG(15.,10.,false) );\n InsertInMenu(\"L1_DoubleEG_22_10\", DoubleEG(22.,10.,false) );\n InsertInMenu(\"L1_TripleEG_14_10_8\", TripleEG(14.,10.,8.) );\n\n Int_t NN = insert_ibin;\n\n Int_t kOFFSET_old = kOFFSET;\n for (Int_t k=0; k < NN; k++) {\n TheTriggerBits[k + kOFFSET_old] = insert_val[k];\n }\n kOFFSET += insert_ibin;\n\n\n if (first) {\n\n NBITS_MULTIEGAMMA = NN;\n\n for (Int_t ibin=0; ibin < insert_ibin; ibin++) {\n TString l1name = (TString)insert_names[ibin];\n h_MultiEgamma -> GetXaxis() -> SetBinLabel(ibin+1, l1name );\n }\n h_MultiEgamma-> GetXaxis() -> SetBinLabel(NN+1,\"MULTIEGAMMA\");\n\n for (Int_t k=1; k <= kOFFSET -kOFFSET_old; k++) {\n h_All -> GetXaxis() -> SetBinLabel(k +kOFFSET_old , h_MultiEgamma -> GetXaxis() -> GetBinLabel(k) );\n }\n } \n\n Bool_t res = false; \n for (Int_t i=0; i < NN; i++) {\n res = res || insert_val[i] ;\n if (insert_val[i]) h_MultiEgamma -> Fill(i);\n } \n if (res) h_MultiEgamma -> Fill(NN);\n\n return res;\n} \n\nBool_t L1Menu2015::Technical() {\n\n insert_ibin = 0;\n\n InsertInMenu(\"L1_ZeroBias\", 1 );\n\n Int_t NN = insert_ibin;\n\n Int_t kOFFSET_old = kOFFSET;\n for (Int_t k=0; k < NN; k++) {\n TheTriggerBits[k + kOFFSET_old] = insert_val[k];\n }\n kOFFSET += insert_ibin;\n\n if (first) {\n for (Int_t ibin=0; ibin < insert_ibin; ibin++) {\n TString l1name = (TString)insert_names[ibin];\n h_Technical->GetXaxis()->SetBinLabel(ibin+1, l1name );\n }\n h_Technical-> GetXaxis() -> SetBinLabel(NN+1,\"Technical\");\n\n for (Int_t k=1; k <= kOFFSET -kOFFSET_old; k++) {\n h_All->GetXaxis()->SetBinLabel(k +kOFFSET_old , h_Technical->GetXaxis()->GetBinLabel(k) );\n }\n } \n\n Bool_t res = false; \n for (Int_t i=0; i < NN; i++) {\n res = res || insert_val[i] ;\n if (insert_val[i]) h_Technical -> Fill(i);\n } \n if(res)h_Technical -> Fill(NN);\n\n return res;\n} \n\n\nvoid L1Menu2015::Loop() {\n\n Int_t nevents = fChain->GetEntriesFast();//GetEntries();\n Double_t nZeroBiasevents = 0.;\n //if(nevents > 1000000) nevents = 1000000;\n\n Int_t NPASS = 0; \n\n Int_t NJETS = 0;\n Int_t MULTINJETS = 0;\n Int_t NEG = 0;\n Int_t MULTINEG = 0;\n Int_t NSUMS =0;\n Int_t NMUONS = 0;\n Int_t MULTINMUONS = 0;\n Int_t NCROSS = 0;\n Int_t MULTINCROSS = 0;\n Int_t TECHNICAL = 0;\n\n Int_t nPAG = 0;\n Int_t nTRIGPHYS = 0;\n\t\n int nLumi(0);\n unsigned int currentLumi(-1);\n\n first = true;\n\n for (Long64_t i=0; i<nevents; i++){ \n Long64_t ientry = LoadTree(i); if (ientry < 0) break;\n GetEntry(i);\n\n if (event_ != NULL && event_ -> lumi != currentLumi){\n std::cout << \"New Lumi section: \" << event_->lumi << std::endl; \n currentLumi=event_ -> lumi;\n nLumi++;\n }\n //FilL1Bits();\n if(first) MyInit();\n\n Bool_t raw = true; //= PhysicsBits[0]; // check for ZeroBias triggered events\n if(!raw) continue;\n\n nZeroBiasevents++;\n\n // reset the emulated trigger bits\n kOFFSET = 0;\n for (Int_t k=0; k < N128; k++) {\n TheTriggerBits[k] = false;\n }\n\n Bool_t jets = Jets() ;\n Bool_t multijets = MultiJets() ;\n Bool_t eg = EGamma();\n Bool_t multieg = MultiEGamma();\n Bool_t muons = Muons();\n Bool_t multimuons = MultiMuons();\n Bool_t sums = Sums();\n Bool_t technical = Technical();\n Bool_t cross = Cross();\n Bool_t multicross = MultiCross();\n\n Bool_t pass = jets || multijets || eg || multieg || sums || muons || multimuons || cross || multicross || technical;\n\n if(pass) NPASS ++;\n\n if(cross) NCROSS++;\n if(multicross) MULTINCROSS++;\n if(muons) NMUONS++;\n if(multimuons) MULTINMUONS++;\n if(sums) NSUMS++;\n if(eg) NEG++;\n if(multieg) MULTINEG++;\n if(jets) NJETS++;\n if(multijets) MULTINJETS++;\n if(technical) TECHNICAL++;\n\n if(pass) h_Block->Fill(10.);\n\n Bool_t dec[10];\n dec[0] = eg;\n dec[1] = multieg;\n dec[2] = jets;\n dec[3] = multijets;\n dec[4] = muons;\n dec[5] = multimuons;\n dec[6] = sums;\n dec[7] = cross;\n dec[8] = multicross;\n dec[9] = technical;\n\n for (Int_t l=0; l < 9; l++) {\n if(dec[l]){\n\th_Block -> Fill(l);\n\tfor (Int_t k=0; k < 5; k++) {\n\t if (dec[k]) cor_Block -> Fill(l,k);\n\t}\n }\n\n }\n\n first = false;\n\n // now the pure rate stuff\n // kOFFSET now contains the number of triggers we have calculated\n\n Bool_t ddd[NPAGS];\n for (Int_t idd=0; idd < NPAGS; idd++) {\n ddd[idd] = false; \n } \n\n Bool_t eee[NTRIGPHYS];\n for (Int_t iee=0; iee < NTRIGPHYS; iee++) {\n eee[iee] = false; \n }\n\n Float_t weightEventPAGs = 1.;\n Float_t weightEventTRIGPHYS = 1.;\n\n for (Int_t k=0; k < kOFFSET; k++) {\n if ( ! TheTriggerBits[k] ) continue;\n h_All -> Fill(k);\n\n TString name = h_All -> GetXaxis() -> GetBinLabel(k+1);\n std::string L1namest = (std::string)name;\n\n Bool_t IsTOP = setTOP.count(L1namest) > 0;\n Bool_t IsHIGGS = setHIGGS.count(L1namest) > 0;\n Bool_t IsBPH = setBPH.count(L1namest) > 0;\n Bool_t IsEXO = setEXO.count(L1namest) > 0;\n Bool_t IsSUSY = setSUSY.count(L1namest) > 0;\n Bool_t IsSMP = setSMP.count(L1namest) > 0;\n Bool_t IsB2G = setB2G.count(L1namest) > 0;\n if(IsHIGGS) ddd[0] = true;\n if(IsSUSY) ddd[1] = true;\n if(IsEXO) ddd[2] = true;\n if(IsTOP) ddd[3] = true;\n if(IsSMP) ddd[4] = true;\n if(IsBPH) ddd[5] = true;\n if(IsB2G) ddd[6] = true;\n\n Float_t ww = WeightsPAGs[L1namest];\n if (ww < weightEventPAGs) weightEventPAGs = ww;\n\n Bool_t IsMuon = setMuon.count(L1namest) > 0;\n Bool_t IsEG = setEG.count(L1namest) > 0;\n Bool_t IsHadronic = setHadronic.count(L1namest) > 0;\n\n Bool_t IsMuonEG = setMuonEG.count(L1namest) > 0;\n Bool_t IsMuonHadronic = setMuonHadronic.count(L1namest) > 0;\n Bool_t IsEGHadronic = setEGHadronic.count(L1namest) > 0;\n\n if(IsMuon) eee[0] = true;\n if(IsEG) eee[1] = true;\n if(IsHadronic) eee[2] = true;\n\n if(IsMuonEG) eee[3] = true;\n if(IsMuonHadronic) eee[4] = true;\n if(IsEGHadronic) eee[5] = true;\n\n Float_t www = WeightsTRIGPHYS[L1namest];\n if(www < weightEventTRIGPHYS) weightEventTRIGPHYS = www;\n\n //did the event pass another trigger ?\n Bool_t pure = true;\n for (Int_t k2=0; k2 < kOFFSET; k2++) {\n\tif (k2 == k) continue;\n\tif ( TheTriggerBits[k2] ) pure = false;\n }\n if (pure) h_Pure -> Fill(k);\n }\n\n // for the PAG rates\n Bool_t PAG = false;\n for (Int_t idd=0; idd < NPAGS; idd++) {\n if (ddd[idd]) {\n\tBool_t pure = true;\n\tPAG = true;\n\tfor (Int_t jdd=0; jdd < NPAGS; jdd++) {\n\t if (ddd[jdd]) {\n\t cor_PAGS -> Fill(idd,jdd);\n\t if (jdd != idd) pure = false;\n\t }\n\t} \n\tif(pure) h_PAGS_pure -> Fill(idd);\n\th_PAGS_shared -> Fill(idd,weightEventPAGs);\n\n } \n }\n if(PAG) nPAG ++;\n\n //for the TRIGPHYS rates :\n Bool_t TRIGPHYS = false;\n for (Int_t iee=0; iee < NTRIGPHYS; iee++) {\n if (eee[iee]) {\n\tBool_t pure = true;\n\tTRIGPHYS = true;\n\tfor (Int_t jee=0; jee < NTRIGPHYS; jee++) {\n\t if (eee[jee]) {\n\t cor_TRIGPHYS -> Fill(iee,jee);\n\t if (jee != iee) pure = false;\n\t }\n\t} \n\tif(pure) h_TRIGPHYS_pure -> Fill(iee);\n\th_TRIGPHYS_shared -> Fill(iee,weightEventTRIGPHYS);\n\n } \n }\n if(TRIGPHYS) nTRIGPHYS++;\n\n } // end evt loop\n\n std::cout << std::endl << std::endl << \" ... number of usable events: \" << nevents << std::endl;\n std::cout << std::endl << \"... number of zero bias triggered events: \" << nZeroBiasevents << std::endl << std::endl;\n\n Float_t scal = 11246.; // ZB per bunch in kHz\n scal /= nZeroBiasevents*1000.;\n scal *= theNumberOfBunches;\n if (theNumberOfBunches == -1)\n {\n //scal = (80.*631.)/(1326*23.3); \n scal = (80.*631.)/(nLumi*23.3); \n }\n\n Float_t extrarate = 10.;\n\n h_Cross -> Scale(scal);\n h_MultiCross -> Scale(scal);\n h_Jets -> Scale(scal);\n h_MultiJets -> Scale(scal);\n h_Egamma -> Scale(scal);\n h_MultiEgamma -> Scale(scal);\n h_Sums -> Scale(scal);\n h_Muons -> Scale(scal);\n h_MultiMuons -> Scale(scal);\n h_Technical -> Scale(scal);\n CorrectScale(h_All, scal);\n h_Pure -> Scale(scal);\n\n std::cout << std::endl << \" --------------------------------------------------------- \" << std::endl << std::endl;\n std::cout << \" Rate that pass L1 \" << NPASS * scal << \" kHz ( claimed by a PAG \" << nPAG * scal << \" kHz i.e. \" << 100.*(float)nPAG/(float)NPASS << \"%. ) \" << \") adding \" << extrarate << \" kHz = \" << NPASS * scal + extrarate << \" kHz \" << std::endl << std::endl;\n std::cout << \" --------------------------------------------------------- \" << std::endl << std::endl;\n std::cout << \" Rate that pass L1 jets: \" << NJETS * scal << \" kHz\" << std::endl;\n std::cout << \" Rate that pass L1 multi-jets: \" << MULTINJETS * scal << \" kHz\" << std::endl;\n std::cout << \" Rate that pass L1 EG: \" << NEG * scal << \" kHz\" << std::endl;\n std::cout << \" Rate that pass L1 multi-EG: \" << MULTINEG * scal << \" kHz\" << std::endl;\n std::cout << \" Rate that pass L1 Sums: \" << NSUMS * scal << \" kHz\" << std::endl;\n std::cout << \" Rate that pass L1 Muons: \" << NMUONS * scal << \" kHz\" << std::endl;\n std::cout << \" Rate that pass L1 multi-Muons: \" << MULTINMUONS * scal << \" kHz\" << std::endl;\n std::cout << \" Rate that pass L1 Cross: \" << NCROSS * scal << \" kHz\" << std::endl;\n std::cout << \" Rate that pass L1 multi-Cross: \" << MULTINCROSS * scal << \" kHz\" << std::endl;\n std::cout << \" Rate that pass L1 Technical: \" << TECHNICAL * scal << \" kHz\" << std::endl;\n\n output << std::endl << \" --------------------------------------------------------- \" << std::endl << std::endl;\n output << \" Rate that pass L1 \" << NPASS * scal << \" kHz ( claimed by a PAG \" << nPAG * scal << \" kHz i.e. \" << 100.*(float)nPAG/(float)NPASS << \"%. ) and adding \" << extrarate << \" kHz = \" << NPASS * scal + extrarate << \" kHz \" << std::endl << std::endl;\n output << \" --------------------------------------------------------- \" << std::endl << std::endl;\n output << \" Rate that pass L1 jets: \" << NJETS * scal << \" kHz\" << std::endl;\n output << \" Rate that pass L1 multi-jets: \" << MULTINJETS * scal << \" kHz\" << std::endl;\n output << \" Rate that pass L1 EG: \" << NEG * scal << \" kHz\" << std::endl;\n output << \" Rate that pass L1 multi-EG: \" << MULTINEG * scal << \" kHz\" << std::endl;\n output << \" Rate that pass L1 Sums: \" << NSUMS * scal << \" kHz\" << std::endl;\n output << \" Rate that pass L1 Muons: \" << NMUONS * scal << \" kHz\" << std::endl;\n output << \" Rate that pass L1 multi-Muons: \" << MULTINMUONS * scal << \" kHz\" << std::endl;\n output << \" Rate that pass L1 Cross: \" << NCROSS * scal << \" kHz\" << std::endl;\n output << \" Rate that pass L1 multi-Cross: \" << MULTINCROSS * scal << \" kHz\" << std::endl;\n output << \" Rate that pass L1 Technical: \" << TECHNICAL * scal << \" kHz\" << std::endl;\n\n for (Int_t i=1; i<= 5; i++) {\n Float_t nev = h_Block -> GetBinContent(i);\n for (Int_t j=1; j<= 5; j++) {\n Int_t ibin = cor_Block -> FindBin(i-1,j-1);\n Float_t val = cor_Block -> GetBinContent(ibin);\n val = val / nev;\n cor_Block -> SetBinContent(ibin,val);\n }\n } \n\n h_Block->Scale(scal);\n\n cor_PAGS->Scale(scal);\n h_PAGS_pure->Scale(scal);\n h_PAGS_shared->Scale(scal);\n\n cor_TRIGPHYS->Scale(scal);\n h_TRIGPHYS_pure->Scale(scal);\n h_TRIGPHYS_shared->Scale(scal);\n\n Int_t NBITS_ALL = NBITS_MUONS + NBITS_MULTIMUONS + NBITS_EGAMMA + NBITS_MULTIEGAMMA + NBITS_JETS + NBITS_MULTIJETS + NBITS_SUMS + NBITS_CROSS + NBITS_MULTICROSS;\n\n std::cout << std::endl << \" --- TOTAL NUMBER OF BITS: \" << std::endl;\n std::cout << \" USED : \" << NBITS_ALL << std::endl;\n std::cout << \" MUONS : \" << NBITS_MUONS << std::endl;\n std::cout << \" MULTIMUONS : \" << NBITS_MULTIMUONS << std::endl;\n std::cout << \" EGAMMA : \" << NBITS_EGAMMA << std::endl;\n std::cout << \" MULTIEGAMMA : \" << NBITS_MULTIEGAMMA << std::endl;\n std::cout << \" JETS : \" << NBITS_JETS << std::endl;\n std::cout << \" MULTIJETS : \" << NBITS_MULTIJETS << std::endl;\n std::cout << \" SUMS : \" << NBITS_SUMS << std::endl;\n std::cout << \" CROSS : \" << NBITS_CROSS << std::endl;\n std::cout << \" MULTICROSS : \" << NBITS_MULTICROSS << std::endl << std::endl;\n\n output << std::endl << \" --- TOTAL NUMBER OF BITS: \" << std::endl;\n output << \" USED : \" << NBITS_ALL << std::endl;\n output << \" MUONS : \" << NBITS_MUONS << std::endl;\n output << \" MULTIMUONS : \" << NBITS_MULTIMUONS << std::endl;\n output << \" EGAMMA : \" << NBITS_EGAMMA << std::endl;\n output << \" MULTIEGAMMA : \" << NBITS_MULTIEGAMMA << std::endl;\n output << \" JETS : \" << NBITS_JETS << std::endl;\n output << \" MULTIJETS : \" << NBITS_MULTIJETS << std::endl;\n output << \" SUMS : \" << NBITS_SUMS << std::endl;\n output << \" CROSS : \" << NBITS_CROSS << std::endl;\n output << \" MULTICROSS : \" << NBITS_MULTICROSS << std::endl << std::endl;\n\n if(isOneSeedNotDefined){\n std::cout << \"##########################\" << std::endl;\n std::cout << \"Warning, undefined seeds! Perhaps is normal, but check!\" << std::endl;\n std::cout << \"Missing seeds are in bit numbers \";\n for(int i=0;i<N128;i++){\n if(MissingBits[i] == 1) std::cout << i << \", \";\n }\n std::cout << std::endl << \"#########################\" << std::endl;\n }\n\n}\n\nvoid RunL1(Bool_t drawplots=true, Bool_t writefiles=true, Int_t whichFileAndLumiToUse=1){\n\n Int_t Nbin_max = 50;\n h_Cross = new TH1F(\"h_Cross\",\"h_Cross\",Nbin_max,-0.5,(float)Nbin_max-0.5);\n h_MultiCross = new TH1F(\"h_MultiCross\",\"h_MultiCross\",Nbin_max,-0.5,(float)Nbin_max-0.5);\n h_Sums = new TH1F(\"h_Sums\",\"h_Sums\",Nbin_max,-0.5,(float)Nbin_max-0.5);\n h_Jets = new TH1F(\"h_Jets\",\"h_Jets\",Nbin_max,-0.5,(float)Nbin_max-0.5);\n h_MultiJets = new TH1F(\"h_MultiJets\",\"h_MultiJets\",Nbin_max,-0.5,(float)Nbin_max-0.5);\n h_Egamma = new TH1F(\"h_Egamma\",\"h_Egamma\",Nbin_max,-0.5,(float)Nbin_max-0.5);\n h_MultiEgamma = new TH1F(\"h_MultiEgamma\",\"h_MultiEgamma\",Nbin_max,-0.5,(float)Nbin_max-0.5);\n h_Muons = new TH1F(\"h_Muons\",\"h_Muons\",Nbin_max,-0.5,(float)Nbin_max-0.5);\n h_MultiMuons = new TH1F(\"h_MultiMuons\",\"h_MultiMuons\",Nbin_max,-0.5,(float)Nbin_max-0.5);\n h_Technical = new TH1F(\"h_Technical\",\"h_Technical\",Nbin_max,-0.5,(float)Nbin_max-0.5);\n\n h_Block = new TH1F(\"h_Block\",\"h_Block\",11,-0.5,10.5);\n cor_Block = new TH2F(\"cor_Block\",\"cor_Block\",10,-0.5,9.5,19,-0.5,9.5);\n\n cor_PAGS = new TH2F(\"cor_PAGS\",\"cor_PAGS\",NPAGS,-0.5,(float)NPAGS-0.5,NPAGS,-0.5,(float)NPAGS-0.5);\n h_PAGS_pure = new TH1F(\"h_PAGS_pure\",\"h_PAGS_pure\",NPAGS,-0.5,(float)NPAGS-0.5);\n h_PAGS_shared = new TH1F(\"h_PAGS_shared\",\"h_PAGS_shared\",NPAGS,-0.5,(float)NPAGS-0.5);\n\n cor_TRIGPHYS = new TH2F(\"cor_TRIGPHYS\",\"cor_TRIGPHYS\",NTRIGPHYS,-0.5,(float)NTRIGPHYS-0.5,NTRIGPHYS,-0.5,(float)NTRIGPHYS-0.5);\n h_TRIGPHYS_pure = new TH1F(\"h_TRIGPHYS_pure\",\"h_TRIGPHYS_pure\",NTRIGPHYS,-0.5,(float)NTRIGPHYS-0.5);\n h_TRIGPHYS_shared = new TH1F(\"h_TRIGPHYS_shared\",\"h_TRIGPHYS_shared\",NTRIGPHYS,-0.5,(float)NTRIGPHYS-0.5);\n\n h_All = new TH1F(\"h_All\",\"h_All\",N128,-0.5,N128-0.5);\n h_Pure = new TH1F(\"h_Pure\",\"h_Pure\",N128,-0.5,N128-0.5);\n\n Float_t NumberOfBunches = 0.; \n std::string L1NtupleFileName = \"\";\n Float_t AveragePU = 0.;\n Bool_t noHF = false;\n Bool_t noTauInJet = false;\n Float_t Energy = 0.;\n Float_t targetlumi = 1.;\n\n std::string themenufilename;\n\n if(whichFileAndLumiToUse==1){\n // 13 TeV ZeroBias 72X sample 30 PU 50 ns, 2012 re-emulation with 10 GeV cut on jet seed\n NumberOfBunches = 1021; \n L1NtupleFileName = \"/data/user/gennai/L1Ntuple/l1t_debug-stage-2_256843.root\";\n //themenufilename = \"Menu_lowPU.txt\";\n themenufilename = \"Menu_20PU_25bx.txt\";\n //themenufilename = \"Menu_Noprescales.txt\";\n AveragePU = 13;\n Energy = 13;\n targetlumi= 50.;\n }\n else if(whichFileAndLumiToUse==2){\n // 13 TeV ZeroBias 62X sample 20PU 25 ns, 2015 re-emulation\n NumberOfBunches = 2508; \n L1NtupleFileName = \"root://lxcms02//data2/p/pellicci/L1DPG/root/v17/25ns_20PU_ReEmul2015/L1Tree.root\";\n themenufilename = \"Menu_20PU_25bx.txt\";\n //themenufilename = \"Menu_Noprescales.txt\";\n AveragePU = 20;\n Energy = 13;\n noTauInJet = true;\n targetlumi= 70.;\n\n //1e32\n //NumberOfBunches = 26;\n //themenufilename = \"Menu_20PU_25bx_26bunch.txt\";\n\n //2e32\n //NumberOfBunches = 74;\n //themenufilename = \"Menu_20PU_25bx_74bunch.txt\";\n\n //5e32\n //NumberOfBunches = 158;\n //themenufilename = \"Menu_20PU_25bx_158bunch.txt\";\n }\n else if(whichFileAndLumiToUse==3){\n // 13 TeV ZeroBias 62X sample 40 PU 25 ns, 2015 re-emulation\n NumberOfBunches = 2508; \n L1NtupleFileName = \"root://lxcms02//data2/p/pellicci/L1DPG/root/v16/25ns_40PU_ReEmul2015/L1Tree.root\";\n themenufilename = \"Menu_40PU_25bx.txt\";\n //themenufilename = \"Menu_Noprescales.txt\";\n AveragePU = 40;\n Energy = 13;\n noTauInJet = true;\n targetlumi= 140.;\n\n //For 7E33 40 PU\n //themenufilename = \"Menu_40PU_25bx_1200bunches.txt\";\n //NumberOfBunches = 1200;\n\n //For 5.6E33 33 PU, kind of...\n //themenufilename = \"Menu_40PU_25bx_5p6e33.txt\";\n //NumberOfBunches = 1200.*5.6/7.;\n }\n else if(whichFileAndLumiToUse==4){\n // 13 TeV ZeroBias 62X sample 20PU 25 ns, 2012 re-emulation\n NumberOfBunches = -1; \n //L1NtupleFileName = \"root:///data2/p/pellicci/L1DPG/root/v14/25ns_20PU_ReEmul2012Gct10GeV/L1Tree.root\";\n L1NtupleFileName = \"ntuples_256843_stage1B.list\";\n //L1NtupleFileName = \"ntuples_256843_stage1.list\";\n //L1NtupleFileName = \"ntuples_256843_stage2.list\";\n themenufilename = \"Menu_256843.txt\";\n //themenufilename = \"Menu_Noprescales.txt\";\n AveragePU = 20;\n Energy = 13;\n targetlumi= 70.;\n }\n else if(whichFileAndLumiToUse==5){\n // 13 TeV ZeroBias 62X sample 20PU 25 ns, 2012 re-emulation\n NumberOfBunches = -1; \n //L1NtupleFileName = \"root:///data2/p/pellicci/L1DPG/root/v14/25ns_20PU_ReEmul2012Gct10GeV/L1Tree.root\";\n L1NtupleFileName = \"ntuples_256843_stage2_full.list\";\n //L1NtupleFileName = \"ntuples_256843_stage1.list\";\n //L1NtupleFileName = \"ntuples_256843_stage2.list\";\n themenufilename = \"Menu_256843.txt\";\n //themenufilename = \"Menu_Noprescales.txt\";\n AveragePU = 20;\n Energy = 13;\n targetlumi= 70.;\n }\n else if(whichFileAndLumiToUse==6){\n // 13 TeV ZeroBias 62X sample 20PU 25 ns, 2012 re-emulation\n NumberOfBunches = 1021; \n //L1NtupleFileName = \"root:///data2/p/pellicci/L1DPG/root/v14/25ns_20PU_ReEmul2012Gct10GeV/L1Tree.root\";\n L1NtupleFileName = \"ntuples_256843_stage2_Simone.list\";\n //L1NtupleFileName = \"ntuples_256843_stage1.list\";\n //L1NtupleFileName = \"ntuples_256843_stage2.list\";\n themenufilename = \"Menu_256843_Simone.txt\";\n //themenufilename = \"Menu_Noprescales.txt\";\n AveragePU = 13;\n Energy = 13;\n targetlumi= 50.;\n }\n else if(whichFileAndLumiToUse==7){\n // 13 TeV ZeroBias 62X sample 20PU 25 ns, 2012 re-emulation\n NumberOfBunches = 1021; \n //L1NtupleFileName = \"root:///data2/p/pellicci/L1DPG/root/v14/25ns_20PU_ReEmul2012Gct10GeV/L1Tree.root\";\n L1NtupleFileName = \"ntuples_260627_Aaron.list\";\n //L1NtupleFileName = \"ntuples_256843_stage1.list\";\n //L1NtupleFileName = \"ntuples_256843_stage2.list\";\n themenufilename = \"Menu_256843_Simone.txt\";\n //themenufilename = \"Menu_Noprescales.txt\";\n AveragePU = 13;\n Energy = 13;\n targetlumi= 50.;\n }\n else{\n std::cout << \"##########################\" << std::endl;\n std::cout << \"ERROR: Please define a ntuple file which is in the allowed range! You did use: whichFileAndLumiToUse = \" << whichFileAndLumiToUse << \" This is not in the allowed range\" << std::endl;\n std::cout << \"##########################\" << std::endl;\n }\n\n std::stringstream txtos;\n txtos << \"L1Menu_\" << L1NtupleFileName <<\"_\" << Energy << \"_\" << AveragePU << \"_rates.txt\";\n TString TXTOutPutFileName = txtos.str();\n std::ofstream TXTOutfile(TXTOutPutFileName);\n\n std::stringstream csvos;\n csvos << \"L1Menu_\" << L1NtupleFileName <<\"_\" << Energy << \"_\" << AveragePU << \"_rates.csv\";\n TString CSVOutPutFileName = csvos.str();\n std::ofstream CSVOutfile(CSVOutPutFileName);\n\n std::cout << std::endl << \"L1 menu used = \" << themenufilename << std::endl;\n std::cout << std::endl << \"Using: whichFileAndLumiToUse = \" << whichFileAndLumiToUse << std::endl;\n std::cout << \" L1NtupleFileName = \" << L1NtupleFileName << std::endl;\n std::cout << \" L1MenuFileName = \" << themenufilename << std::endl;\n std::cout << \" AveragePU = \" << AveragePU << std::endl;\n\n if (writefiles) { \n std::cout << std::endl << \"Writing CSV and txt files as well ...\" << std::endl;\n std::cout << \" TXTOutPutFileName: \" << TXTOutPutFileName << std::endl;\n std::cout << \" CVSOutPutFileName: \" << CSVOutPutFileName << std::endl << std::endl;\n\n TXTOutfile << std::endl << \"L1 menu used = \" << themenufilename << std::endl;\n\n TXTOutfile << std::endl << \"Target Luminosity = \" << targetlumi << std::endl << std::endl;\n\n TXTOutfile << std::endl << \"Using: whichFileAndLumiToUse = \" << whichFileAndLumiToUse << std::endl;\n TXTOutfile << \" L1NtupleFileName = \" << L1NtupleFileName << std::endl;\n }\n\n //TFile f(L1NtupleFileName.c_str());\n //TTree *tree;\n //TDirectory * dir = (TDirectory*)f.Get(\"l1UpgradeTree\");\n //dir->GetObject(\"L1UpgradeTree\",tree);\n //L1Menu2015 a(themenufilename,NumberOfBunches,noHF,noTauInJet,AveragePU, tree);\n\n L1Menu2015 a(themenufilename,NumberOfBunches,noHF,noTauInJet,AveragePU);\n a.OpenWithList(L1NtupleFileName);\n a.Loop();\n\n \n if(drawplots){\n\n TFile fOut(\"plots_menu.root\",\"RECREATE\");\n fOut.cd();\n\n TString YaxisName;\n if(targetlumi == 1.) YaxisName = \"Rate (kHz) at 1e32\";\n if(targetlumi == 2.) YaxisName = \"Rate (kHz) at 2e32\";\n if(targetlumi == 50) YaxisName = \"Rate (kHz) at 5e33\";\n if(targetlumi == 60.) YaxisName = \"Rate (kHz) at 6e33\";\n if(targetlumi == 70.) YaxisName = \"Rate (kHz) at 7e33\";\n if(targetlumi == 140.) YaxisName = \"Rate (kHz) at 1.4e34\";\n\n TCanvas* c1 = new TCanvas(\"c1\",\"c1\");\n c1 -> cd();\n //gStyle -> SetOptStat(0);\n h_Cross -> SetLineColor(4);\n h_Cross -> GetXaxis() -> SetLabelSize(0.035);\n h_Cross -> SetYTitle(YaxisName);\n h_Cross -> Draw();\n c1->Write();\n\n TCanvas* c2 = new TCanvas(\"c2\",\"c2\");\n c2 -> cd();\n h_MultiCross -> SetLineColor(4);\n h_MultiCross -> GetXaxis() -> SetLabelSize(0.035);\n h_MultiCross -> SetYTitle(YaxisName);\n h_MultiCross -> Draw();\n c2->Write();\n\n TCanvas* c3 = new TCanvas(\"c3\",\"c3\");\n c3 -> cd();\n h_Sums -> SetLineColor(4);\n h_Sums -> GetXaxis() -> SetLabelSize(0.035);\n h_Sums -> SetYTitle(YaxisName);\n h_Sums -> Draw();\n c3->Write();\n\n TCanvas* c4 = new TCanvas(\"c4\",\"c4\");\n c4 -> cd();\n h_Egamma -> SetLineColor(4);\n h_Egamma -> GetXaxis() -> SetLabelSize(0.035);\n h_Egamma -> SetYTitle(YaxisName);\n h_Egamma -> Draw();\n c4->Write();\n\n TCanvas* c5 = new TCanvas(\"c5\",\"c5\");\n c5 -> cd();\n h_MultiEgamma -> SetLineColor(4);\n h_MultiEgamma -> GetXaxis() -> SetLabelSize(0.035);\n h_MultiEgamma -> SetYTitle(YaxisName);\n h_MultiEgamma -> Draw();\n c5->Write();\n\n TCanvas* c6 = new TCanvas(\"c6\",\"c6\");\n c6 -> cd();\n h_Jets -> SetLineColor(4);\n h_Jets -> GetXaxis() -> SetLabelSize(0.035);\n h_Jets -> SetYTitle(YaxisName);\n h_Jets -> Draw();\n c6->Write();\n\n TCanvas* c7 = new TCanvas(\"c7\",\"c7\");\n c7 -> cd();\n h_MultiJets -> SetLineColor(4);\n h_MultiJets -> GetXaxis() -> SetLabelSize(0.035);\n h_MultiJets -> SetYTitle(YaxisName);\n h_MultiJets -> Draw();\n c7->Write();\n\n TCanvas* c8 = new TCanvas(\"c8\",\"c8\");\n c8 -> cd();\n h_Muons -> SetLineColor(4);\n h_Muons -> GetXaxis() -> SetLabelSize(0.035);\n h_Muons -> SetYTitle(YaxisName);\n h_Muons -> Draw();\n c8->Write();\n\n TCanvas* c9 = new TCanvas(\"c9\",\"c9\");\n c9 -> cd();\n h_MultiMuons -> SetLineColor(4);\n h_MultiMuons -> GetXaxis() -> SetLabelSize(0.035);\n h_MultiMuons -> SetYTitle(YaxisName);\n h_MultiMuons -> Draw();\n c9->Write();\n\n TCanvas* c10 = new TCanvas(\"c10\",\"c10\");\n c10 -> cd();\n cor_Block -> GetXaxis() -> SetBinLabel(1,\"EG\");\n cor_Block -> GetXaxis() -> SetBinLabel(2,\"MultiEG\");\n cor_Block -> GetXaxis() -> SetBinLabel(3,\"Jets\");\n cor_Block -> GetXaxis() -> SetBinLabel(4,\"MultiJets\");\n cor_Block -> GetXaxis() -> SetBinLabel(5,\"Muons\");\n cor_Block -> GetXaxis() -> SetBinLabel(6,\"MultiMuons\");\n cor_Block -> GetXaxis() -> SetBinLabel(7,\"Sums\");\n cor_Block -> GetXaxis() -> SetBinLabel(8,\"Cross\");\n cor_Block -> GetXaxis() -> SetBinLabel(9,\"MultiCross\");\n cor_Block -> GetXaxis() -> SetBinLabel(10,\"Technical\");\n\n cor_Block -> GetYaxis() -> SetBinLabel(1,\"EG\");\n cor_Block -> GetYaxis() -> SetBinLabel(2,\"MultiEG\");\n cor_Block -> GetYaxis() -> SetBinLabel(3,\"Jets\");\n cor_Block -> GetYaxis() -> SetBinLabel(4,\"MultiJets\");\n cor_Block -> GetYaxis() -> SetBinLabel(5,\"Muons\");\n cor_Block -> GetYaxis() -> SetBinLabel(6,\"MultiMuons\");\n cor_Block -> GetYaxis() -> SetBinLabel(7,\"Sums\");\n cor_Block -> GetYaxis() -> SetBinLabel(8,\"Cross\");\n cor_Block -> GetYaxis() -> SetBinLabel(9,\"MultiCross\");\n cor_Block -> GetYaxis() -> SetBinLabel(10,\"Technical\");\n\n cor_Block -> Draw(\"colz\");\n cor_Block -> Draw(\"same,text\");\n c10->Write();\n\n TCanvas* c11 = new TCanvas(\"c11\",\"c11\");\n c11 -> cd();\n cor_PAGS -> GetXaxis() -> SetBinLabel(1,\"HIGGS\");\n cor_PAGS -> GetXaxis() -> SetBinLabel(2,\"SUSY\");\n cor_PAGS -> GetXaxis() -> SetBinLabel(3,\"EXO\");\n cor_PAGS -> GetXaxis() -> SetBinLabel(4,\"TOP\");\n cor_PAGS -> GetXaxis() -> SetBinLabel(5,\"SMP\");\n cor_PAGS -> GetXaxis() -> SetBinLabel(6,\"BPH\");\n cor_PAGS -> GetXaxis() -> SetBinLabel(7,\"B2G\");\n\n cor_PAGS -> GetYaxis() -> SetBinLabel(1,\"HIGGS\");\n cor_PAGS -> GetYaxis() -> SetBinLabel(2,\"SUSY\");\n cor_PAGS -> GetYaxis() -> SetBinLabel(3,\"EXO\");\n cor_PAGS -> GetYaxis() -> SetBinLabel(4,\"TOP\");\n cor_PAGS -> GetYaxis() -> SetBinLabel(5,\"SMP\");\n cor_PAGS -> GetYaxis() -> SetBinLabel(6,\"BPH\");\n cor_PAGS -> GetYaxis() -> SetBinLabel(7,\"B2G\");\n\n cor_PAGS -> Draw(\"colz\");\n cor_PAGS -> Draw(\"same,text\"); \n c11->Write();\n\n TCanvas* c12 = new TCanvas(\"c12\",\"c12\");\n c12 -> cd();\n h_PAGS_pure -> GetXaxis() -> SetBinLabel(1,\"HIGGS\");\n h_PAGS_pure -> GetXaxis() -> SetBinLabel(2,\"SUSY\");\n h_PAGS_pure -> GetXaxis() -> SetBinLabel(3,\"EXO\");\n h_PAGS_pure -> GetXaxis() -> SetBinLabel(4,\"TOP\");\n h_PAGS_pure -> GetXaxis() -> SetBinLabel(5,\"SMP\");\n h_PAGS_pure -> GetXaxis() -> SetBinLabel(6,\"BPH\");\n h_PAGS_pure -> GetXaxis() -> SetBinLabel(7,\"B2G\");\n h_PAGS_pure -> SetYTitle(\"Pure rate (kHz)\");\n h_PAGS_pure -> Draw();\n c12->Write();\n\n TCanvas* c13 = new TCanvas(\"c13\",\"c13\");\n c13 -> cd();\n h_PAGS_shared -> GetXaxis() -> SetBinLabel(1,\"HIGGS\");\n h_PAGS_shared -> GetXaxis() -> SetBinLabel(2,\"SUSY\");\n h_PAGS_shared -> GetXaxis() -> SetBinLabel(3,\"EXO\");\n h_PAGS_shared -> GetXaxis() -> SetBinLabel(4,\"TOP\");\n h_PAGS_shared -> GetXaxis() -> SetBinLabel(5,\"SMP\");\n h_PAGS_shared -> GetXaxis() -> SetBinLabel(6,\"BPH\");\n h_PAGS_shared -> GetXaxis() -> SetBinLabel(7,\"B2G\");\n h_PAGS_shared -> SetYTitle(\"Shared rate (kHz)\");\n h_PAGS_shared -> Draw();\n c13->Write();\n \n TCanvas* c14 = new TCanvas(\"c14\",\"c14\");\n c14 -> cd();\n cor_TRIGPHYS -> GetXaxis() -> SetBinLabel(1,\"Muon\");\n cor_TRIGPHYS -> GetXaxis() -> SetBinLabel(2,\"EG\");\n cor_TRIGPHYS -> GetXaxis() -> SetBinLabel(3,\"Hadronic\");\n cor_TRIGPHYS -> GetXaxis() -> SetBinLabel(4,\"Muon+EG\");\n cor_TRIGPHYS -> GetXaxis() -> SetBinLabel(5,\"Muon+Hadronic\");\n cor_TRIGPHYS -> GetXaxis() -> SetBinLabel(6,\"EG+Hadronic\");\n\n cor_TRIGPHYS -> GetYaxis() -> SetBinLabel(1,\"Muon\");\n cor_TRIGPHYS -> GetYaxis() -> SetBinLabel(2,\"EG\");\n cor_TRIGPHYS -> GetYaxis() -> SetBinLabel(3,\"Hadronic\");\n cor_TRIGPHYS -> GetYaxis() -> SetBinLabel(4,\"Muon+EG\");\n cor_TRIGPHYS -> GetYaxis() -> SetBinLabel(5,\"Muon+Hadronic\");\n cor_TRIGPHYS -> GetYaxis() -> SetBinLabel(6,\"EG+Hadronic\");\n\n cor_TRIGPHYS -> Draw(\"colz\");\n cor_TRIGPHYS -> Draw(\"same,text\"); \n c14->Write();\n\n TCanvas* c15 = new TCanvas(\"c15\",\"c15\");\n c15 -> cd();\n h_TRIGPHYS_pure -> GetXaxis() -> SetBinLabel(1,\"Muon\");\n h_TRIGPHYS_pure -> GetXaxis() -> SetBinLabel(2,\"EG\");\n h_TRIGPHYS_pure -> GetXaxis() -> SetBinLabel(3,\"Hadronic\");\n h_TRIGPHYS_pure -> GetXaxis() -> SetBinLabel(4,\"Muon+EG\");\n h_TRIGPHYS_pure -> GetXaxis() -> SetBinLabel(5,\"Muon+Hadronic\");\n h_TRIGPHYS_pure -> GetXaxis() -> SetBinLabel(6,\"EG+Hadronic\");\n \n h_TRIGPHYS_pure -> SetYTitle(\"Pure rate (kHz)\");\n h_TRIGPHYS_pure -> Draw();\n c15->Write();\n\n TCanvas* c16 = new TCanvas(\"c16\",\"c16\");\n c16 -> cd();\n h_TRIGPHYS_shared -> GetXaxis() -> SetBinLabel(1,\"Muon\");\n h_TRIGPHYS_shared -> GetXaxis() -> SetBinLabel(2,\"EG\");\n h_TRIGPHYS_shared -> GetXaxis() -> SetBinLabel(3,\"Hadronic\");\n h_TRIGPHYS_shared -> GetXaxis() -> SetBinLabel(4,\"Muon+EG\");\n h_TRIGPHYS_shared -> GetXaxis() -> SetBinLabel(5,\"Muon+Hadronic\");\n h_TRIGPHYS_shared -> GetXaxis() -> SetBinLabel(6,\"EG+Hadronic\");\n \n h_TRIGPHYS_shared -> SetYTitle(\"Shared rate (kHz)\");\n h_TRIGPHYS_shared -> Draw();\n c16->Write();\n\n fOut.Close();\n }\n \n std::cout << \"L1Bit\" << \"\\t\" << \"L1SeedName\" << \"\\t\" << \"pre-scale\" << \"\\t\" << \"rate@13TeV\" << \"\\t +/- \\t\" << \"error_rate@13TeV\" << \"\\t \" << \"pure@13TeV\" << std::endl;\n TXTOutfile << \"L1Bit\" << \"\\t\" << \"L1SeedName\" << \"\\t\" << \"pre-scale\" << \"\\t\" << \"rate@13TeV\" << \"\\t +/- \\t\" << \"error_rate@13TeV\" << \"\\t \" << \"pure@13TeV\" << std::endl;\n\n if(writefiles) CSVOutfile << \"L1Bit\" << \"\\t\" << \"TriggerName\" << \"\\t\" << \"Prescale\" << std::endl; \n\n Float_t totalrate = 0.;\n\n for(Int_t k=1; k < kOFFSET+1; k++) { // -- kOFFSET now contains the number of triggers we have calculated\n TString name = h_All->GetXaxis()->GetBinLabel(k);\n\n Float_t rate = h_All->GetBinContent(k);\n Float_t err_rate = h_All->GetBinError(k);\n Float_t pure = h_Pure->GetBinContent(k);\n\n std::string L1namest = (std::string)name;\n std::map<std::string, int>::const_iterator it = a.Prescales.find(L1namest);\n Float_t pre;\n if (it == a.Prescales.end() ) {\n std::cout << \" --- SET P = 1 FOR SEED : \" << L1namest << std::endl;\n if (writefiles) { TXTOutfile << \" --- SET P = 1 FOR SEED : \" << L1namest << std::endl; }\n pre = 1;\n }\n else {\n pre = it -> second;\n }\n Bool_t bias = a.Biased[L1namest];\n\n if (bias) std::cout << a.L1BitNumber(L1namest) << \"\\t\" << name << \"\\t\" << pre << \"\\t\" << rate << \"\\t +/- \\t\" << err_rate << \"\\t \" << pure << \"\\t\" << \" *** BIAS *** \" << std::endl;\n else\n std::cout << a.L1BitNumber(L1namest) << \"\\t \" << name << \"\\t \\t\" << pre << \"\\t \\t\" << rate << \"\\t +/- \\t\" << err_rate << \"\\t \" << pure << std::endl;\n\n if (writefiles) { \n if (bias) { TXTOutfile << a.L1BitNumber(L1namest) << \"\\t\" << name << \"\\t \\t\" << pre << \"\\t \\t\" << rate << \"\\t +/- \\t\" << err_rate << \"\\t \" << pure << \"\\t\" << \" *** BIAS *** \" << std::endl; }\n else { TXTOutfile << a.L1BitNumber(L1namest) << \"\\t\" << name << \"\\t \\t\" << pre << \"\\t \\t\" << rate << \"\\t +/- \\t\" << err_rate << \"\\t \" << pure << std::endl; }\n\n CSVOutfile << a.L1BitNumber(L1namest) << \":\\t\" << name << \":\\t\" << pre << std::endl; \n }\n\n totalrate +=rate;\n }\n\n std::cout << std::endl << \"Total rate (without overlaps) = \" << totalrate << std::endl;\n\n if (writefiles) {\n TXTOutfile << std::endl << a.GetPrintout() << std::endl;\n TXTOutfile << std::endl << \"Total rate (without overlaps) = \" << totalrate << std::endl;\n }\n\n TXTOutfile.close();\n CSVOutfile.close();\n}\n"
},
{
"alpha_fraction": 0.5479804277420044,
"alphanum_fraction": 0.5803961753845215,
"avg_line_length": 45.27381134033203,
"blob_id": "2442e348c9c60d7601cf5fb640dd5f23118d6665",
"content_id": "572cf02cdf01578473a816dae72670a8f7566cf6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3887,
"license_type": "no_license",
"max_line_length": 187,
"num_lines": 84,
"path": "/README.md",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "L1TMenu\n=======\n\n## Check out the code\nPackage to put together code and configuration file to prepare first version of the 2016 L1 menu\n\n#### The Stage2 emulator and L1Ntuples package\n\n<pre><code>\ncmsrel CMSSW_9_0_0_pre6\ncd CMSSW_9_0_0_pre6/src\ncmsenv\ngit cms-init\n</code></pre>\n\n#### L1Menu DPG package for menu-making \n<pre><code>\ngit clone [email protected]:cms-l1-dpg/L1Menu.git L1TriggerDPG/L1Menu\ncd L1TriggerDPG/L1Menu/macros\nmake -j 8\n</code></pre>\n\n\n## Menu Tuning\n\nBeside the old code inherited from 2015 L1Menu, a new executable *testMenu2016* is rewritten for easier tunning process.\n\n<pre><code>\n ./testMenu2016 -h\nAllowed options:\n -h [ --help ] produce help message\n -m [ --menufile ] arg (=menu/Slim2E34.txt)\n set the input menu\n -l [ --filelist ] arg (=ntuple/Train_v87p3_PU55.list)\n set the input ntuple list\n -u [ --Lumilist ] arg (=menu/TrainPLTZ.csv)\n set the input lumi list\n -o [ --outfilename ] arg (=Auto) set output file name\n -d [ --outputdir ] arg (=results) set output directory\n -t [ --writetext ] arg (=1) write rate to output\n -c [ --writecsv ] arg (=1) write rate to output in CSV format\n -p [ --writeplot ] arg (=1) write plot to output\n --doPlotRate save rate plot to output\n --doPlotEff save efficiency plot to output\n --doPlotTest save testing plot to output\n --doPlotuGt save uGT histograms to output\n --doPlotLS save count per LS plot to output\n --doTnPMuon use tag & probe for muon efficiency\n --doPrintPU print out rate per PU to file\n --doCompuGT Compare emulation with uGT tree\n --doScanLS Quickly scan files for selected LS\n -n [ --maxEvent ] arg (=-1) run number of events; -1 for all\n -b [ --nBunches ] arg set number of bunches\n --SumJetET arg PT threshold of Jet for HT\n --SumJetEta arg Eta threshold of Jet for HT\n --SetMuonER arg Set the ER in eta for Muon\n --SetNoPrescale Set all prescales to 1\n --UseUpgradeLyr1 Use Upgrade Layer1 Tree\n --UseL1CaloTower Use Layer1 CaloTower Tree\n --UsePFMETNoMuon Use PFMET no Muon in SingleMu sample\n --UseuGTDecision Trigger seeds fired by uGT\n --UseUnpackTree Use unpacked tree in Ntuple\n --SelectRun arg (=-1) Select specific run\n --SelectEvent arg (=-1) Select specific event\n --SelectLS arg Select specific LS ranges\n --SelectBX arg Select specific BX ranges\n --SelectCol arg Select prescale column from input csv menu\n</code></pre>\n\n#### Tips\n* `--nBunches float`: Positive number will be treated as number of colliding bunches for pre-deadtime rate estimation;\n negative number will be treated as L1 and HLT ZB prescales for post-deadtime rate estimation.\n* `--SelectLS string`: SelectLS allows JSON-like format, like \"[1, 30], [34, 40]\"\n* `--SelectBX string`: SelectBX allows JSON-like format, like \"[1, 30], [34, 40]\"\n* If you set the prescale of a L1Seed to -1 in the menu, the code will produce rates of two prescale columns, with/without this L1Seed.\n\n\n\n### Tuning for Post-ICHEP\nUse plot/PUDep.py for PU scaling \n\n```\n./testMenu2016 -d NewLumi --UseUnpackTree --nBunches 4143.995262 --SelectLS '[1, 96]' -m menu/Lumi1p5E34.txt -l ntuple/r275066_parkV62.list -o r275066_1p5E34_0 >&! r275066_1p5E34_0.log &\n```\n"
},
{
"alpha_fraction": 0.4731554090976715,
"alphanum_fraction": 0.5718472003936768,
"avg_line_length": 30.123779296875,
"blob_id": "93e582ad43cd4fbdd8a11aac608e82bba284c3ae",
"content_id": "dbd542605849b52c1d08e4b64c80e735d955cfa8",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 9555,
"license_type": "no_license",
"max_line_length": 130,
"num_lines": 307,
"path": "/macros/batch/SubmitLSF.py",
"repo_name": "sscruz/L1Menu",
"src_encoding": "UTF-8",
"text": "#!/bin/env python\n# Example PBS cluster job submission in Python\n\nimport os\nimport time\nimport glob\nimport re\nimport subprocess\n\n\n###############################\nDelDir = None #Auto pick up by CMSSW_BASE\nDryRun = False\nDelExe = 'testMenu2016'\n# OutDir = 'Output/ITGv27/'\n# OutDir = 'Output/ITGv19Study/'\n# OutDir = 'Output/TSGv4Vsv3/'\nOutDir = 'Output/ITGv59'\n# Analysis = 'MuonPU2'\n# Analysis = 'MenuPU3'\n# Analysis = 'PFMET'\nAnalysis = 'doubleMu2'\nMenuFile = [\n # \"menu/Menu_MuonStudy.txt\",\n # \"menu/Menu_MuonStudy.txt\",\n # \"menu/Menu_None.txt\"\n # \"menu/Menu_259721_TSGv4_Prescales.txt\",\n # \"menu/Menu_259721_TSGv3_FixPre_EG.txt\",\n \"menu/Lumi5E33_TSGv5_Prescales.txt\",\n # \"menu/Menu_259721_TSGv5_Prescales.txt\",\n # \"menu/Menu_ETMStudy.txt\",\n]\nNtuplelist = [\n #\"ntuple/r259721_tsgv4Latest.list\"\n # \"ntuple/r259721_tsgv3.list\",\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TSG-v4 ~~~~~\n # \"ntuple/MC10PU_tsgv4.list\",\n # \"ntuple/MC20PU_tsgv4.list\",\n # \"ntuple/MC30PU_tsgv4.list\",\n # \"ntuple/MC40PU_tsgv4.list\",\n # \"ntuple/MC50PU_tsgv4.list\",\n # \"ntuple/r258425_tsgv4.list\",\n # \"ntuple/r258427_tsgv4.list\",\n # \"ntuple/r258428_tsgv4.list\",\n # \"ntuple/r258434_tsgv4.list\",\n # \"ntuple/r258440_tsgv4.list\",\n # \"ntuple/r258445_tsgv4.list\",\n # \"ntuple/r258448_tsgv4.list\",\n # \"ntuple/r259626_tsgv4.list\",\n # \"ntuple/r259721_tsgv4.list\",\n # \"ntuple/SingleMuZmu_tsgv4.list\",\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TSGv4-METFix ~~~~~\n #\"ntuple/r259721_tsgv4METfix.list\",\n #\"ntuple/r259721_tsgv4.list\",\n #\"ntuple/r259721_gomber.list\",\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Integration v19 ~~~~~\n # \"ntuple/r258440_itgv19Layer1.list\",\n # \"ntuple/r258440_itgv19.list\",\n # \"ntuple/r259626_itgv19Layer1.list\",\n # \"ntuple/r259626_itgv19.list\",\n # \"ntuple/r259721_itgv19Layer1.list\",\n # \"ntuple/r259721_itgv19.list\",\n # \"ntuple/SingleMuZmu_itgv19Layer1.list\",\n # \"ntuple/SingleMuZmu_itgv19.list\",\n # \"ntuple/r259721_itgv19Layer1_Reco.list\",\n # \"ntuple/r259721_itgv19_Reco.list\",\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ TSGv4p1 ~~~~~\n # \"ntuple/MC20PU_tsgv4p1.list\",\n # \"ntuple/MC30PU_tsgv4p1.list\",\n # \"ntuple/r258440_tsgv4p1.list\",\n # \"ntuple/r259626_tsgv4p1.list\",\n # \"ntuple/r259721_tsgv4p1.list\",\n # \"ntuple/SingleMuZmu_tsgv4p1.list\",\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Integration v27 ~~~~~\n # \"ntuple/MC20PU_itgv27.list\",\n # \"ntuple/MC30PU_itgv27.list\",\n # \"ntuple/MC40PU_itgv27.list\",\n # \"ntuple/r258440_itgv27.list\",\n # \"ntuple/r259626_itgv27.list\",\n # \"ntuple/r259721_itgv27.list\",\n # \"ntuple/SingleMuZmu_itgv27.list\",\n # \"ntuple/r259721_itgv35.list\"\n # \"ntuple/r259721_itgv37p2_Opt5.list\"\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Com ~~~~~\n # \"ntuple/r271306_unpack.list\",\n # \"ntuple/r271306_TSGv5p1.list\"\n # \"ntuple/r258440_itgv42p1.list\",\n # \"ntuple/r259626_itgv42p1.list\",\n # \"ntuple/r259721_itgv42p1.list\",\n\n # \"ntuple/r271071_itgv42p1.list\",\n # \"ntuple/r271074_itgv42p1.list\",\n # \"ntuple/r271075_itgv42p1.list\",\n # \"ntuple/r271084_itgv42p1.list\",\n # \"ntuple/r271306_itgv42p1.list\",\n # \"ntuple/r271336_itgv42p1.list\",\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Itg-v42.1 ~~~~~\n # \"ntuple/r271336_itgv42p1.list\",\n # \"ntuple/r271336_unpack.list\",\n\n # \"ntuple/r272011_itgv42p1.list\",\n # \"ntuple/r272011_unpack.list\",\n # \"ntuple/r272022_itgv42p1.list\",\n # \"ntuple/r272022_unpack.list\",\n\n # \"ntuple/r258440_itgv46p0.list\",\n # \"ntuple/r259626_itgv46p0.list\",\n # \"ntuple/r259721_itgv46p0.list\",\n # \"ntuple/r272011_itgv46p0.list\",\n # \"ntuple/r272022_itgv46p0.list\",\n\n\n # \"ntuple/r272011_itgv48p2.list\",\n # \"ntuple/r272022_itgv48p2.list\",\n # \"ntuple/r272784_itgv48p2.list\",\n # \"ntuple/r272798_itgv48p2.list\",\n # \"ntuple/r272812_itgv48p2.list\",\n # \"ntuple/r272818_itgv48p2.list\",\n # \"ntuple/r272828_itgv48p2.list\",\n # \"ntuple/r272011_itgv48.list\",\n # \"ntuple/r272022_itgv48.list\",\n # \"ntuple/r272784_itgv48.list\",\n # \"ntuple/r272798_itgv48.list\",\n # \"ntuple/r272812_itgv48.list\",\n # \"ntuple/r272818_itgv48.list\",\n # \"ntuple/r272011_unpack.list\",\n # \"ntuple/r272022_unpack.list\",\n # \"ntuple/r272784_unpack.list\",\n # \"ntuple/r272798_unpack.list\",\n # \"ntuple/r272812_unpack.list\",\n # \"ntuple/r272818_unpack.list\",\n\n \"ntuple/r273725_itgv59.list\",\n \"ntuple/r273728_itgv59.list\",\n \"ntuple/r273730_itgv59.list\",\n # \"ntuple/r273725_itgv58.list\",\n # \"ntuple/r273728_itgv58.list\",\n # \"ntuple/r272828_unpack.list\",\n # \"ntuple/r272022_unpack.list\",\n # \"ntuple/r272011_unpack.list\",\n # \"ntuple/r272784_unpack.list\",\n # \"ntuple/r272812_unpack.list\",\n # \"ntuple/r272818_unpack.list\",\n # \"ntuple/r272798_unpack.list\",\n]\nGlobalOpt = \"\"\n# GlobalOpt += \" --doPlotEff\"\nGlobalOpt += \" --doPlotRate\"\n# GlobalOpt += \" --doPlotTest\"\nGlobalOpt += \" --SetNoPrescale\"\nGlobalOpt += \" --doPrintPU\"\n# GlobalOpt += \" --UsePFMETNoMuon\"\n# GlobalOpt += \" --doPlotRate --doPrintPU\"\nOptions = {\n # None:\"\",\n #\"test\" : \"-n 10\"\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Muon ER Study ~~~~~\n #\"MuER0p8\" : \"--SetMuonER 0.8\",\n #\"MuER1p2\" : \"--SetMuonER 1.25\",\n #\"MuER1p5\" : \"--SetMuonER 1.5\",\n #\"MuER1p8\" : \"--SetMuonER 1.8\",\n #\"MuER2p0\" : \"--SetMuonER 2.0\",\n #\"MuER2p1\" : \"--SetMuonER 2.1\",\n #\"MuER2p2\" : \"--SetMuonER 2.2\",\n #\"MuER2p3\" : \"--SetMuonER 2.3\",\n #\"MuER2p4\" : \"--SetMuonER 2.4\",\n #\"MuER2p5\" : \"--SetMuonER 2.5\",\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ Muon Turn on Study ~~~~~\n #\"r258425\" : \"--SelectRun 258425\",\n #\"r258427\" : \"--SelectRun 258427\",\n #\"r258428\" : \"--SelectRun 258428\",\n #\"r258434\" : \"--SelectRun 258434\",\n #\"r258440\" : \"--SelectRun 258440\",\n #\"r258445\" : \"--SelectRun 258445\",\n #\"r258448\" : \"--SelectRun 258448\",\n #\"r259626\" : \"--SelectRun 259626\",\n\n#~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ MET Cross Check ~~~~~\n #\"r259721\" : \"--SelectRun 259721\",\n \"EmuC++\" : \"\",\n \"EmuGT\" : \"--UseuGTDecision\",\n # #\"Bitwise\" : \"--UseUpgradeLyr1\",\n # \"Float\" : \" --SumJetET 30 --UseL1CaloTower\",\n \"UnpackuGT\" : \" --UseuGTDecision --UseUnpackTree\",\n \"UnpackC++\" : \" --UseUnpackTree\",\n\n}\n# LSFque = '8nm'\nLSFque = '8nh'\n# LSFque = '1nd'\n# nBunches = 6840 ## From 12PU scaled to 30PU\nnBunches = 1165\n# nBunches = 8\n# nBunches = 3963.7\n\ndef BSUB(Analysis, Menu_, Ntuple_, Option):\n global LSFque\n\n # Open a pipe to the qsub command.\n #output, input = popen2('echo')\n\n Menu = \"%s/%s\" % (DelDir, Menu_)\n Ntuple =\"%s/%s\" % (DelDir, Ntuple_)\n stripMenu = os.path.splitext(os.path.basename(Menu))[0]\n stripNtuple = os.path.splitext(os.path.basename(Ntuple))[0]\n job_name = \"%s_%s_%s_%s\" % (Analysis, stripMenu, stripNtuple, Option[0])\n if len(MenuFile) == 1:\n out_name = \"_\".join(filter(None, (stripNtuple, Option[0])))\n else:\n out_name = \"_\".join(filter(None, (stripMenu, stripNtuple, Option[0])))\n\n cmd = \"./%s %s -m %s -l %s -o %s -b %f %s\" % (os.path.basename(DelExe), Option[1], Menu, Ntuple,out_name, nBunches, GlobalOpt)\n if DryRun:\n print cmd\n return\n\n p = subprocess.Popen('bsub', shell=True, stdin=subprocess.PIPE, stdout=subprocess.PIPE, close_fds=True)\n output, input = (p.stdout, p.stdin)\n ## -J Job name\n ## -o output -e error\n ## -q Que:\n ### 8nm (8 minutes)\n ### 1nh (1 hour)\n ### 8nh\n ### 1nd (1day)\n ### 2nd\n ### 1nw (1 week)\n ### 2nw\n job_string = \"\"\"#!/bin/tcsh\n #BSUB -q %s\n #BSUB -J %s\n #BSUB -o %s/%s_stdout\n #BSUB -e %s/%s_stderr\n date\n cp %s ./\n ## Need this to fix the problem with batch node\n setenv LD_LIBRARY_PATH ''\n set TOP=\"$PWD\"\n set CMSSW=%s\n cd $CMSSW/src\n eval `scramv1 runtime -csh`\n cd $TOP\n mkdir menu\n cp $CMSSW/src/L1TriggerDPG/L1Menu/macros/menu/run_lumi.csv menu/\n %s\n ls\n foreach i (`ls results`)\n rfcp results/$i %s\n end\n date\"\"\" % (LSFque, job_name, OutDir, job_name, OutDir, job_name, DelExe, os.environ['CMSSW_BASE'], cmd, OutDir)\n\n #print job_string\n # Send job_string to qsub\n input.write(job_string)\n input.close()\n\n # Print your job and the response to the screen\n print job_string\n print output.read()\n\n time.sleep(1)\n\ndef my_process():\n global OutDir\n ## Some checking first\n my_CheckFile()\n\n ## Create the output directory\n OutDir = \"%s/%s/%s\" % (DelDir , OutDir, Analysis)\n try:\n os.makedirs(OutDir)\n except OSError:\n pass\n\n for menu in MenuFile:\n for ntuple in Ntuplelist:\n for opt in Options.items():\n #print Analysis, menu, ntuple, opt\n BSUB(Analysis, menu, ntuple, opt)\n\ndef my_CheckFile():\n global DelDir\n global DelExe\n ## Check the Delphes Dir\n DelDir = \"%s/src/L1TriggerDPG/L1Menu/macros/\" % os.environ['CMSSW_BASE']\n\n ## Check DelFill to be execute\n DelExe = DelDir + \"/\" + DelExe\n if os.path.isfile(DelExe) and os.access(DelExe, os.X_OK):\n #print \"Found DelFill\"\n pass\n else:\n DelExe = DelDir + \"/\" + DelExe.split(\"/\")[-1]\n if os.path.isfile(DelExe) and os.access(DelExe, os.X_OK):\n #print \"Found DelFill\"\n pass\n else:\n print \"Please locate %s\" % DelExe\n quit()\n\n\nif __name__ == \"__main__\":\n my_process()\n"
}
] | 36 |
thehyve/v2d_data | https://github.com/thehyve/v2d_data | fb565f6cb3e971ad0e9b408f731f1030610c062a | 4f4e84316f897dc8a01f972925f63151715fe570 | 421712383b7f90c6e11d21ce59c53faddb6ae29f | refs/heads/master | 2022-08-25T20:39:56.219479 | 2021-06-22T13:43:18 | 2021-06-22T13:43:18 | 154,505,304 | 1 | 0 | Apache-2.0 | 2018-10-24T13:23:09 | 2022-06-27T17:43:40 | 2022-07-26T09:31:39 | Python | [
{
"alpha_fraction": 0.5473037958145142,
"alphanum_fraction": 0.5530608296394348,
"avg_line_length": 28.275279998779297,
"blob_id": "2f156c4bb0409fc60e018ed1679f8c7a3e756939",
"content_id": "5ec09684420f217432fea3cd7fa37797331ea1fc",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5211,
"license_type": "permissive",
"max_line_length": 126,
"num_lines": 178,
"path": "/scripts/make_UKB_study_table.py",
"repo_name": "thehyve/v2d_data",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Ed Mountjoy\n#\n\nimport re\nimport sys\nimport os\nimport argparse\nimport pandas as pd\nfrom pprint import pprint\nfrom collections import OrderedDict\nfrom operator import itemgetter\nimport json\n\ndef main():\n\n # Parse args\n args = parse_args()\n\n # Load manifest\n manifest = pd.read_csv(args.in_manifest, sep='\\t',\n header=0, dtype=object)\n \n # Only keep required cols\n to_keep = OrderedDict([\n ('code', 'study_id'),\n ('trait', 'trait_raw'),\n ('n_total', 'n_total'),\n ('n_cases', 'n_cases')\n ])\n manifest = (\n manifest\n .loc[:, to_keep.keys()]\n .rename(columns=to_keep)\n )\n\n #\n # Clean trait names -------------------------------------------------------\n #\n\n # Get list of phenotype prefixes with counts\n counts = count_prefixes(manifest['trait_raw'].tolist())\n with open(args.prefix_counts, 'w') as out_h:\n for prefix, count in sorted(counts.items(),\n key=itemgetter(1),\n reverse=True):\n out_h.write('{}\\t{}\\n'.format(prefix, count))\n \n # Move prefixes to suffix (helps when viewed in the UI)\n manifest['trait_reported'] = (\n manifest['trait_raw'].apply(make_trait_reported_string)\n ) \n\n #\n # Add other columns -------------------------------------------------------\n #\n\n # Vector to get Neale or SAIGE studies\n is_neale = manifest['study_id'].str.startswith(\"NEALE2_\")\n is_saige = manifest['study_id'].str.startswith(\"SAIGE_\")\n assert (is_neale | is_saige).all()\n\n # Make columns\n manifest.loc[:, 'pmid'] = ''\n manifest.loc[is_neale, 'pub_date'] = '2018-08-01'\n manifest.loc[is_saige, 'pub_date'] = '2018-10-24'\n manifest.loc[:, 'pub_journal'] = ''\n manifest.loc[:, 'pub_title'] = ''\n manifest.loc[is_neale, 'pub_author'] = 'UKB Neale v2'\n manifest.loc[is_saige, 'pub_author'] = 'UKB SAIGE'\n manifest.loc[:, 'n_initial'] = manifest['n_total'].apply(to_int_safe)\n manifest.loc[:, 'n_cases'] = manifest['n_cases'].apply(to_int_safe)\n manifest.loc[:, 'n_replication'] = 0\n manifest.loc[:, 'ancestry_initial'] = 'European=' + manifest['n_initial'].astype(str)\n manifest.loc[:, 'ancestry_replication'] = ''\n\n # Load efos annotations\n efo_mapper = {}\n with open(args.in_efos, 'r') as in_h:\n for line in in_h:\n parts = json.loads(line)\n efo_mapper[parts['study_id']] = parts['efos']\n \n # Map efos\n manifest['trait_efos'] = manifest['study_id'].apply(\n lambda stid: efo_mapper.get(stid, None)\n )\n\n # Ouput required columns\n cols = OrderedDict([\n ('study_id', 'study_id'),\n ('pmid', 'pmid'),\n ('pub_date', 'pub_date'),\n ('pub_journal', 'pub_journal'),\n ('pub_title', 'pub_title'),\n ('pub_author', 'pub_author'),\n ('trait_reported', 'trait_reported'),\n ('trait_efos', 'trait_efos'),\n # ('trait_category', 'trait_category'),\n ('ancestry_initial', 'ancestry_initial'),\n ('ancestry_replication', 'ancestry_replication'),\n ('n_initial', 'n_initial'),\n ('n_cases', 'n_cases'),\n ('n_replication', 'n_replication')\n ])\n manifest = ( manifest.loc[:, list(cols.keys())]\n .rename(columns=cols) )\n\n # Write\n manifest.to_json(args.outf, orient='records', lines=True)\n\ndef to_int_safe(i):\n try:\n return int(float(i))\n except ValueError:\n return None\n\ndef make_trait_reported_string(s_raw):\n ''' Takes the raw trait name and outputs trnasformed name\n '''\n\n # Replace any double spaces with single\n s_raw = re.sub(r' +', r' ', s_raw)\n\n # Assert no \"|\" in trait name\n assert \"|\" not in s_raw\n\n # Split prefix\n parts = s_raw.split(': ', 1)\n\n # Move prefix to end if exists\n if len(parts) == 2:\n trait = \" | \".join([parts[1], parts[0]])\n else:\n trait = s_raw\n\n # Capitalise the frist letter\n trait = trait.capitalize()\n \n return trait\n\ndef count_prefixes(l, sep=': '):\n ''' Counts the occurence of prefixes based on sep\n '''\n # Extract prefixes\n prefixes = []\n for entry in l:\n parts = entry.split(sep)\n if len(parts) > 1:\n prefixes.append(parts[0])\n # Count\n counts = {}\n for prefix in prefixes:\n try:\n counts[prefix] += 1\n except KeyError:\n counts[prefix] = 1\n \n return counts\n\ndef combine_rows(items):\n return ';'.join(items)\n\ndef parse_args():\n \"\"\" Load command line args \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--in_manifest', metavar=\"<str>\", help=(\"Input\"), type=str, required=True)\n parser.add_argument('--in_efos', metavar=\"<str>\", help=(\"EFO mapping file\"), type=str, required=True)\n parser.add_argument('--prefix_counts', metavar=\"<str>\", help=(\"File to output prefix counts to\"), type=str, required=True)\n parser.add_argument('--outf', metavar=\"<str>\", help=(\"Output\"), type=str, required=True)\n args = parser.parse_args()\n return args\n\nif __name__ == '__main__':\n\n main()\n"
},
{
"alpha_fraction": 0.6442494988441467,
"alphanum_fraction": 0.6461988091468811,
"avg_line_length": 22.31818199157715,
"blob_id": "174c3d64725c935c0fdaff223d6336ef750a9347",
"content_id": "18a45aed272ee3573334ada10dba5239a89211fc",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1026,
"license_type": "permissive",
"max_line_length": 106,
"num_lines": 44,
"path": "/scripts/merge_study_tables.py",
"repo_name": "thehyve/v2d_data",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Ed Mountjoy\n#\n# Merge top loci table\n#\n\nimport sys\nimport argparse\nimport pandas as pd\nfrom collections import OrderedDict\nfrom parquet_writer import write_parquet\nimport datetime\n\ndef main():\n\n # Parse args\n args = parse_args()\n\n # Load\n gwas = pd.read_json(args.in_gwascat, orient='records', lines=True)\n ukb = pd.read_json(args.in_ukb, orient='records', lines=True)\n\n # Merge\n merged = pd.concat([gwas, ukb], sort=False)\n\n # Write\n merged.to_json(args.output, orient='records', lines=True)\n\n return 0\n\ndef parse_args():\n \"\"\" Load command line args \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--in_gwascat', metavar=\"<str>\", type=str, required=True)\n parser.add_argument('--in_ukb', metavar=\"<str>\", type=str, required=True)\n parser.add_argument('--output', metavar=\"<str>\", help=(\"Output merged file\"), type=str, required=True)\n args = parser.parse_args()\n return args\n\nif __name__ == '__main__':\n\n main()\n"
},
{
"alpha_fraction": 0.559680163860321,
"alphanum_fraction": 0.5767180919647217,
"avg_line_length": 31.93416976928711,
"blob_id": "d18d3eaa92857dfb57750d510a34a427ae1bda5c",
"content_id": "09f970abe3b9f94b53aacacae6e86c2137212911",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 10506,
"license_type": "permissive",
"max_line_length": 162,
"num_lines": 319,
"path": "/scripts/study_table_to_parquet.py",
"repo_name": "thehyve/v2d_data",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Ed Mountjoy\n#\n# Merge top loci table\n#\n\nimport os\nimport sys\nimport argparse\nimport pandas as pd\nfrom collections import OrderedDict\nfrom parquet_writer import write_parquet\nimport datetime\nimport json\n\ndef main():\n\n # Parse args\n args = parse_args()\n\n # Load\n merged = pd.read_json(args.in_study_table, orient='records', lines=True)\n\n #\n # Annotate whether summary stats are available ----------------------------\n #\n\n # Load list of study IDs that have sumstats\n from_sumstats = set([])\n with open(args.sumstat_studies, 'r') as in_h:\n for line in in_h:\n # Get study_id\n line = line.rstrip().rstrip('/')\n stid = os.path.basename(line).replace('.parquet', '')\n from_sumstats.add(stid)\n \n # Annotate study table with field showing if there are sumstats\n merged['has_sumstats'] = merged['study_id'].isin(from_sumstats)\n\n #\n # Fail if there are any sumstat studies not in table ----------------------\n #\n\n # Get list of study IDs that are in the sumstats but not the study table\n from_sumstats_series = pd.Series(list(from_sumstats))\n missing_ids = from_sumstats_series[\n ~from_sumstats_series.isin(merged['study_id'])\n ]\n\n # Add missing studies manually (we shouldn't have to do this but\n # occasionally GWAS Catalog will remove studies without warning due to\n # a curation error being detected)\n manual_additions = pd.DataFrame([\n {'ancestry_initial': 'European=360063',\n 'ancestry_replication': None,\n 'n_cases': 108473,\n 'n_initial': 360063,\n 'n_replication': None,\n 'pmid': None,\n 'pub_author': 'UKB Neale v2',\n 'pub_date': '2018-08-01',\n 'pub_journal': '',\n 'pub_title': '',\n 'study_id': 'NEALE2_6160_1',\n 'trait_efos': None,\n 'trait_reported': 'Leisure/social activities: Sports club or gym',\n 'has_sumstats': True},\n {'ancestry_initial': 'European=360088',\n 'ancestry_replication': None,\n 'n_cases': 326854,\n 'n_initial': 360088,\n 'n_replication': None,\n 'pmid': None,\n 'pub_author': 'UKB Neale v2',\n 'pub_date': '2018-08-01',\n 'pub_journal': '',\n 'pub_title': '',\n 'study_id': 'NEALE2_670_1',\n 'trait_efos': None,\n 'trait_reported': 'Type of accommodation lived in: A house or bungalow',\n 'has_sumstats': True},\n {'ancestry_initial': 'European=359931',\n 'ancestry_replication': None,\n 'n_cases': 2818,\n 'n_initial': 359931,\n 'n_replication': None,\n 'pmid': None,\n 'pub_author': 'UKB Neale v2',\n 'pub_date': '2018-08-01',\n 'pub_journal': '',\n 'pub_title': '',\n 'study_id': 'NEALE2_6142_7',\n 'trait_efos': None,\n 'trait_reported': 'Current employment status: Full or part-time student',\n 'has_sumstats': True},\n {'ancestry_initial': 'European=20883',\n 'ancestry_replication': 'European=41309;Greater Middle Eastern (Middle Eastern / North African / Persian)=493;South Asian=1174;East Asian=5409',\n 'n_cases': 5956,\n 'n_initial': 20883,\n 'n_replication': 48385,\n 'pmid': 'PMID:26192919',\n 'pub_author': 'Liu JZ',\n 'pub_date': '2015-07-20',\n 'pub_journal': 'Nat Genet',\n 'pub_title': 'Association analyses identify 38 susceptibility loci for inflammatory bowel disease and highlight shared genetic risk across populations.',\n 'study_id': 'GCST003044',\n 'trait_efos': ['EFO_0000384'],\n 'trait_reported': \"Crohn's disease\"}\n ])\n\n # Only keep manual additions if they are missing (when GWAS Catalog re-add\n # them at a later I won't have to do anything)\n manual_additions = manual_additions.loc[\n manual_additions['study_id'].isin(missing_ids)\n ]\n \n # Merge manual additions\n merged = pd.concat([merged, manual_additions], axis=0, sort=True)\n\n # Assert that there are no longer any missing studies\n missing_ids = from_sumstats_series[\n ~from_sumstats_series.isin(merged['study_id'])\n ]\n if len(missing_ids) > 0:\n sys.exit(\n 'ERROR: the {0} following study IDs are in the summary statistics '\n 'but are missing from the study table, they will need adding '\n 'manually:\\n{1}'.format(len(missing_ids), missing_ids)\n )\n\n #\n # Annotate number of associated loci from top loci table ------------------\n #\n\n # Load the number of associated loci per study\n top_loci = pd.read_parquet(args.in_toploci, engine='pyarrow')\n num_loci = (top_loci\n .groupby('study_id')\n .size().reset_index(name='counts')\n .rename(columns={'counts': 'num_assoc_loci'}))\n merged = pd.merge(merged, num_loci, how='left', on='study_id')\n merged['num_assoc_loci'] = merged['num_assoc_loci'].fillna(\n value=0).astype(int)\n\n #\n # Annotate EFOs with therapeutic area (trait category) --------------------\n #\n\n # Make sure that the trait_efos column is a list\n merged['trait_efos'] = merged['trait_efos'].apply(clean_efo)\n\n # Load efo to category mappings\n efo_anno = {}\n with open(args.efo_categories, 'r') as in_h:\n for line in in_h:\n parts = json.loads(line)\n efo_anno[parts['efo_term']] = parts['therapeutic_areas']\n \n # Load theraputic areas to sort results against\n ta_dict = load_therapeutic_area_labels(args.in_ta)\n\n # Annotate efos with therapeutic areas\n merged['trait_category_list'] = merged['trait_efos'].apply(\n annotate_efos,\n efo_anno_dict=efo_anno,\n sort_list=list(ta_dict.values())\n )\n\n # Select first\n merged['trait_category'] = merged['trait_category_list'].apply(\n select_best_category,\n unknown_label=args.unknown_label\n )\n\n # Remove category_list\n merged = merged.drop('trait_category_list', axis=1)\n\n #\n # Format output parquet ---------------------------------------------------\n #\n\n # # Debug\n # merged.to_csv('tmp_study_table.tsv', sep='\\t', index=None)\n # sys.exit()\n\n # Coerce data types\n dtypes = OrderedDict([\n ('study_id', 'object'),\n ('pmid', 'object'),\n ('pub_date', 'object'),\n ('pub_journal', 'object'),\n ('pub_title', 'object'),\n ('pub_author', 'object'),\n ('trait_reported', 'object'),\n ('trait_efos', 'object'),\n ('ancestry_initial', 'object'),\n ('ancestry_replication', 'object'),\n ('n_initial', 'Int64'),\n ('n_replication', 'Int64'),\n ('n_cases', 'Int64'),\n ('trait_category', 'object'),\n ('num_assoc_loci', 'Int64'),\n ('has_sumstats', 'bool')\n \n ])\n assert(set(dtypes.keys()) == set(merged.columns))\n merged = (\n merged.loc[:, dtypes.keys()]\n .astype(dtype=dtypes)\n )\n\n # Split array columns\n split_cols = ['ancestry_initial', 'ancestry_replication']\n for col in split_cols:\n merged[col] = merged[col].str.split(';')\n\n # Sort output\n merged = merged.sort_values(['study_id'])\n\n # DEBUG output study table\n merged.to_csv('tmp/study_table.tsv', sep='\\t', index=None)\n\n # Save as parquet\n array_cols = ['trait_efos', 'ancestry_initial', 'ancestry_replication']\n write_parquet(merged,\n args.output,\n str_list_cols=array_cols,\n compression='snappy',\n flavor='spark')\n\n return 0\n\n\ndef clean_efo(value):\n ''' Always returns a list of EFOs or empty list\n '''\n if isinstance(value, list):\n return value\n elif pd.isnull(value):\n return []\n elif isinstance(value, str):\n return [value]\n else:\n assert True, 'Error: unrecognised EFO column type {} {}'.format(type(value), value)\n\ndef select_best_category(cat_list, unknown_label):\n ''' Selects the best (first) category for use in the portal\n '''\n try:\n return cat_list[0].capitalize()\n except IndexError:\n return unknown_label.capitalize()\n\n\ndef annotate_efos(efo_list, efo_anno_dict, sort_list=None):\n ''' Returns therapeutic area annotations for one or more efos\n Params:\n efo_list (list): list of EFO terms\n efo_anno_dict (dict): dictionary of efo to TA mappings\n sort_list (list): list against which to sort terms\n Return:\n list of therapeutic ares\n '''\n # Make list\n ta_list = []\n for efo in efo_list:\n tas = efo_anno_dict.get(efo, [])\n ta_list = ta_list + tas\n\n # Sort list\n if sort_list:\n ta_list = sorted(\n ta_list, key=lambda x: sort_list.index(x)\n )\n\n return ta_list\n\ndef load_therapeutic_area_labels(inf):\n ''' Loads therapeutic labels and display labels\n '''\n d = OrderedDict()\n with open(inf, 'r') as in_h:\n in_h.readline() # skip header\n for line in in_h:\n \n if line.startswith('#'):\n continue\n\n try:\n category, term_label, display_label = line.rstrip().split('\\t')\n except ValueError:\n sys.exit('Error for in {}: {}'.format(inf, line))\n\n if term_label in d:\n sys.exit(\n 'Error: duplicate term_label in therapuetic'\n ' area list: {}'.format(term_label)\n )\n d[term_label] = display_label\n return d\n\ndef parse_args():\n \"\"\" Load command line args \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--in_study_table', metavar=\"<str>\", type=str, required=True)\n parser.add_argument('--in_toploci', metavar=\"<str>\", type=str, required=True)\n parser.add_argument('--sumstat_studies', metavar=\"<str>\", help=(\"List of studies with sumstats\"), type=str, required=True)\n parser.add_argument('--efo_categories', metavar=\"<str>\", help=(\"Efo category mappings\"), type=str, required=True)\n parser.add_argument('--in_ta', metavar=\"<str>\", help=(\"Therapuetic are list\"), type=str, required=True)\n parser.add_argument('--unknown_label', metavar=\"<str>\", help=(\"Category label when unkown\"), type=str, required=True)\n parser.add_argument('--output', metavar=\"<str>\", help=(\"Output merged file\"), type=str, required=True)\n args = parser.parse_args()\n return args\n\nif __name__ == '__main__':\n\n main()\n"
},
{
"alpha_fraction": 0.6070312261581421,
"alphanum_fraction": 0.6109374761581421,
"avg_line_length": 31,
"blob_id": "1d95ac7ad8c094b8f27bcd10af66055224c7af5c",
"content_id": "2cc26f5b0563d065d41c7afa9780beb29632eba9",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1280,
"license_type": "permissive",
"max_line_length": 133,
"num_lines": 40,
"path": "/scripts/study_tsv2json.py",
"repo_name": "thehyve/v2d_data",
"src_encoding": "UTF-8",
"text": "import csv\nimport json\nimport sys\n\ncsvfile = open(sys.argv[1], 'r+')\njsonfile = open(sys.argv[2], 'w+')\n\nfields = [\"study_id\", \"pmid\", \"pub_date\", \"pub_journal\", \"pub_title\", \"pub_author\", \"trait_reported\", \"trait_code\", \"trait_category\"]\n\nfields_array = [\"trait_efos\", \"ancestry_initial\", \"ancestry_replication\"]\n\nfields_int = [\"n_initial\", \"n_replication\", \"n_cases\"]\ndef remove_if_empty(line, fields):\n for field in fields:\n if field in line and len(line[field]) == 0:\n del(line[field])\n return line\n\ndef string_to_int(line, fields):\n for field in fields:\n if field in line and len(line[field]) > 0:\n line[field] = int(round(float(line[field])))\n return line\n\ndef string_to_list(line, fields, sep=';'):\n for field in fields:\n if field in line and len(line[field]) > 0:\n tokens = line[field].split(sep)\n line[field] = list(map(lambda el: el.strip(), tokens))\n else:\n line[field] = []\n return line\n\nreader = csv.DictReader(csvfile, delimiter=\"\\t\")\nfor row in reader:\n cleaned_line = string_to_int(\n string_to_list(\n remove_if_empty(row,fields+fields_array+fields_int),fields_array), fields_int)\n json.dump(row, jsonfile)\n jsonfile.write('\\n')\n"
},
{
"alpha_fraction": 0.6066718101501465,
"alphanum_fraction": 0.6136540174484253,
"avg_line_length": 28.295454025268555,
"blob_id": "52c6e41755bb7349061ff2d46eccfa28867089fa",
"content_id": "5f396c91145c9370f7e235f0fe20ed00e5bd3c1e",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1289,
"license_type": "permissive",
"max_line_length": 141,
"num_lines": 44,
"path": "/scripts/overlap_table_tsv2json.py",
"repo_name": "thehyve/v2d_data",
"src_encoding": "UTF-8",
"text": "import csv\nimport json\nimport sys\nimport gzip\n\ncsvfile = gzip.open(sys.argv[1], 'rt')\njsonfile = gzip.open(sys.argv[2], 'wt')\n\nfields = [\"study_id_A\", \"index_variantid_b37_A\", \"study_id_B\", \"index_variantid_b37_B\", \"set_type\", \"distinct_A\", \"overlap_AB\", \"distinct_B\"]\n\nfields_array = []\n\nfields_int = [\"distinct_A\", \"overlap_AB\", \"distinct_B\"]\ndef remove_if_empty(line, fields):\n for field in fields:\n if field in line and len(line[field]) == 0:\n del(line[field])\n return line\n\ndef string_to_int(line, fields):\n for field in fields:\n if field in line and len(line[field]) > 0:\n line[field] = int(round(float(line[field])))\n return line\n\ndef string_to_list(line, fields, sep=';'):\n for field in fields:\n if field in line and len(line[field]) > 0:\n tokens = line[field].split(sep)\n line[field] = list(map(lambda el: el.strip(), tokens))\n else:\n line[field] = []\n return line\n\nreader = csv.DictReader(csvfile, delimiter=\"\\t\")\nfor row in reader:\n cleaned_line = string_to_int(\n string_to_list(\n remove_if_empty(row,fields+fields_array+fields_int),fields_array), fields_int)\n json.dump(row, jsonfile)\n jsonfile.write('\\n')\n\ncsvfile.close()\njsonfile.close()\n"
},
{
"alpha_fraction": 0.5925562977790833,
"alphanum_fraction": 0.5954946279525757,
"avg_line_length": 22.744186401367188,
"blob_id": "2141ef99bcf04165f0315844aa6e09accb386bfe",
"content_id": "930bc76a4f72bdf84329653032fd93adf990393d",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1021,
"license_type": "permissive",
"max_line_length": 96,
"num_lines": 43,
"path": "/scripts/list_ancestries.py",
"repo_name": "thehyve/v2d_data",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Ed Mountjoy\n#\n\nimport sys\nimport os\nimport argparse\nimport pandas as pd\n\ndef main():\n\n # Parse args\n args = parse_args()\n\n # Load\n df = pd.read_csv(args.inf, sep='\\t', header=0)\n\n # Parse ancestries\n anc_list = df.ancestry_initial.dropna().tolist() + df.ancestry_replication.dropna().tolist()\n anc_clean = []\n for anc_str in anc_list:\n for entry in anc_str.split(';'):\n anc = entry.split('=')[0]\n anc_clean.append(anc)\n\n # Output\n out = pd.DataFrame(list(set(anc_clean)), columns=['gwascat_population'])\n out.to_csv(args.outf, sep='\\t', index=None)\n\n\ndef parse_args():\n \"\"\" Load command line args \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--inf', metavar=\"<str>\", help=(\"Input\"), type=str, required=True)\n parser.add_argument('--outf', metavar=\"<str>\", help=(\"Output\"), type=str, required=True)\n args = parser.parse_args()\n return args\n\nif __name__ == '__main__':\n\n main()\n"
},
{
"alpha_fraction": 0.6034979820251465,
"alphanum_fraction": 0.6182971596717834,
"avg_line_length": 33.217105865478516,
"blob_id": "0384fb4181a087cc3b51eed0d309cdbf1bb6d4ca",
"content_id": "fe98415c32407d47dc86089a9a4ab3300092edc3",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5203,
"license_type": "permissive",
"max_line_length": 141,
"num_lines": 152,
"path": "/scripts/Make_FINNGEN_entries.py",
"repo_name": "thehyve/v2d_data",
"src_encoding": "UTF-8",
"text": "\n# coding: utf-8\n\n# In[ ]:\n\nimport re\nimport sys\nimport os\nimport argparse\nimport pandas as pd\nfrom pprint import pprint\nfrom collections import OrderedDict\nfrom operator import itemgetter\nimport json\n\ndef main():\n\n # Parse args\n args = parse_args()\n\n # read manifest + EFO mappings\n\n FINNGEN_EFO=pd.read_csv(args.in_EFO, sep='\\t',\n header=0)\n\n FINNGEN_manifest = (pd.read_json(args.in_manifest, lines=True).rename(\n columns={\n 'phenocode': 'study_id',\n 'phenostring': 'trait',\n 'category': 'trait_category',\n 'num_cases': 'n_cases',\n 'num_controls': 'n_controls'\n }\n )\n )\n\n keep_columns = [\n 'study_id',\n 'trait',\n 'trait_category',\n 'n_cases',\n 'n_controls'\n ]\n FINNGEN_manifest = FINNGEN_manifest[keep_columns]\n\n FINNGEN_manifest['study_id'] = \"FINNGEN_R5_\" + FINNGEN_manifest['study_id']\n FINNGEN_manifest['n_total'] = FINNGEN_manifest['n_cases'] + FINNGEN_manifest['n_controls']\n\n\n # Keep valid EFOs\n\n FINNGEN_valid_EFO=FINNGEN_EFO.loc[FINNGEN_EFO['valid'] == True]\n #FINNGEN_valid_EFO=FINNGEN_EFO\n #FINNGEN_valid_EFO.head()\n\n FINNGEN_valid_EFO['FINNGEN_ID']=\"FINNGEN_R5_\"+FINNGEN_valid_EFO['NAME']\n to_keep= OrderedDict([\n ('FINNGEN_ID', 'study_id'),\n ('LONGNAME', 'trait_reported'),\n ('efo_cls', 'trait EFOs')])\n\n FINNGEN_valid_EFO_trimmed=FINNGEN_valid_EFO.loc[:, to_keep.keys()].rename(columns=to_keep)\n\n # Map manifest to efo trait and ID:\n\n\n FINNGEN_manifest['trait_efos']=FINNGEN_manifest.apply(lambda x: Get_EFO_mapping_list(x['study_id'], FINNGEN_valid_EFO_trimmed), axis=1)\n\n\n FINNGEN_manifest['trait_reported']=FINNGEN_manifest.apply(lambda x: Get_EFO_trait_list(x['study_id'], FINNGEN_valid_EFO_trimmed), axis=1)\n FINNGEN_manifest.head()\n\n # Format table:\n\n FINNGEN_manifest['pmid']=\"\"\n FINNGEN_manifest['pub_date']='2021-5-11'\n FINNGEN_manifest['pub_author']='FINNGEN_R5'\n FINNGEN_manifest['ancestry_initial']=\"European=\"+FINNGEN_manifest['n_total'].astype(str)\n FINNGEN_manifest['n_replication']=0\n FINNGEN_manifest['ancestry_replication']=\"\"\n FINNGEN_manifest['pub_journal']=\"\"\n FINNGEN_manifest['pub_title']=\"\"\n\n cols = OrderedDict([\n ('study_id', 'study_id'),\n ('pmid', 'pmid'),\n ('pub_date', 'pub_date'),\n ('pub_journal', 'pub_journal'),\n ('pub_title', 'pub_title'),\n ('pub_author', 'pub_author'),\n ('trait', 'trait_reported'),\n ('trait_efos', 'trait_efos'),\n ('ancestry_initial', 'ancestry_initial'),\n ('ancestry_replication', 'ancestry_replication'),\n ('n_total', 'n_initial'),\n ('n_cases', 'n_cases'),\n ('n_replication', 'n_replication')\n ])\n\n FINNGEN_manifest=FINNGEN_manifest.loc[:, list(cols.keys())].rename(columns=cols)\n\n Additional_row=pd.Series([\"GCST90013791\", \"\",\n \"2021-02-22\", \"\", \"\", \"Crouch D\", \"Type 1 diabetes\", \n [\"EFO_0001359\"], \"European=7977\", \"\", \"7977\", \"3983\", \"0\" ])\n\n row_df=pd.DataFrame([Additional_row])\n row_df=row_df.set_axis(list(FINNGEN_manifest.columns.values), axis=1, inplace=False)\n\n FINNGEN_manifest_new=pd.concat([FINNGEN_manifest, row_df], ignore_index=True)\n FINNGEN_manifest_new['trait_reported'][FINNGEN_manifest_new['study_id']==\"FINNGEN_R5_I9_HEARTFAIL_AND_CHD\"]=\"cardiovascular disease\"\n\n # Load no finngen study table\n gwas = pd.read_json(args.in_study_table, \n orient='records', lines=True)\n # Merge\n merged = pd.concat([gwas, FINNGEN_manifest], sort=False)\n print(merged)\n # Write\n merged.to_json(args.outf, orient='records', lines=True)\n\ndef Get_EFO_mapping_list(study_ids, EFOs):\n EFO_mappings=[]\n Found_EFOs=EFOs.loc[EFOs['study_id'].str.contains(study_ids)]['trait EFOs'].unique()\n return(Found_EFOs)\n\ndef Get_EFO_trait_list(study_ids, EFOs):\n EFO_mappings=[]\n Found_EFOs=EFOs.loc[EFOs['study_id'].str.contains(study_ids)]['trait_reported'].unique()\n return(Found_EFOs)\n\n\ndef parse_args():\n \"\"\" Load command line args \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--in_manifest', metavar=\"<str>\", type=str, required=True)\n parser.add_argument('--in_EFO', metavar=\"<str>\", type=str, required=True)\n parser.add_argument('--in_study_table', metavar=\"<str>\", type=str, required=True)\n parser.add_argument('--outf', metavar=\"<str>\", help=(\"Output\"), type=str, required=True)\n \n args = parser.parse_args()\n return args\n\nif __name__ == '__main__':\n\n main()\n\n# FINNGEN_manifest_path=\"/home/xg1/r5_finngen.json\"\n# FINNGEN_EFO_path=\"/home/xg1/finngen_df5_efo_mapping.lastest.nonull.tsv\"\n# \"/home/xg1/genetics-v2d-data/tmp/210526/merged_study_table.old.json\"\n# \"/home/xg1/genetics-v2d-data/tmp/210526/merged_study_table.json\"\n\n#python Manual_FINNGENs --in_manifest r5_finngen.json --in_EFO finngen_df5_efo_mapping.lastest.nonull.tsv \n# --in_study_table tmp/version_date/merged_study_table.old.json --outf tmp/version_date/merged_study_table.json\n\n"
},
{
"alpha_fraction": 0.5680073499679565,
"alphanum_fraction": 0.5766042470932007,
"avg_line_length": 27.823009490966797,
"blob_id": "0de08ef476c4aeb9751742872c7dc6a487fbb919",
"content_id": "17a97d597f446b9eb6d71d94f5cfe0fa5affb144",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6515,
"license_type": "permissive",
"max_line_length": 106,
"num_lines": 226,
"path": "/scripts/get_therapeutic_areas.py",
"repo_name": "thehyve/v2d_data",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Ed Mountjoy\n#\n\n'''\nhttp://www.ebi.ac.uk/ols/api/ontologies/efo/terms/http%253A%252F%252Fwww.ebi.ac.uk%252Fefo%252FEFO_0002508\n\n'''\n\nimport sys\nimport os\nimport pandas as pd\nimport requests\nimport json\nfrom pprint import pprint\nimport numpy as np\nfrom collections import OrderedDict\nimport argparse\n\ndef main():\n\n pd.set_option('display.max_columns', 500)\n\n # Args\n args = parse_args()\n\n # Load therapeutic areas dict\n ta_dict = load_therapeutic_area_labels(args.in_ta)\n\n # Load study info and explode efo column\n std = pd.read_json(args.in_study, orient='records', lines=True)\n std['trait_efos'] = std['trait_efos'].apply(\n lambda x: x if isinstance(x, list) else [None])\n std = explode(std, ['trait_efos'])\n \n # # DEBUG\n # std = std.head(100)\n\n # Get efo therapeutic areas\n efo_res = get_efo_therapeutic_areas_multi(\n efo_list=std['trait_efos'],\n ta_dict=ta_dict,\n order=True\n )\n\n # Write as json\n with open(args.output, 'w') as out_h:\n for efo, ta in efo_res.items():\n out_h.write(\n json.dumps(\n {'efo_term': efo,\n 'therapeutic_areas': ta}\n ) + '\\n'\n )\n\n return 0\n\ndef get_efo_therapeutic_areas_multi(efo_list, ta_dict, order=False):\n ''' For a list of efo terms, get a list of therapeutic areas\n params:\n efo (str): EFO short form code\n ta_dict (dict): Dictionary of therapeutic area EFO labels -> display labels\n order (bool): whether to order efo's by order in input file\n returns:\n dict of efo -> list of therapeutic areas\n '''\n d = {}\n efo_set = set([x for x in efo_list if isinstance(x, str)])\n # efo_set = set([x for x in efo_list])\n for i, efo in enumerate(set(efo_set)):\n if i % 10 == 0:\n print('Processed {} of {}...'.format(i, len(efo_set)))\n d[efo] = get_efo_therapeutic_areas(efo, ta_dict, order)\n return d\n\ndef get_efo_therapeutic_areas(efo, ta_dict, order=False):\n ''' For a single efo term, get a list of therapeutic areas\n params:\n efo (str): EFO short form code\n ta_dict (dict): Dictionary of therapeutic area EFO labels -> display labels\n order (bool): whether to order efo's by order in input file\n returns list of therapeutic area display labels\n '''\n ta_set = set([])\n\n # Get set of labels from ancestors\n for anc in get_efo_ancestor_terms(efo):\n if anc['label'] in ta_dict:\n ta_set.add(ta_dict[anc['label']])\n \n # Check if the efo term is a therapeutic area itself\n # This is only likely if we get to a root (phenotype, disease, measurement)\n if len(ta_set) < 2:\n efo_label = get_efo_label(efo)\n if efo_label in ta_dict:\n ta_set.add(ta_dict[efo_label])\n \n # Order labels same as input file\n if order:\n ta_list = sorted(ta_set, key=lambda x: list(ta_dict.values()).index(x))\n # Random order list\n else:\n ta_list = list(ta_set)\n \n return ta_list\n\ndef load_therapeutic_area_labels(inf):\n ''' Loads therapeutic labels and display labels\n '''\n d = OrderedDict()\n with open(inf, 'r') as in_h:\n in_h.readline() # skip header\n for line in in_h:\n\n if line.startswith('#'):\n continue\n \n try:\n category, term_label, display_label = line.rstrip().split('\\t')\n except ValueError:\n sys.exit('Error for in {}: {}'.format(inf, line))\n \n if term_label in d:\n sys.exit(\n 'Error: duplicate term_label in therapuetic'\n ' area list: {}'.format(term_label)\n )\n d[term_label] = display_label\n return d\n\ndef get_efo_ancestor_terms(efo):\n ''' Uses OLS API to get all ancestors for an efo term.\n Params:\n efo (str): efo short form code\n Returns:\n yields dicts of json respons for each ancestor term\n '''\n\n # Query OLS\n url = (\"http://www.ebi.ac.uk/ols/api/ontologies/efo/terms/\"\n \"http%253A%252F%252Fwww.ebi.ac.uk%252Fefo%252F{efo}/ancestors\")\n url = url.format(efo=efo.replace(':', '_'))\n # print(url)\n\n # Get first page\n page = query_rest(url)\n \n # Process data\n while True:\n \n # Stop if no terms\n try:\n page['_embedded']['terms']\n except KeyError:\n break\n\n # Iterate over ancestors\n for anc in page['_embedded']['terms']:\n yield anc\n\n # Get next page\n if 'next' in page['_links']:\n page = query_rest(page['_links']['next']['href'])\n else:\n break\n\ndef get_efo_label(code):\n ''' Gets the mapped trait name from the efo code from the OLS API\n '''\n # Get from API\n url = ('https://www.ebi.ac.uk/ols/api/'\n 'search?q={code}&queryFields=short_form')\n url = url.format(code=code)\n \n # Make query\n data = query_rest(url)\n\n # Extract label\n label = None\n for entry in data['response']['docs']:\n if entry['short_form'] == code:\n label = entry['label']\n break\n\n return label\n\ndef query_rest(url):\n ''' Queries rest api, checks response is ok and parases json\n '''\n try:\n resp = requests.get(url)\n except:\n sys.exit('Error fetching: {}'.format(url))\n\n # Check the response was ok\n if not (resp.ok):\n resp.raise_for_status()\n \n # Load the response data into a dict variable\n data = json.loads(resp.content.decode('utf-8'))\n\n return data\n\ndef explode(df, columns):\n ''' Explodes multiple columns\n '''\n idx = np.repeat(df.index, df[columns[0]].str.len())\n a = df.T.reindex(columns).values\n concat = np.concatenate([np.concatenate(a[i]) for i in range(a.shape[0])])\n p = pd.DataFrame(concat.reshape(a.shape[0], -1).T, idx, columns)\n return pd.concat([df.drop(columns, axis=1), p], axis=1).reset_index(drop=True)\n\ndef parse_args():\n \"\"\" Load command line args \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--in_study', metavar=\"<str>\", type=str, required=True)\n parser.add_argument('--in_ta', metavar=\"<str>\", type=str, required=True)\n parser.add_argument('--output', metavar=\"<str>\", help=(\"Output\"), type=str, required=True)\n args = parser.parse_args()\n return args\n\nif __name__ == '__main__':\n\n main()\n"
},
{
"alpha_fraction": 0.5794183611869812,
"alphanum_fraction": 0.5902844071388245,
"avg_line_length": 31.59375,
"blob_id": "339ccea139530354e736e17c6ed583606dfe022d",
"content_id": "83ba59cebd8ce7a4fb6f198a917406f262266c83",
"detected_licenses": [
"Apache-2.0"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3129,
"license_type": "permissive",
"max_line_length": 101,
"num_lines": 96,
"path": "/scripts/process_nealeUKB_efo_curations.py",
"repo_name": "thehyve/v2d_data",
"src_encoding": "UTF-8",
"text": "#!/usr/bin/env python\n# -*- coding: utf-8 -*-\n#\n# Ed Mountjoy\n#\n\nimport sys\nimport os\nimport argparse\nimport pandas as pd\nfrom pprint import pprint\nimport numpy as np\nimport requests\nimport json\n\ndef main():\n\n # Parse args\n args = parse_args()\n\n # Load ICD10 curation\n icd10 = pd.read_csv(args.in_icd10, sep=',', header=0)\n icd10 = ( icd10.loc[icd10['Confidence (High/Medium/Low/None)'].isin(['High']), :]\n .loc[:, ['Field.code', 'Manual curation']]\n .rename(columns={'Field.code': 'trait_code',\n 'Manual curation': 'efo_code'}) )\n # Split\n icd10['efo_code'] = icd10['efo_code'].astype(str).str.split('\\|\\|')\n icd10 = explode(icd10, ['efo_code'])\n\n # Load self-reported curation\n selfrep = pd.read_csv(args.in_self, sep=',', header=0)\n selfrep = ( selfrep.loc[selfrep['Confidence (High/Medium/Low/None)'].isin(['High', 'Medium']), :]\n .loc[:, ['Field.code', 'Manual curation']]\n .rename(columns={'Field.code': 'trait_code',\n 'Manual curation': 'efo_code'}) )\n # Split\n selfrep['efo_code'] = selfrep['efo_code'].astype(str).str.split('\\|\\|')\n selfrep = explode(selfrep, ['efo_code'])\n\n # Combine\n merge = pd.concat([icd10, selfrep])\n merge['efo_code'] = merge['efo_code'].str.replace(':', '_')\n\n # Get labels for EFO codes\n print('Getting EFO labels from OLS API...')\n merge['efo_trait'] = merge['efo_code'].apply(get_efo_label)\n\n # Write\n merge.to_csv(args.outf, sep='\\t', index=None)\n\ndef get_efo_label(code):\n ''' Gets the mapped trait name from the efo code from the OLS API\n '''\n # Get from API\n url = 'https://www.ebi.ac.uk/ols/api/search?q={code}&queryFields=short_form'.format(code=code)\n resp = requests.get(url)\n # Check the response was ok\n if not (resp.ok):\n resp.raise_for_status()\n # Load the response data into a dict variable\n data = json.loads(resp.content.decode('utf-8'))\n\n # Extract label\n label = None\n for entry in data['response']['docs']:\n if entry['short_form'] == code:\n label = entry['label']\n break\n\n return label\n\ndef combine_rows(items):\n return ';'.join(items)\n\ndef explode(df, columns):\n ''' Explodes multiple columns\n '''\n idx = np.repeat(df.index, df[columns[0]].str.len())\n a = df.T.reindex(columns).values\n concat = np.concatenate([np.concatenate(a[i]) for i in range(a.shape[0])])\n p = pd.DataFrame(concat.reshape(a.shape[0], -1).T, idx, columns)\n return pd.concat([df.drop(columns, axis=1), p], axis=1).reset_index(drop=True)\n\ndef parse_args():\n \"\"\" Load command line args \"\"\"\n parser = argparse.ArgumentParser()\n parser.add_argument('--in_icd10', metavar=\"<str>\", help=(\"Input\"), type=str, required=True)\n parser.add_argument('--in_self', metavar=\"<str>\", help=(\"Input\"), type=str, required=True)\n parser.add_argument('--outf', metavar=\"<str>\", help=(\"Output\"), type=str, required=True)\n args = parser.parse_args()\n return args\n\nif __name__ == '__main__':\n\n main()\n"
}
] | 9 |
mleimeister/kaggle-chars74k | https://github.com/mleimeister/kaggle-chars74k | 6b49ad3b83d0d1e42c6b0a945435d2494e2ea341 | 6d651b0da887f49279f5c4f2ef7e02779e36d7e6 | 16f99a3c43f849631990addd2c9b029848411095 | refs/heads/master | 2021-01-17T11:48:14.857055 | 2016-07-24T11:10:31 | 2016-07-24T11:10:31 | 37,416,330 | 0 | 3 | null | null | null | null | null | [
{
"alpha_fraction": 0.6242496967315674,
"alphanum_fraction": 0.6410564184188843,
"avg_line_length": 20.28205108642578,
"blob_id": "f768d69b1f5035a9c6676d29544ffedca076acec",
"content_id": "8c6cf24c10a126d7d001c3fe04d870ff31d82cc5",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 833,
"license_type": "no_license",
"max_line_length": 78,
"num_lines": 39,
"path": "/gen_test.py",
"repo_name": "mleimeister/kaggle-chars74k",
"src_encoding": "UTF-8",
"text": "\"\"\"\nGenerate test images by converting to gray scale and resizing to 56x56 pixels.\n\"\"\"\n\nimport os\nimport sys\nimport csv\n\nif len(sys.argv) < 2:\n print \"Usage: python gen_test.py input_folder output_folder\"\n exit(1)\n\nfi = sys.argv[1]\nfo = sys.argv[2]\n\ncmd = \"convert -colorspace gray -resize 56x56\\! \"\n\nimg_lst = []\n\nimgs = os.listdir(fi)\n\n# resize original images\nprint \"Resizing images\"\nfor img in imgs:\n basename = os.path.basename(img)\n filename = os.path.splitext(basename)\n img_without_ext = filename[0]\n outFileName = str(img_without_ext) + \".jpg\"\n md = \"\"\n md += cmd\n md += fi + str(img)\n md += \" \" + fo + outFileName\n img_lst.append((outFileName, 0))\n os.system(md)\n\n\nfo = csv.writer(open(\"test.lst\", \"w\"), delimiter='\\t', lineterminator='\\n')\nfor item in img_lst:\n fo.writerow(item)\n\n\n\n"
},
{
"alpha_fraction": 0.6801393628120422,
"alphanum_fraction": 0.7045296430587769,
"avg_line_length": 32.16279220581055,
"blob_id": "2d6ed3d4b3e85c062266b854a2a8362f09e00fe0",
"content_id": "48095a3eb4e92fe478d8dc3a2647923d09cbedbb",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1435,
"license_type": "no_license",
"max_line_length": 101,
"num_lines": 43,
"path": "/make_submission.py",
"repo_name": "mleimeister/kaggle-chars74k",
"src_encoding": "UTF-8",
"text": "\"\"\"\nRun pretrained Caffe model to predict character classes and store results in a submission file.\n\"\"\"\n\nimport csv\nimport os\nimport numpy as np\nfrom sklearn import preprocessing\nimport pandas as pd\nimport caffe\n\nfc = pd.read_csv('/home/matthias/kaggle/chars74k/data/trainLabels.csv')\n\nlabels = fc.Class.values\nlbl_enc = preprocessing.LabelEncoder()\nlabels = lbl_enc.fit_transform(labels)\n\n\nmean_image = np.load('/home/matthias/kaggle/chars74k/mean.npy')\nprint np.shape(mean_image)\nmean_image = mean_image[:, 4:52, 4:52]\nprint np.shape(mean_image)\nmean_image = np.reshape(mean_image, (1, 48, 48))\n\nnet = caffe.Classifier('/home/matthias/kaggle/chars74k/networks/vgg_test.prototxt',\n '/home/matthias/kaggle/chars74k/models/vgg_train_valid_iter_20000.caffemodel',\n image_dims=(56, 56), raw_scale=255, mean=mean_image)\n\ncaffe.set_mode_gpu()\n\nimgs = os.listdir('/home/matthias/kaggle/chars74k/data/testAugmented/')\nfo = csv.writer(open('out.csv', \"w\"), lineterminator='\\n')\n\nfo.writerow(['ID', 'Class'])\n\nfor i, img in enumerate(imgs):\n print str(i)\n im = caffe.io.load_image('/home/matthias/kaggle/chars74k/data/testAugmented/' + img, color=False)\n scores = net.predict([im], oversample=True)\n predLabel = np.argmax(scores)\n predClass = lbl_enc.inverse_transform(predLabel)\n fileName, fileExtension = os.path.splitext(img)\n fo.writerow([str(fileName), predClass])\n\n\n\n \n\n"
},
{
"alpha_fraction": 0.5892751812934875,
"alphanum_fraction": 0.5998821258544922,
"avg_line_length": 25.920635223388672,
"blob_id": "4f414fcce97a64de19a44512e94e4c82181667a1",
"content_id": "286f0e086c84caa68c2209b8f4f7a0aa65df39a6",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1697,
"license_type": "no_license",
"max_line_length": 88,
"num_lines": 63,
"path": "/gen_img_list.py",
"repo_name": "mleimeister/kaggle-chars74k",
"src_encoding": "UTF-8",
"text": "\"\"\"\nGenerates text files that contain the filenames for training and test sets.\n\"\"\"\n\nimport csv\nimport os\nimport sys\nimport random\n\nif len(sys.argv) < 4:\n print \"Usage: gen_img_list.py train/test sample_submission.csv folder\"\n exit(1)\n\nrandom.seed(888)\n\ntask = sys.argv[1]\t\t\t# train or test (train has subfolders for classes)\nfc = csv.reader(file(sys.argv[2]))\t# csv containing class list in first column\nfi = sys.argv[3]\t\t\t# path to folder containing class subfolders (train) or images (test)\n\n# make class map (will be used to read subfolders)\nhead = fc.next()\nhead = head[1:]\n\n# make image list\nimg_lst = []\ncnt = 0\nif task == \"train\":\n for i in xrange(len(head)):\n path = fi + head[i]\n lst = os.listdir(fi + head[i])\n for img in lst:\n img_lst.append((head[i] + '/' + img, i))\n # img_lst.append((cnt, i, path + '/' + img))\n # cnt += 1\nelse:\n lst = os.listdir(fi)\n for img in lst:\n img_lst.append((img, 0))\n # img_lst.append((cnt, 0, fi + img))\n # cnt += 1\n\n# shuffle\nif task == \"train\":\n random.shuffle(img_lst)\n\n# in training, 10% of the data are used for validation\nif task == \"train\":\n val_index = int(0.9 * len(img_lst))\n val_lst = img_lst[val_index:]\n img_lst = img_lst[:val_index]\n\n fo = csv.writer(open(\"train.lst\", \"w\"), delimiter='\\t', lineterminator='\\n')\n for item in img_lst:\n fo.writerow(item)\n\n fo = csv.writer(open(\"valid.lst\", \"w\"), delimiter='\\t', lineterminator='\\n')\n for item in val_lst:\n fo.writerow(item)\n\nelse:\n fo = csv.writer(open(\"test.lst\", \"w\"), delimiter='\\t', lineterminator='\\n')\n for item in img_lst:\n fo.writerow(item)\n\n"
},
{
"alpha_fraction": 0.5917137265205383,
"alphanum_fraction": 0.6092278957366943,
"avg_line_length": 31.765432357788086,
"blob_id": "dcfb98b022aa895e67c773630316d87b490297f7",
"content_id": "6a4fa7a31c03d1fa84edfc5f8f5198c69db8b8ba",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 5310,
"license_type": "no_license",
"max_line_length": 150,
"num_lines": 162,
"path": "/gen_train.py",
"repo_name": "mleimeister/kaggle-chars74k",
"src_encoding": "UTF-8",
"text": "\"\"\"\nCreate training and validation images by converting to gray scale, resizing to 56x56 pixels and applying\ndata augmentation by random scaling and shearing.\n\"\"\"\n\nimport os\nimport sys\nimport csv\nimport random\nimport numpy as np\nimport pandas as pd\nfrom sklearn import preprocessing\n\nrandom.seed(0)\nnp.random.seed(0)\n\nif len(sys.argv) < 3:\n print \"Usage: python gen_train.py input_folder output_folder label_file\"\n exit(1)\n\nfi = sys.argv[1]\nfo = sys.argv[2]\nfc = pd.read_csv(sys.argv[3])\n\nlabels = fc.Class.values\nlbl_enc = preprocessing.LabelEncoder()\nlabels = lbl_enc.fit_transform(labels)\nimgs = fc.ID.values\n\np = np.random.permutation(len(imgs))\nimgs = imgs[p]\nlabels = labels[p]\n\nval_index = int(0.9 * len(imgs))\nval_imgs = imgs[val_index:]\nval_labels = labels[val_index:]\n\nimgs = imgs[:val_index]\nlabels = labels[:val_index]\n\ncmd = \"convert -colorspace gray -resize 56x56\\! \"\n\nimg_lst = []\n\n# resize original images\nprint \"Resizing training images\"\nfor i, img in enumerate(imgs):\n outFileName = str(img) + \".jpg\"\n outLabel = labels[i]\n md = \"\"\n md += cmd\n md += fi + str(img) + \".Bmp\"\n md += \" \" + fo + outFileName\n img_lst.append((outFileName, outLabel))\n os.system(md)\n\nprint \"Inverting training images\"\nfor i, img in enumerate(imgs):\n outFileName = str(img) + \"_inverted.jpg\"\n outLabel = labels[i]\n md = \"\"\n md += cmd\n md += \" -negate \"\n md += fi + str(img) + \".Bmp\"\n md += \" \" + fo + outFileName\n img_lst.append((outFileName, outLabel))\n os.system(md)\n\nprint \"Creating scaled training images\"\nfor i, img in enumerate(imgs):\n for nRep in range(3):\n scale_factor = random.randint(44, 68)\n outFileName = str(img) + \"_scaled_\" + str(scale_factor) + \".jpg\"\n outLabel = labels[i]\n md = \"convert -colorspace gray -resize \" + str(scale_factor) + \"x\" + str(scale_factor) + \"\\! -gravity center -background white -extent 56x56 \"\n md += \" -gravity center -crop 56x56+0+0 +repage \"\n md += fi + str(img) + \".Bmp\"\n md += \" \" + fo + outFileName\n img_lst.append((outFileName, outLabel))\n os.system(md)\n\nprint \"Creating scaled sheared training images\"\nfor i, img in enumerate(imgs):\n for nRep in range(3):\n scale_factor = random.randint(58, 70)\n shear_x = random.randint(-15, 15)\n shear_y = random.randint(-15, 15)\n outFileName = str(img) + \"_scaled_\" + str(scale_factor) + \"_\" + str(shear_x) + \"x\" + str(shear_y) + \"shear.jpg\"\n outLabel = labels[i]\n md = \"convert -colorspace gray -resize \" + str(scale_factor) + \"x\" + str(scale_factor) + \"\\! -gravity center -background white -extent 56x56 \"\n md += \"-shear \" + str(shear_x) + \"x\" + str(shear_y)\n md += \" -gravity center -crop 56x56+0+0 +repage \"\n md += fi + str(img) + \".Bmp\"\n md += \" \" + fo + outFileName\n img_lst.append((outFileName, outLabel))\n os.system(md)\n\nrandom.shuffle(img_lst)\n\ntrain_list_writer = csv.writer(open(\"train.lst\", \"w\"), delimiter='\\t', lineterminator='\\n')\nfor item in img_lst:\n train_list_writer.writerow(item)\n\nval_lst = []\n\n# resize original images\nprint \"Resizing validation images\"\nfor i, img in enumerate(val_imgs):\n outFileName = str(img) + \".jpg\"\n outLabel = val_labels[i]\n md = \"\"\n md += cmd\n md += fi + str(img) + \".Bmp\"\n md += \" \" + fo + outFileName\n val_lst.append((outFileName, outLabel))\n os.system(md)\n\nprint \"Inverting validation images\"\nfor i, img in enumerate(val_imgs):\n outFileName = str(img) + \"_inverted.jpg\"\n outLabel = val_labels[i]\n md = \"\"\n md += cmd\n md += \" -negate \"\n md += fi + str(img) + \".Bmp\"\n md += \" \" + fo + outFileName\n val_lst.append((outFileName, outLabel))\n os.system(md)\n\nprint \"Creating scaled validation images\"\nfor i, img in enumerate(val_imgs):\n for nRep in range(3):\n scale_factor = random.randint(44, 68)\n outFileName = str(img) + \"_scaled_\" + str(scale_factor) + \".jpg\"\n outLabel = val_labels[i]\n md = \"convert -colorspace gray -resize \" + str(scale_factor) + \"x\" + str(scale_factor) + \"\\! -gravity center -background white -extent 56x56 \"\n md += \" -gravity center -crop 56x56+0+0 +repage \"\n md += fi + str(img) + \".Bmp\"\n md += \" \" + fo + outFileName\n val_lst.append((outFileName, outLabel))\n os.system(md)\n\nprint \"Creating scaled sheared validation images\"\nfor i, img in enumerate(val_imgs):\n for nRep in range(3):\n scale_factor = random.randint(58, 70)\n shear_x = random.randint(-15, 15)\n shear_y = random.randint(-15, 15)\n outFileName = str(img) + \"_scaled_\" + str(scale_factor) + \"_\" + str(shear_x) + \"x\" + str(shear_y) + \"shear.jpg\"\n outLabel = val_labels[i]\n md = \"convert -colorspace gray -resize \" + str(scale_factor) + \"x\" + str(scale_factor) + \"\\! -gravity center -background white -extent 56x56 \"\n md += \"-shear \" + str(shear_x) + \"x\" + str(shear_y)\n md += \" -gravity center -crop 56x56+0+0 +repage \"\n md += fi + str(img) + \".Bmp\"\n md += \" \" + fo + outFileName\n val_lst.append((outFileName, outLabel))\n os.system(md)\n\n\nval_list_writer = csv.writer(open(\"valid.lst\", \"w\"), delimiter='\\t', lineterminator='\\n')\nfor item in val_lst:\n val_list_writer.writerow(item)\n\n\n"
},
{
"alpha_fraction": 0.5839191675186157,
"alphanum_fraction": 0.6467486619949341,
"avg_line_length": 34.5625,
"blob_id": "1a8865a4a8f022817831b633781bbea5cdd888e7",
"content_id": "9fba1bf08acfb5bcd35d06fe40ad1a48d3d803fd",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 2276,
"license_type": "no_license",
"max_line_length": 299,
"num_lines": 64,
"path": "/README.md",
"repo_name": "mleimeister/kaggle-chars74k",
"src_encoding": "UTF-8",
"text": "# Kaggle Chars74k\n\nCode for producing a submission for the Kaggle challenge [First steps with Julia](https://www.kaggle.com/c/street-view-getting-started-with-julia). The Chars74k dataset contains images from Google Streetview of 64 characters. The below network achieves an accuracy of 0.76014 on the public test set.\n\n\n\nModel architecture\n------------------\n\n| Layer | Type \t\t\t\t|\n|:-----:|:-------------------------:\t\t|\n| Input | 48x48 \t\t\t\t|\n| 1 | conv 3x3, 128, leaky relu (0.01) \t|\n| 2 | conv 3x3, 128, leaky relu (0.01) |\n| | max 2x2/2, dropout 0.25\t\t\t| \n| 3 | conv 3x3, 128, relu \t\t\t|\n| 4 | conv 3x3, 128, relu \t\t\t|\n| | max 2x2/2, LR normalization\t\t|\n| 5 | conv 3x3, 128, leaky relu (0.01) |\n| 6 | conv 3x3, 128, leaky relu (0.01) |\n| | max 2x2/2, LR normalization\t\t|\n| 7 | conv 3x3, 128, leaky relu (0.01) |\n| 8 | fc 2048, leaky relu (0.01) \t\t|\n| | droput 0.5 \t\t\t\t\t\t|\n| 10 | fc 2048, leaky relu (0.01) \t\t|\n| | dropout 0.5 \t\t\t\t\t\t|\n| 11 | fc 62, softmax \t\t\t\t|\n\n\nRunning training\n----------------\n\nCreate augmented data from original images\n```\npython gen_train.py ./data/train/ ./data/trainAugmented/ ./data/trainLabels.csv\npython gen_test.py ./data/test/ ./data/testAugmented/\n```\n \nCreate database files\n``` \nrm -r ~/kaggle/chars74k/train_leveldb/\nrm -r ~/kaggle/chars74k/valid_leveldb/\n\ncd ~/caffe/build/tools\n\n./convert_imageset -gray -backend leveldb ~/kaggle/chars74k/data/trainAugmented/ ~/kaggle/chars74k/train.lst ~/kaggle/chars74k/train_leveldb\n./convert_imageset -gray -backend leveldb ~/kaggle/chars74k/data/trainAugmented/ ~/kaggle/chars74k/valid.lst ~/kaggle/chars74k/valid_leveldb\n```\n\nCompute mean image from training set\n```\n./compute_image_mean ~/kaggle/chars74k/train_leveldb ~/kaggle/chars74k/mean.binaryproto -backend leveldb`\n```\n\nRun CNN training\n```\n./caffe train --solver=/home/matthias/kaggle/chars74k/networks/vgg_solver.prototxt\n```\n\nMake submission\n```\ncd ~/kaggle/chars74k\npython make_submission.py ~/kaggle/chars74k/data/sampleSubmission.csv test.lst out.csv\n```\n"
}
] | 5 |
Ceachi/Python-Repository | https://github.com/Ceachi/Python-Repository | 852e99677de18582fa80be1e39d24e0d2281a841 | aa4e59c7552fb43a2cb7f67c2921bfa526c679f4 | fd7e59cf200ac30d79372c91411a0f9f9abbc95a | refs/heads/master | 2021-07-22T05:02:29.968832 | 2019-12-30T09:48:36 | 2019-12-30T09:48:36 | 194,269,599 | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6591304540634155,
"alphanum_fraction": 0.7043478488922119,
"avg_line_length": 27.75,
"blob_id": "5cc52774648a595540fa2bbb412fb231cd35030b",
"content_id": "e117d2cf65eced06c693a6c327613e3e3779e36a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 575,
"license_type": "no_license",
"max_line_length": 94,
"num_lines": 20,
"path": "/Tensorflow-Tutorial-master/README.md",
"repo_name": "Ceachi/Python-Repository",
"src_encoding": "UTF-8",
"text": "# Tensorflow-Tutorial\n\n\n\n* Tensorflow basic: \n * [Session](11_session.py)\n * [Placeholder](12_placeholder.py)\n * [Variable](13_variable.py)\n * [Activation](14_activation.py)\n \n* Build your first network:\n * [Regression](21_regression.py)\n * [Classification](22_classification.py)\n * [Save and reload processes](23_save_reload.py)\n * [Optimizer](24_optimizer.py)\n * [TensorBoard](25_tensorboard.py)\n * [Dataset](26_dataset.py)\n\n* Standford:\n [CS231n: Convolutional Neural Networks for Visual Recognition] (http://cs231n.stanford.edu/)\n"
},
{
"alpha_fraction": 0.7067806720733643,
"alphanum_fraction": 0.778863787651062,
"avg_line_length": 84.15789794921875,
"blob_id": "34e5844fd02198500860d2f9a212ebad23b6d982",
"content_id": "4af0ec20748087e931e7cad2688c5210dd124882",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1637,
"license_type": "no_license",
"max_line_length": 210,
"num_lines": 19,
"path": "/Python basic/README.md",
"repo_name": "Ceachi/Python-Repository",
"src_encoding": "UTF-8",
"text": "# Python-Fundamentals\r\n\r\n\r\n\r\n * [Lecture 1 - Variables](https://github.com/Ceachi/Python-Repository/tree/master/Python%20basic/Python-Fundamentals/Lecture%201%20-%20Variables)\r\n * [Lecture 2 - Loops, if](https://github.com/Ceachi/Python-Repository/tree/master/Python%20basic/Python-Fundamentals/Lecture%202%20-%20Loops%2C%20if)\r\n * [Lecture 3 - Other types of data](https://github.com/Ceachi/Python-Repository/tree/master/Python%20basic/Python-Fundamentals/Lecture%203%20-%20Other%20types%20of%20data)\r\n * [Lecture 4 - Files, Exception](https://github.com/Ceachi/Python-Repository/tree/master/Python%20basic/Python-Fundamentals/Lecture%204%20-%20Files%2C%20Exception)\r\n * [Lecture 5 - POO](https://github.com/Ceachi/Python-Repository/tree/master/Python%20basic/Python-Fundamentals/Lecture%205%20-%20POO)\r\n * [Lecture 6 - Python Modules](https://github.com/Ceachi/Python-Repository/tree/master/Python%20basic/Python-Fundamentals/Lecture%206%20-%20Python%20Modules)\r\n * [Lecture 7 - Advanced Modules in Python](https://github.com/Ceachi/Python-Repository/tree/master/Python%20basic/Python-Fundamentals/Lecture%207%20-%20Advanced%20Modules%20in%20Python)\r\n * [Lecture 8 - Advanced Modules in Python ( part-2)](https://github.com/Ceachi/Python-Repository/tree/master/Python%20basic/Python-Fundamentals/Lecture%208%20-%20Advanced%20Modules%20in%20Python%20(%20part-2))\r\n\r\n\r\n* Interprocess communication: \r\n * [Communication using sockets](https://github.com/Ceachi/Python-Repository/tree/master/Python%20basic/Communication%20using%20sockets)\r\n \r\n# Other references:\r\n* https://www.bogotobogo.com/python/pytut.php\r\n"
},
{
"alpha_fraction": 0.49546828866004944,
"alphanum_fraction": 0.49546828866004944,
"avg_line_length": 14.809523582458496,
"blob_id": "45b1ce8ebec51bd9b6ed9a2c808b8742df437cc7",
"content_id": "4aca14858f2a4dd64b85603a12ac2753c6e84325",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 331,
"license_type": "no_license",
"max_line_length": 38,
"num_lines": 21,
"path": "/Python basic/Python-Fundamentals/Lecture 4 - Files, Exception/words.py",
"repo_name": "Ceachi/Python-Repository",
"src_encoding": "UTF-8",
"text": "def fetch_words():\n\n with open('t.txt') as file:\n\n file_words = []\n\n for line in file:\n\n line_words = line.split()\n\n for word in line_words:\n\n file_words.append(word)\n\n for word in file_words:\n\n print(word)\n \nprint(__name__)\nif __name__ == '__name__':\n fetch_words()"
}
] | 3 |
sanyaade-research-hub/qibuild | https://github.com/sanyaade-research-hub/qibuild | 7c4e0421bffced992efcd2a978529cf671e18ed1 | fc1b9fbe571ef0e96f5d6f2ac253f64e7dfd6c1f | a89dec5231d06b2c19832676f814dfd1d2f93fa5 | refs/heads/master | 2021-01-16T00:12:18.992855 | 2012-08-21T16:33:18 | 2012-08-21T16:37:10 | null | 0 | 0 | null | null | null | null | null | [
{
"alpha_fraction": 0.6076443195343018,
"alphanum_fraction": 0.6232449412345886,
"avg_line_length": 27.488889694213867,
"blob_id": "1b7423806c65032bdb2170a384a091f54c2fba5e",
"content_id": "1be9cf3e521c8ca5ca12ca4e736076f2b9cbbf2d",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Makefile",
"length_bytes": 1282,
"license_type": "permissive",
"max_line_length": 81,
"num_lines": 45,
"path": "/python/Makefile",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "##\n## Author(s):\n## - Cedric GESTES <[email protected]>\n##\n## Copyright (C) 2009, 2010, 2012 Aldebaran Robotics\n##\n\nTEST_MODULES =\nifneq ($(MYPYMODULES),)\nPYMODULES = $(MYPYMODULES)\nTEST_MODULES:= $(foreach module,$(MYPYMODULES),\\\n\t$(shell dirname $(module))/test/test_$(shell basename $(module)).py)\nTEST_MODULES:= $(foreach test,$(TEST_MODULES),\\\n\t$(filter $(test),$(wildcard $(shell dirname $(test))/*)))\nendif\n\nPYMODULES ?= qibuild qitoolchain qisrc qixml qidoc \\\n\tbin/qibuild \\\n\tbin/qisrc \\\n\tbin/qitoolchain\n\nPYTHON ?= python\n\nall: check-error check\n\ncheck-all:\n\t@echo \":: Running pylint check-all: $(PYMODULES)\"\n\t@pylint -f colorized --rcfile pylint.rc $(PYMODULES) --ignore=external 2>&1 || \\\n\t\texit 1 || exit 0\n\ncheck-error:\n\t@echo \":: Running pylint --errors-only: $(PYMODULES)\"\n\t@pylint --include-ids=y -f colorized --errors-only --rcfile pylint.rc \\\n\t\t$(PYMODULES) --ignore=external 2>&1 || \\\n\t\texit 1 || exit 0\n\t@echo \" => Checked only for pylint errors\"\n\t@echo \" Use make check-all for running a full pylint check\"\n\ncheck:\n\t@echo \":: Running tests: $(TEST_MODULES)\"\n\t@$(PYTHON) -m pytest $(TEST_MODULES)\n\ncheck-fast:\n\t@echo \":: Runnig fasts tests: $(TEST_MODULES)\"\n\t@$(PYTHON) -m pytest -k -slow $(TEST_MODULES)\n"
},
{
"alpha_fraction": 0.6120907068252563,
"alphanum_fraction": 0.615113377571106,
"avg_line_length": 37.92156982421875,
"blob_id": "3a16b62dda5e0cc5d2cf4f67f74db7ee60bc3fa5",
"content_id": "5818d83479ac894fdc4142f6d97cc4d0924222fd",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1985,
"license_type": "permissive",
"max_line_length": 80,
"num_lines": 51,
"path": "/python/qibuild/actions/make.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\n\"\"\"Build a project\n\n\"\"\"\n\nfrom qibuild import ui\nimport qibuild\nimport qibuild.cmdparse\n\ndef configure_parser(parser):\n \"\"\"Configure parser for this action\"\"\"\n qibuild.parsers.toc_parser(parser)\n qibuild.parsers.build_parser(parser)\n qibuild.parsers.project_parser(parser)\n group = parser.add_argument_group(\"make options\")\n group.add_argument(\"-t\", \"--target\", help=\"Special target to build\")\n group.add_argument(\"--rebuild\", \"-r\", action=\"store_true\", default=False)\n group.add_argument(\"--no-fix-shared-libs\", action=\"store_false\",\n dest=\"fix_shared_libs\",\n help=\"Do not try to fix shared libraries after build. \"\n \"Used by `qibuild package`\")\n\ndef do(args):\n \"\"\"Main entry point\"\"\"\n toc = qibuild.toc.toc_open(args.worktree, args)\n\n (project_names, _package_names, _not_found) = toc.resolve_deps()\n use_incredibuild = toc.config.build.incredibuild\n\n ui.info(ui.green, \"Current worktree:\", ui.reset, ui.bold, toc.worktree.root)\n if toc.active_config:\n ui.info(ui.green, \"Active configuration: \",\n ui.blue, \"%s (%s)\" % (toc.active_config, toc.build_type))\n projects = [toc.get_project(name) for name in project_names]\n\n project_count = len(projects)\n i = 0\n for project in projects:\n i += 1\n if args.target:\n mess = \"Building target %s for\" % args.target\n else:\n mess = \"Building\"\n ui.info(ui.green, \"*\", ui.reset, \"(%i/%i)\" % (i, project_count),\n ui.green, mess, ui.blue, project.name)\n toc.build_project(project, target=args.target, num_jobs=args.num_jobs,\n incredibuild=use_incredibuild, rebuild=args.rebuild,\n fix_shared_libs=args.fix_shared_libs)\n"
},
{
"alpha_fraction": 0.6049334406852722,
"alphanum_fraction": 0.6068911552429199,
"avg_line_length": 28.022727966308594,
"blob_id": "1c8a4c1b7f070b4a8335ff3789efb922a4b6c011",
"content_id": "5c8370210670876a7c9f8bfe3d6bdd4ae40ddd29",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2554,
"license_type": "permissive",
"max_line_length": 73,
"num_lines": 88,
"path": "/python/qidoc/config.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\n\"\"\" Handling qidoc config files\n\n\"\"\"\n\nimport qixml\nfrom xml.etree import ElementTree as etree\n\nclass Depends:\n def __init__(self):\n self.name = None\n\n def parse(self, element):\n self.name = element.get(\"name\")\n\nclass SphinxDoc:\n def __init__(self):\n self.name = None\n self.src = None\n self.dest = None\n self.depends = list()\n\n def parse(self, element):\n self.name = qixml.parse_required_attr(element, \"name\")\n self.src = element.get(\"src\", \".\")\n self.dest = element.get(\"dest\", self.name)\n depends_elements = element.findall(\"depends\")\n for depends_element in depends_elements:\n depends = Depends()\n depends.parse(depends_element)\n self.depends.append(depends.name)\n\nclass DoxyDoc:\n def __init__(self):\n self.name = None\n self.src = None\n self.dest = None\n self.depends = list()\n\n def parse(self, element):\n self.name = qixml.parse_required_attr(element, \"name\")\n self.src = element.get(\"src\", \".\")\n self.dest = element.get(\"dest\", self.name)\n depends_elements = element.findall(\"depends\")\n for depends_element in depends_elements:\n depends = Depends()\n depends.parse(depends_element)\n self.depends.append(depends.name)\n\n\ndef parse_project_config(config_path):\n \"\"\" Parse a config file, returns a tuple\n of lists (SphinxDoc, DoxyDoc)\n\n \"\"\"\n tree = etree.ElementTree()\n try:\n tree.parse(config_path)\n except Exception, e:\n mess = \"Could not parse config from %s\\n\" % config_path\n mess += \"Error was: %s\" % e\n raise Exception(mess)\n root = tree.getroot()\n doxydocs = list()\n doxy_trees = root.findall(\"doxydoc\")\n for doxy_tree in doxy_trees:\n doxydoc = DoxyDoc()\n doxydoc.parse(doxy_tree)\n doxydocs.append(doxydoc)\n sphinxdocs = list()\n sphinx_trees = root.findall(\"sphinxdoc\")\n for sphinx_tree in sphinx_trees:\n sphinxdoc = SphinxDoc()\n sphinxdoc.parse(sphinx_tree)\n sphinxdocs.append(sphinxdoc)\n return (doxydocs, sphinxdocs)\n\ndef is_template(qiproj_xml):\n \"\"\" Check whether a project is a template repo\n\n \"\"\"\n tree = etree.ElementTree()\n tree.parse(qiproj_xml)\n root = tree.getroot()\n return root.get(\"template_repo\", \"\") in [\"true\", \"1\"]\n"
},
{
"alpha_fraction": 0.5791658163070679,
"alphanum_fraction": 0.583264172077179,
"avg_line_length": 35.30131912231445,
"blob_id": "288c7240665dcaed4ff43a0bca2877f1099a828f",
"content_id": "8760775d0875e732172694ae54bc8d5f489e3b9f",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 19276,
"license_type": "permissive",
"max_line_length": 90,
"num_lines": 531,
"path": "/python/qibuild/cmake/modules.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\n\"\"\"This module contains helpers for generating, checking CMake modules.\n\n\"\"\"\n\nimport os\nimport re\nimport sys\n\nimport qibuild\n\n\ndef _find_path_best_matches(path_list, filename_regex):\n \"\"\"Return the list of path whose their basename match the given regular\n expression.\n\n \"\"\"\n matches = list()\n if path_list is None or len(path_list) == 0:\n return matches\n regex = r\"(\" + \"|\".join(filename_regex) + \")\"\n regex = re.compile(regex, re.IGNORECASE)\n # pep8-ignore: E501\n matches = [item for item in path_list if regex.search(os.path.basename(item))]\n matches.sort()\n return matches\n\n\ndef _find_headers(path_list):\n \"\"\"Return the list of headers found in the given path list.\n\n \"\"\"\n extensions = [\"\\.h$\", \"\\.hh$\", \"\\.hpp$\"]\n hdrs = _find_path_best_matches(path_list, extensions)\n return hdrs\n\n\ndef _get_header_relative_path(header):\n \"\"\"Return the header path from the include directory\n\n \"\"\"\n prefix = r\".*?\" + os.sep + \"?include\" + os.sep\n hdr_path = re.sub(prefix, \"\", header)\n return hdr_path\n\n\ndef _find_libraries(path_list, platform=None):\n \"\"\"Return the list of libraries found in the given path list.\n\n \"\"\"\n extensions = None\n if platform is None:\n platform = sys.platform\n if platform.startswith(\"linux\"):\n extensions = [\"\\.a\", \"\\.so\"]\n elif platform.startswith(\"darwin\"):\n extensions = [\"\\.a\", \"\\.dylib\"]\n elif platform.startswith(\"win\"):\n extensions = [\"\\.lib\", \"\\.dll\"]\n else:\n mess = \"Unsupported platform\"\n raise Exception(mess)\n regex = r\"(\" + \"|\".join(extensions) + \")$\"\n libs = _find_path_best_matches(path_list, [regex])\n libs_ = dict()\n for lib in libs:\n key = re.sub(regex, \"\", lib)\n if not key in libs_.keys():\n libs_[key] = list()\n libs_[key].append(lib)\n return libs_.values()\n\n\ndef _get_library_name(library):\n \"\"\"Return the library name for the library file path\n\n \"\"\"\n lib_name = os.path.basename(library)\n lib_name = lib_name.rsplit('.', 1)[0]\n lib_name = re.sub(\"^lib\", \"\", lib_name)\n return lib_name\n\n\ndef find_cmake_module_in(path_list):\n \"\"\"Return the list of CMake modules found in the given path list.\n\n :param path_list: list of the content to be searched\n\n :return: list of found CMake modules\n\n \"\"\"\n pattern = r\"^(find.*?|.*?-config).cmake$\"\n modules = _find_path_best_matches(path_list, [pattern])\n return modules\n\n\ndef find_matching_qibuild_cmake_module(names):\n \"\"\"Return the list of CMake modules provided by qiBuild and matching names.\n\n :param names: list of names used for matching\n\n :return: list of matching CMake modules\n\n \"\"\"\n root = qibuild.__path__[0].rsplit(os.sep, 2)[0]\n root = os.path.join(root, 'cmake', 'qibuild', 'modules')\n root = os.path.abspath(root)\n path_list = qibuild.sh.ls_r(root)\n names = [re.sub(\"^lib\", \"(lib)?\", name) for name in names]\n names = [re.sub(\"[^a-zA-Z0-9]+\", \".*?\", name) for name in names]\n names = list(set(names))\n modules = find_cmake_module_in(path_list)\n modules = _find_path_best_matches(modules, names)\n return modules\n\n\ndef check_for_module_generation(names, root_dir=None, path_list=None,\n modules_package=None, modules_qibuild=None):\n \"\"\"Return the status of the search of matching CMake modules already\n provided by either the package itself or qiBuild.\n\n The status can have the following values: \"provided_by_package\", or\n \"provided_by_qibuild\" or \"nonexistent\".\n\n :param name: list of names of the CMake module to be checked\n :param root_dir: base directory of the package to be search\n (default: None)\n :param path_list: list of the content of the package to be search\n (default: None)\n :param module_package: list of CMake modules found in the package\n (default: None)\n :param module_qibuild: list of CMake modules provided by qiBuild\n (default: None)\n\n :return: the tuple (module check status,\n list of modules provided by package,\n list of modules provided by qiBuild)\n\n \"\"\"\n if modules_package is None and modules_qibuild is None:\n if path_list is None:\n if root_dir is None:\n mess = \"Wrong call: at least 1 argument should be not 'None'\"\n raise Exception(mess)\n path_list = qibuild.sh.ls_r(root_dir)\n modules_package = find_cmake_module_in(path_list)\n modules_qibuild = find_matching_qibuild_cmake_module(names)\n prefix = r\".*?\" + os.sep + \"?usr\" + os.sep\n # pep8-ignore: E501\n modules_package = [re.sub(prefix, \"\", item) for item in modules_package]\n # pep8-ignore: E501\n modules_qibuild = [re.sub(prefix, \"\", item) for item in modules_qibuild]\n status = \"nonexistent\"\n if modules_qibuild:\n status = \"provided_by_qibuild\"\n if modules_package:\n status = \"provided_by_package\"\n return (status, modules_package, modules_qibuild)\n\n\ndef show_exiting_modules(name, modules_package, modules_qibuild):\n \"\"\"Print the CMake modules found in the package itself or provided by\n qiBuild for this package.\n\n :param name: package nane\n :param module_package: list of CMake modules found in the package\n :param module_qibuild: list of CMake modules provided by qiBuild\n\n \"\"\"\n if len(modules_package) > 0:\n modules = \"\\n\".join([\" {0}\".format(x) for x in modules_package])\n message = \"\"\"\\\nPackage '{0}' already provides the following CMake module(s):\n{1}\n\"\"\".format(name, modules)\n qibuild.ui.info(message)\n if len(modules_qibuild) > 0:\n modules = \"\\n\".join([\" {0}\".format(x) for x in modules_qibuild])\n message = \"\"\"\\\nqiBuild already provides the following CMake module(s) for the package '{0}':\n{1}\n\"\"\".format(name, modules)\n qibuild.ui.info(message)\n return\n\n\ndef _generate_template(name, prefix, header, libraries):\n \"\"\"Generate a template of CMake module.\n\n :param name: package name\n :param prefix: CMake module prefix\n :param header: header location (used by 'fpath')\n :param libraries: list of libraries (used by 'flib')\n\n :return: the template string of the CMake module\n\n \"\"\"\n # pep8-ignore: E501\n content = \"\"\"\\\n## ----------------------------------------------------------------------------\n##\n## WARNING:\n##\n## This is just a templated CMake module generated from the content of the\n## package.\n##\n## It is highly recommended to double-check the exactness of this generated\n## file.\n##\n## To get help writing this cmake module, check out:\n## http://www.aldebaran-robotics.com/documentation/qibuild/ref/cmake/api/find.html\n##\n## ----------------------------------------------------------------------------\n\"\"\"\n content += \"\"\"\n## CMake module for {name}\n\nclean({prefix})\n\"\"\".format(name=name, prefix=prefix)\n if header is not None:\n content += \"\"\"\nfpath({prefix} {header})\n\"\"\".format(prefix=prefix, header=_get_header_relative_path(header))\n if len(libraries) > 0:\n libnames = [_get_library_name(lib[0]) for lib in libraries]\n libnames = list(set(libnames))\n for libname in libnames:\n content += \"\"\"\\\nflib({prefix} {libname})\n\"\"\".format(prefix=prefix, libname=libname)\n content += \"\"\"\nexport_lib({prefix})\n\"\"\".format(prefix=prefix)\n return content\n\ndef _ask_template_info(name, prefix, headers, libraries):\n \"\"\"Interactively get the required CMake module data.\n\n :param name: package name\n :param prefix: CMake module prefix\n :param header: header location (used by 'fpath')\n :param libraries: list of libraries (used by 'flib')\n\n :return: a tuple (name, prefix, header, libraries)\n\n \"\"\"\n patterns = [name]\n question = \"Enter the package name:\"\n name = qibuild.interact.ask_string(question, default=name)\n patterns.append(name)\n patterns = list(set(patterns))\n question = \"Do you want to use '{0}' as CMake module name?\"\n question = question.format(prefix)\n answer = qibuild.interact.ask_yes_no(question, default=True)\n if not answer:\n question = \"Enter the CMake module name (uppercase):\"\n prefix = qibuild.interact.ask_string(question, default=prefix)\n header = None\n if len(headers) > 0:\n patterns = [pattern.lower() for pattern in patterns]\n patterns = [re.sub(\"[-_]\", \".?\", pattern) for pattern in patterns]\n patterns = [re.sub(\"^lib\", \"(lib)?\", pattern) for pattern in patterns]\n try:\n header_ = _find_path_best_matches(headers, patterns)[0]\n headers.remove(header_)\n headers.insert(0, header_)\n question = \"Which is the main header?\"\n header = qibuild.interact.ask_choice(headers, question)\n except IndexError:\n pass\n libs = None\n if len(libraries) > 0:\n libs = list()\n question = \"\"\"\\\nWhich libraries do you want to declare in the CMake module?\\\n\"\"\"\n qibuild.ui.info(question)\n for lib_static_shared in libraries:\n question = \", \".join(lib_static_shared)\n answer = qibuild.interact.ask_yes_no(question, default=True)\n if answer:\n libs.append([lib_static_shared[0]])\n return (name, prefix, header, libs)\n\ndef _edit_template(name, template, package_path_list):\n \"\"\"Handle interactive edition of the CMake module template.\n\n :param name: package name\n :param template: input CMake module template\n :param package_path_list: list of the content of the package\n (default: None)\n\n :return: the template string\n\n \"\"\"\n # pep8-ignore: E501\n question = \"Edit generated CMake module for {0} (highly recommended)?\".format(name)\n answer = qibuild.interact.ask_yes_no(question, default=True)\n if answer:\n answer = False\n if package_path_list is not None:\n # pep8-ignore: E501\n question = \"Would you like to list the package content before?\".format(name)\n answer = qibuild.interact.ask_yes_no(question, default=True)\n if answer:\n message = \"\"\"\\\nPackage content:\n{0}\n\nPress enter to launch the editor.\\\n\"\"\".format(\"\\n\".join([\" \" + x for x in package_path_list]))\n qibuild.ui.info(message)\n qibuild.interact.read_input()\n qibuild_cfg = qibuild.config.QiBuildConfig()\n qibuild_cfg.read()\n editor = qibuild_cfg.defaults.env.editor\n if not editor:\n editor = qibuild.interact.get_editor()\n editor_path = qibuild.command.find_program(editor)\n with qibuild.sh.TempDir() as tmp_dir:\n cmake_module = os.path.join(tmp_dir, 'tmp-module.cmake')\n with open(cmake_module, 'w') as module_file:\n module_file.write(template)\n qibuild.command.call([editor_path, cmake_module])\n with open(cmake_module, 'r') as module_file:\n template = module_file.read()\n return template\n\n\n# pylint: disable-msg=R0913\ndef generate_template(name, prefix, headers, libraries, path_list=None,\n interactive=True):\n \"\"\"Generate a template of CMake module from all information passed.\n\n :param name: package name\n :param prefix: CMake module prefix\n :param header: header location (used by 'fpath')\n :param libraries: list of libraries (used by 'flib')\n :param path_list: list of the content of the package\n (default: None)\n :param interactive: enable user interaction\n (default: True)\n\n :return: the tuple (package name,\n CMake module prefix,\n template string of the CMake module)\n\n \"\"\"\n libs = None\n header = None\n if prefix is None:\n prefix = name\n prefix = prefix.upper()\n if interactive:\n template_data = _ask_template_info(name, prefix, headers, libraries)\n name, prefix, header, libs = template_data\n if header is None and len(headers) > 0:\n header = headers[0]\n if libs is None:\n libs = libraries\n prefix = prefix.upper()\n template = _generate_template(name, prefix, header, libs)\n if interactive:\n template = _edit_template(name, template, path_list)\n return (name, prefix, template)\n\n\ndef generate_template_from_directory(directory, name, prefix=None,\n path_list=None, interactive=True):\n \"\"\"Generate a template of CMake module from the content of directory.\n\n :param directory: base directory of the package\n :param name: package name\n :param prefix: CMake module prefix\n (default: None)\n :param path_list: list of the content of the package\n (default: None)\n :param interactive: enable user interaction\n (default: True)\n\n :return: the tuple (package name,\n CMake module prefix,\n template string of the CMake module)\n\n \"\"\"\n if path_list is None:\n path_list = qibuild.sh.ls_r(directory)\n headers = _find_headers(path_list)\n libraries = _find_libraries(path_list)\n module = generate_template(name, prefix, headers, libraries,\n path_list=path_list, interactive=interactive)\n return module\n\n\ndef generate_template_from_archive(archive, name=None, prefix=None,\n interactive=True):\n \"\"\"Generate a template of CMake module from an archive.\n\n :param archive: archive path of the package\n :param name: package name\n (default: None)\n :param prefix: CMake module prefix\n (default: None)\n :param interactive: enable user interaction\n (default: True)\n\n :return: the tuple (package name,\n CMake module prefix,\n template string of the CMake module)\n\n \"\"\"\n algo = qibuild.archive.guess_algo(archive)\n module = None\n with qibuild.sh.TempDir() as work_dir:\n # pep8-ignore: E501\n root_dir = qibuild.archive.extract(archive, work_dir, algo=algo, quiet=True)\n if name is None:\n name = os.path.basename(root_dir)\n module = generate_template_from_directory(root_dir, name,\n prefix=prefix,\n interactive=interactive)\n return module\n\n\nclass CMakeModule(object):\n \"\"\" A class to handle CMake module generation\n\n \"\"\"\n __slots__ = (\"name\", \"prefix\", \"template\")\n\n def __init__(self, name=None, prefix=None, template=None):\n self.name = name\n self.prefix = prefix\n self.template = template\n\n def generate_template(self, name, prefix, headers, libraries,\n path_list=None, interactive=True):\n \"\"\"Generate a template of CMake module from all information passed.\n\n :param name: package name\n :param prefix: CMake module prefix\n :param header: header location (used by 'fpath')\n :param libraries: list of libraries (used by 'flib')\n :param path_list: list of the content of the package\n (default: None)\n :param interactive: enable user interaction\n (default: True)\n\n \"\"\"\n template = generate_template(name, prefix, headers, libraries,\n path_list=path_list,\n interactive=interactive)\n self.name = template[0]\n self.prefix = template[1]\n self.template = template[2]\n\n def generate_from_directory(self, directory, name, prefix=None,\n path_list=None, interactive=True):\n \"\"\"Generate a template of CMake module from the content of directory.\n\n :param directory: base directory of the package\n :param name: package name\n :param prefix: CMake module prefix\n (default: None)\n :param path_list: list of the content of the package\n (default: None)\n :param interactive: enable user interaction\n (default: True)\n\n \"\"\"\n template = generate_template_from_directory(directory, name,\n prefix=prefix,\n path_list=path_list,\n interactive=interactive)\n self.name = template[0]\n self.prefix = template[1]\n self.template = template[2]\n\n def generate_from_archive(self, archive, name=None, prefix=None,\n interactive=True):\n \"\"\"Generate a template of CMake module from an archive.\n\n :param archive: archive path of the package\n :param name: package name\n (default: None)\n :param prefix: CMake module prefix\n (default: None)\n :param interactive: enable user interaction\n (default: True)\n\n \"\"\"\n template = generate_template_from_archive(archive, name=name,\n prefix=prefix,\n interactive=interactive)\n self.name = template[0]\n self.prefix = template[1]\n self.template = template[2]\n\n def write(self, base_dir, prefix=None):\n \"\"\"Write the CMake module content in the right location.\n\n This writes the CMake module in::\n\n base_dir/prefix/share/cmake/self.prefix.lower()/self.prefix.lower()-config.cmake\n\n :param base_dir: root directory (the package installation DESTDIR)\n :param prefix: installation prefix (e.g. /usr on Linux)\n (default: None)\n\n :return: the path of the generated CMake module\n\n \"\"\"\n if self.template is None:\n message = \"No CMake module to write\"\n qibuild.ui.info(message)\n return None\n module_filename = \"{0}-config.cmake\".format(self.prefix.lower())\n if prefix is not None:\n module_dir = os.path.join(base_dir, prefix)\n else:\n module_dir = base_dir\n # pep8-ignore: E501\n module_dir = os.path.join(module_dir, \"share\", \"cmake\", self.prefix.lower())\n module_path = os.path.join(module_dir, module_filename)\n qibuild.sh.mkdir(module_dir, recursive=True)\n with open(module_path, \"w\") as module_file:\n module_file.write(self.template)\n return module_path\n"
},
{
"alpha_fraction": 0.6140257120132446,
"alphanum_fraction": 0.6161670088768005,
"avg_line_length": 41.942527770996094,
"blob_id": "985e0a0ccdf688ed2fd76151a7de09a2fb9564c4",
"content_id": "b01dfdd09c2667fd88cc1f5842529f5a876c2730",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3736,
"license_type": "permissive",
"max_line_length": 85,
"num_lines": 87,
"path": "/python/qibuild/actions/deploy.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\n\"\"\"Deploy code to a remote target \"\"\"\n\nimport os\n\nfrom qibuild import ui\nimport qibuild\nimport qibuild.sh\nimport qibuild.deploy\n\ndef configure_parser(parser):\n \"\"\"Configure parser for this action\"\"\"\n qibuild.parsers.toc_parser(parser)\n qibuild.parsers.project_parser(parser)\n qibuild.parsers.build_parser(parser)\n parser.add_argument(\"url\", help=\"remote url: user@hostname:path\")\n parser.add_argument(\"-p\", \"--port\", help=\"port\", type=int)\n parser.set_defaults(port=22)\n\ndef do(args):\n \"\"\"Main entry point\"\"\"\n url = args.url\n (username, server, remote_directory) = qibuild.deploy.parse_url(url)\n toc = qibuild.toc_open(args.worktree, args)\n ui.info(ui.green, \"Current worktree:\", ui.reset, ui.bold, toc.worktree.root)\n if toc.active_config:\n ui.info(ui.green, \"Active configuration: \",\n ui.blue, \"%s (%s)\" % (toc.active_config, toc.build_type))\n rsync = qibuild.command.find_program(\"rsync\", env=toc.build_env)\n use_rsync = False\n if rsync:\n use_rsync = True\n else:\n ui.warning(\"Please install rsync to get faster synchronisation\")\n scp = qibuild.command.find_program(\"scp\", env=toc.build_env)\n if not scp:\n raise Exception(\"Could not find rsync or scp\")\n\n # Resolve deps:\n (project_names, package_names, _) = toc.resolve_deps(runtime=True)\n projects = [toc.get_project(name) for name in project_names]\n\n if not args.single:\n ui.info(ui.green, \"The following projects\")\n for project_name in project_names:\n ui.info(ui.green, \" *\", ui.blue, project_name)\n if not args.single and package_names:\n ui.info(ui.green, \"and the following packages\")\n for package_name in package_names:\n ui.info(\" *\", ui.blue, package_name)\n ui.info(ui.green, \"will be deployed to\", ui.blue, url)\n\n # Deploy packages: install all of them in the same temp dir, then\n # deploy this temp dir to the target\n if not args.single and package_names:\n print\n ui.info(ui.green, \":: \", \"Deploying packages\")\n with qibuild.sh.TempDir() as tmp:\n for (i, package_name) in enumerate(package_names):\n ui.info(ui.green, \"*\", ui.reset,\n \"(%i/%i)\" % (i+1, len(package_names)),\n ui.green, \"Deploying package\", ui.blue, package_name,\n ui.green, \"to\", ui.blue, url)\n toc.toolchain.install_package(package_name, tmp, runtime=True)\n qibuild.deploy.deploy(tmp, args.url, use_rsync=use_rsync, port=args.port)\n print\n\n if not args.single:\n ui.info(ui.green, \":: \", \"Deploying projects\")\n # Deploy projects: install them inside a 'deploy' dir inside the build dir,\n # then deploy this dir to the target\n for (i, project) in enumerate(projects):\n ui.info(ui.green, \"*\", ui.reset,\n \"(%i/%i)\" % (i+1, len(projects)),\n ui.green, \"Deploying project\", ui.blue, project.name,\n ui.green, \"to\", ui.blue, url)\n destdir = os.path.join(project.build_directory, \"deploy\")\n #create folder for project without install rules\n qibuild.sh.mkdir(destdir, recursive=True)\n toc.install_project(project, destdir, prefix=\"/\",\n runtime=True, num_jobs=args.num_jobs,\n split_debug=True)\n qibuild.deploy.deploy(destdir, args.url, use_rsync=use_rsync, port=args.port)\n qibuild.deploy.generate_debug_scripts(toc, project.name, args.url)\n"
},
{
"alpha_fraction": 0.6228448152542114,
"alphanum_fraction": 0.6271551847457886,
"avg_line_length": 33.37036895751953,
"blob_id": "fac6b334843fbcffcd10e6ceb213fa36a4cd8e28",
"content_id": "a725b023b05a3299cff8b93c7f1e4a6cdb708035",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 928,
"license_type": "permissive",
"max_line_length": 74,
"num_lines": 27,
"path": "/python/qisrc/actions/add.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\n\"\"\"Add a new project in a qisrc workspace \"\"\"\n\nimport qisrc.sync\nimport qibuild\n\n\n\ndef configure_parser(parser):\n \"\"\"Configure parser for this action \"\"\"\n qibuild.parsers.worktree_parser(parser)\n parser.add_argument(\"url\", metavar=\"URL\", help=\"url of the project. \"\n \"right now only git URLs are supported\")\n parser.add_argument(\"--src\",\n help=\"path to the source of project. (Relative to the worktree). \"\n \"If not given, the project will be put in \"\n \"<QI_WORK_TREE>/<name>\")\n\ndef do(args):\n \"\"\"Main entry point\"\"\"\n worktree = qisrc.worktree.open_worktree(args.worktree)\n qisrc.sync.clone_project(worktree, args.url,\n src=args.src,\n skip_if_exists=False)\n"
},
{
"alpha_fraction": 0.6531499028205872,
"alphanum_fraction": 0.6560463309288025,
"avg_line_length": 26.078432083129883,
"blob_id": "583fdc3da9c91f5fd2510592842b0ff68424dd85",
"content_id": "3ec80e3d09e55f109761d621c773ad8676471420",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1381,
"license_type": "permissive",
"max_line_length": 73,
"num_lines": 51,
"path": "/python/qidoc/actions/open.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\n\"\"\" Open the current documentation in a web browser\n\n\"\"\"\n\nimport os\n\nimport qibuild\nimport qidoc.core\n\ndef configure_parser(parser):\n \"\"\" Configure parser for this action \"\"\"\n qibuild.parsers.default_parser(parser)\n parser.add_argument(\"--work-tree\", dest=\"worktree\")\n parser.add_argument(\"-o\", \"--output-dir\", dest=\"output_dir\",\n help=\"Where to generate the docs\")\n parser.add_argument(\"name\", nargs=\"?\",\n help=\"project to open\")\n\n\ndef do(args):\n \"\"\" Main entry point \"\"\"\n worktree = args.worktree\n project_name = args.name\n\n worktree = qidoc.core.find_qidoc_root(worktree)\n if not worktree:\n raise Exception(\"No qidoc worktree found.\\n\"\n \"Please call qidoc init or go to a qidoc worktree\")\n\n output_dir = args.output_dir\n if not output_dir:\n output_dir = os.path.join(worktree, \"build-doc\")\n else:\n output_dir = qibuild.sh.to_native_path(output_dir)\n\n builder = qidoc.core.QiDocBuilder(worktree, output_dir)\n\n if project_name:\n builder.open_single(project_name)\n return\n\n project_name = builder.project_from_cwd()\n if project_name:\n builder.open_single(project_name)\n return\n\n builder.open_main()\n"
},
{
"alpha_fraction": 0.6417574286460876,
"alphanum_fraction": 0.6466391086578369,
"avg_line_length": 34.50666809082031,
"blob_id": "0713571715c2254f674eeeff2c1b72bd1da7eb5d",
"content_id": "82b26f19ceb00c4c887be1f3c2e77978c0436000",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2663,
"license_type": "permissive",
"max_line_length": 77,
"num_lines": 75,
"path": "/python/qisrc/test/test_clone.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\nimport os\nimport unittest\nimport tempfile\n\nimport pytest\n\nimport qisrc\nimport qisrc.sync\nimport qibuild\nfrom qisrc.test.test_git import create_git_repo\n\n\n# pylint: disable-msg=E1101\[email protected]\nclass CloneProjectTestCase(unittest.TestCase):\n def setUp(self):\n qibuild.command.CONFIG[\"quiet\"] = True\n self.tmp = tempfile.mkdtemp(prefix=\"test-qisrc-sync\")\n qibuild.sh.mkdir(self.tmp)\n self.srv = os.path.join(self.tmp, \"srv\")\n qibuild.sh.mkdir(self.srv)\n worktree_root = os.path.join(self.tmp, \"work\")\n qibuild.sh.mkdir(worktree_root)\n self.worktree = qisrc.worktree.open_worktree(worktree_root)\n\n def tearDown(self):\n qibuild.command.CONFIG[\"false\"] = True\n qibuild.sh.rm(self.tmp)\n\n def test_simple_clone(self):\n bar_url = create_git_repo(self.tmp, \"bar\")\n qisrc.sync.clone_project(self.worktree, bar_url)\n self.assertEqual(self.worktree.git_projects[0].src, \"bar\")\n\n def test_clone_skipping(self):\n bar_url = create_git_repo(self.tmp, \"bar\")\n qisrc.sync.clone_project(self.worktree, bar_url)\n self.assertEqual(self.worktree.git_projects[0].src, \"bar\")\n qisrc.sync.clone_project(self.worktree, bar_url, skip_if_exists=True)\n self.assertEqual(len(self.worktree.git_projects), 1)\n self.assertEqual(self.worktree.git_projects[0].src, \"bar\")\n\n def test_clone_project_already_exists(self):\n bar_url = create_git_repo(self.tmp, \"bar\")\n baz_url = create_git_repo(self.tmp, \"baz\")\n qisrc.sync.clone_project(self.worktree, bar_url, src=\"bar\")\n error = None\n try:\n qisrc.sync.clone_project(self.worktree, baz_url, src=\"bar\")\n except Exception, e:\n error = e\n self.assertFalse(error is None)\n self.assertTrue(\"already registered\" in str(error))\n\n def test_clone_path_already_exists(self):\n bar_url = create_git_repo(self.tmp, \"bar\")\n conflicting_path = os.path.join(self.worktree.root, \"bar\")\n qibuild.sh.mkdir(conflicting_path)\n error = None\n try:\n qisrc.sync.clone_project(self.worktree, bar_url)\n except Exception, e:\n error = e\n\n self.assertFalse(error is None)\n self.assertTrue(\"already exists\" in str(error), error)\n qisrc.sync.clone_project(self.worktree, bar_url, src=\"baz\")\n self.assertEqual(self.worktree.git_projects[0].src, \"baz\")\n\nif __name__ == \"__main__\":\n unittest.main()\n"
},
{
"alpha_fraction": 0.5486694574356079,
"alphanum_fraction": 0.5539740324020386,
"avg_line_length": 32.07310104370117,
"blob_id": "51eca402ae33ea60d86f03be5e286fd8128ef9af",
"content_id": "5e1b0ca577f422a56e6829d7f8e426d0f3d66621",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11311,
"license_type": "permissive",
"max_line_length": 113,
"num_lines": 342,
"path": "/python/qibuild/ctest.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\n\"\"\" Re-implementation of CTest in Python.\n\nNecessary to by-pass some small ctest shortcomings.\n\"\"\"\n\nimport os\nimport sys\nimport re\nimport datetime\nimport errno\nimport signal\nimport shlex\n\nimport qibuild\nfrom qibuild import ui\n\n\ndef _str_from_signal(code):\n \"\"\" Returns a nice string describing the signal\n\n \"\"\"\n if code == signal.SIGSEGV:\n return \"Segmentation fault\"\n if code == signal.SIGABRT:\n return \"Aborted\"\n else:\n return \"%i\" % code\n\n\nclass TestResult:\n \"\"\" Just a small class to store the results for a test\n\n \"\"\"\n def __init__(self, test_name):\n self.test_name = test_name\n self.time = 0\n self.ok = False\n # Output of the executable of the test\n self.out = \"\"\n # Short description of what went wrong\n self.message = \"\"\n\ndef parse_valgrind(valgrind_log, tst):\n \"\"\"\n parse valgrind logs and extract interesting errors.\n \"\"\"\n leak_fd_regex = re.compile(\"==\\d+== FILE DESCRIPTORS: (\\d+)\")\n invalid_read_regex = re.compile(\"==\\d+== Invalid read of size (\\d+)\")\n with open(valgrind_log, \"r\") as f:\n lines = f.readlines()\n\n for l in lines:\n tst.out += l\n r = leak_fd_regex.search(l)\n if r:\n fdopen = int(r.group(1))\n # 4: in/out/err + valgrind_log\n if fdopen > 4:\n tst.ok = False\n tst.message += \"Error file descriptors leaks:\" + str(fdopen - 4) + \"\\n\"\n continue\n r = invalid_read_regex.search(l)\n if r:\n tst.ok = False\n tst.message += \"Invalid read \" + r.group(1) + \"\\n\"\n\n\ndef run_test(build_dir, test_name, cmd, properties, build_env, verbose=False, valgrind=False):\n \"\"\" Run a test.\n\n :return: (res, output) where res is a string describing wether\n the test was sucessul, and output is the output of the test\n\n \"\"\"\n timeout = properties.get(\"TIMEOUT\")\n if timeout:\n timeout = int(timeout)\n # we will merge the build env coming from toc\n # config with the env coming from CMake config,\n # assuming that cmake is always right\n env = build_env.copy()\n cmake_env = properties.get(\"ENVIRONMENT\")\n if cmake_env:\n cmake_env = cmake_env.split(\";\")\n for key_value in cmake_env:\n key, value = key_value.split(\"=\")\n env[key] = value\n working_dir = properties.get(\"WORKING_DIRECTORY\")\n if working_dir:\n cwd = working_dir\n else:\n cwd = build_dir\n ncmd = cmd\n\n if valgrind:\n valgrind_log = os.path.join(build_dir, test_name + \"valgrind_output.log\")\n ncmd = [ \"valgrind\", \"--track-fds=yes\", \"--log-file=%s\" % valgrind_log ]\n ncmd.extend(cmd)\n process_thread = qibuild.command.ProcessThread(ncmd,\n name=test_name,\n cwd=cwd,\n env=env,\n verbose=verbose)\n\n res = TestResult(test_name)\n start = datetime.datetime.now()\n process_thread.start()\n process_thread.join(timeout)\n end = datetime.datetime.now()\n delta = end - start\n res.time = float(delta.microseconds) / 10**6 + delta.seconds\n\n process = process_thread.process\n if not process:\n exception = process_thread.exception\n mess = \"Could not run test: %s\\n\" % test_name\n mess += \"Error was: %s\\n\" % exception\n mess += \"Full command was: %s\\n\" % \" \".join(ncmd)\n if isinstance(exception, OSError):\n # pylint: disable-msg=E1101\n if exception.errno == errno.ENOENT:\n mess += \"Are you sure you have built the tests?\"\n raise Exception(mess)\n res.out = process_thread.out\n if process_thread.isAlive():\n process.terminate()\n res.ok = False\n res.message = \"Timed out (%i s)\" % timeout\n else:\n retcode = process.returncode\n if retcode == 0:\n res.ok = True\n else:\n res.ok = False\n try:\n process.kill()\n except:\n pass\n if retcode > 0:\n res.message = \"Return code: %i\" % retcode\n else:\n res.message = _str_from_signal(-retcode)\n if valgrind:\n parse_valgrind(valgrind_log, res)\n return res\n\n\ndef run_tests(project, build_env, pattern=None, verbose=False, slow=False, dry_run=False, valgrind=False):\n \"\"\" Called by :py:meth:`qibuild.toc.Toc.test_project`\n\n :param test_name: If given, only run this test\n\n Always write some XML files in build-<config>/test-results\n (even if they were no tests to run at all)\n\n :return: a boolean to indicate if test was sucessful\n\n \"\"\"\n build_dir = project.build_directory\n results_dir = os.path.join(project.build_directory, \"test-results\")\n\n all_tests = parse_ctest_test_files(build_dir)\n tests = list()\n slow_tests = list()\n if pattern:\n tests = [x for x in all_tests if re.search(pattern, x[0])]\n if not tests:\n mess = \"No tests matching %s\\n\" % pattern\n mess += \"Known tests are:\\n\"\n for x in all_tests:\n mess += \" * \" + x[0] + \"\\n\"\n raise Exception(mess)\n else:\n for test in all_tests:\n (name, cmd_, properties) = test\n cost = properties.get(\"COST\")\n if not slow and cost and float(cost) > 50:\n ui.debug(\"Skipping test\", name, \"because cost\",\n \"(%s)\"% cost, \"is greater than 50\")\n slow_tests.append(name)\n continue\n tests.append(test)\n\n if not tests:\n # Create a fake test result to keep CI jobs happy:\n fake_test_res = TestResult(\"compilation\")\n fake_test_res.ok = True\n xml_out = os.path.join(results_dir, \"compilation.xml\")\n write_xml(xml_out, fake_test_res)\n ui.warning(\"No tests found for project\", project.name)\n return\n\n if dry_run:\n ui.info(ui.green, \"List of tests for\", project.name)\n for (test_name, _, _) in tests:\n ui.info(ui.green, \" * \", ui.reset, test_name)\n return\n\n ui.info(ui.green, \"Testing\", project.name, \"...\")\n ok = True\n fail_tests = list()\n for (i, test) in enumerate(tests):\n (test_name, cmd, properties) = test\n ui.info(ui.green, \" * \", ui.reset, ui.bold,\n \"(%2i/%2i)\" % (i+1, len(tests)),\n ui.blue, test_name.ljust(25), end=\"\")\n if verbose:\n print\n sys.stdout.flush()\n test_res = run_test(build_dir, test_name, cmd, properties, build_env,\n valgrind=valgrind, verbose=verbose)\n if test_res.ok:\n ui.info(ui.green, \"[OK]\")\n else:\n ok = False\n ui.info(ui.red, \"[FAIL]\")\n if not verbose:\n print test_res.out\n fail_tests.append(test_name)\n xml_out = os.path.join(results_dir, test_name + \".xml\")\n if not os.path.exists(xml_out):\n write_xml(xml_out, test_res)\n\n if ok:\n ui.info(\"Ran %i tests\" % len(tests))\n if slow_tests and not slow:\n ui.info(\"Note: %i\" % len(slow_tests),\n \"slow tests did not run, use --slow to run them\")\n ui.info(\"All pass. Congrats!\")\n return True\n\n ui.error(\"Ran %i tests, %i failures\" %\n (len(tests), len(fail_tests)))\n for fail_test in fail_tests:\n ui.info(ui.bold, \" -\", ui.blue, fail_test)\n return False\n\n\ndef write_xml(xml_out, test_res):\n \"\"\" Write a XUnit XML file\n\n \"\"\"\n to_write = \"\"\"<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n<testsuites tests=\"1\" failures=\"{num_failures}\" disabled=\"0\" errors=\"0\" time=\"{time}\" name=\"All\">\n <testsuite name=\"{testsuite_name}\" tests=\"1\" failures=\"{num_failures}\" disabled=\"0\" errors=\"0\" time=\"{time}\">\n <testcase name=\"{testcase_name}\" status=\"run\">\n {failure}\n </testcase>\n </testsuite>\n</testsuites>\n\"\"\"\n if test_res.ok:\n num_failures = \"0\"\n failure = \"\"\n else:\n num_failures = \"1\"\n failure = \"\"\"\n <failure message=\"{message}\">\n <![CDATA[ {out} ]]>\n </failure>\n\"\"\"\n failure = failure.format(out=test_res.out,\n message=test_res.message)\n to_write = to_write.format(num_failures=num_failures,\n testsuite_name=\"test\", # nothing clever to put here :/\n testcase_name=test_res.test_name,\n failure=failure,\n time=test_res.time)\n qibuild.sh.mkdir(os.path.dirname(xml_out), recursive=True)\n with open(xml_out, \"w\") as fp:\n fp.write(to_write)\n\n\ndef parse_ctest_test_files(build_dir):\n \"\"\" Recursively parse CTestTestfile.cmake.\n Returns a list of lists of 3 elements:\n [name, cmd, properties]\n\n \"\"\"\n tests = list()\n subdirs = list()\n _parse_ctest_test_files(build_dir, tests, subdirs)\n return tests\n\ndef _parse_ctest_test_files(root, tests, subdirs):\n \"\"\" Helper for parse_ctest_test_files.\n We will fill up the tests and subdirs parameters as we go.\n\n \"\"\"\n ctest_test_file = os.path.join(root, \"CTestTestfile.cmake\")\n if not os.path.exists(ctest_test_file):\n return list()\n with open(ctest_test_file, \"r\") as fp:\n lines = fp.readlines()\n\n current_test = None\n for i, line in enumerate(lines):\n match = re.match(\"SUBDIRS\\((.*)\\)\", line)\n if match:\n subdir = match.groups()[0]\n subdirs.append(subdir)\n current_test = None\n continue\n match = re.match(\"ADD_TEST\\(([a-zA-Z0-9_-]*) (.*)\\)\", line)\n if match:\n groups = match.groups()\n current_test = groups[0]\n args = groups[1]\n test_cmd = shlex.split(args)\n tests.append([current_test, test_cmd, dict()])\n continue\n match = re.match(\"SET_TESTS_PROPERTIES\\(([a-zA-Z0-9_-]*) PROPERTIES (.*)\\)\", line)\n if match:\n groups = match.groups()\n if current_test is None:\n mess = \"Expecting ADD_TEST before SET_TESTS_PROPERTIES\\n\"\n mess += \"in %s:%i\" % (ctest_test_file, i+1)\n raise Exception(mess)\n name = groups[0]\n if name != current_test:\n mess = \"SET_TESTS_PROPERTIES called with wrong name\\n\"\n mess += \"Expecting %s, got %s\\n\" % (current_test, name)\n mess += \"in %s:%i\" % (ctest_test_file, i+1)\n raise Exception(mess)\n properties = groups[1]\n properties = shlex.split(properties)\n test_properties = dict()\n for i in range(0, len(properties)/2):\n key = properties[2*i]\n value = properties[2*i+1]\n test_properties[key] = value\n # Just erase everything if there are two calls to set_test_properties()\n tests[-1][2] = test_properties\n current_test = None\n\n for subdir in subdirs:\n new_root = os.path.join(root, subdir)\n _parse_ctest_test_files(new_root, tests, list())\n"
},
{
"alpha_fraction": 0.6842105388641357,
"alphanum_fraction": 0.6937798857688904,
"avg_line_length": 33.75,
"blob_id": "e4a6b86d98fae321b77d11319bafe25d87c46700",
"content_id": "6ef5074597ee1268dcc4b17c07b43b382c75d26a",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 418,
"license_type": "permissive",
"max_line_length": 75,
"num_lines": 12,
"path": "/python/qisrc/parsers.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\n\"\"\" Common parsers for qisrc actions \"\"\"\n\nimport qibuild.parsers\n\ndef worktree_parser(parser):\n qibuild.parsers.default_parser(parser)\n parser.add_argument(\"-w\", \"--worktree\", \"--work-tree\", dest=\"worktree\",\n help=\"Use a specific work tree path.\")\n\n"
},
{
"alpha_fraction": 0.6311631798744202,
"alphanum_fraction": 0.6327975988388062,
"avg_line_length": 32.37272644042969,
"blob_id": "e729ed0e2983fb9ae1c9fc43544fc7af7bb58f6b",
"content_id": "12d2a64584b4d6a437cd5bceab6fdc5e20658804",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3671,
"license_type": "permissive",
"max_line_length": 83,
"num_lines": 110,
"path": "/python/qidoc/sphinx.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\n\"\"\" Set of tools to handle sphinx projects\n\n\"\"\"\n\nimport os\nimport sys\n\nfrom qibuild import ui\nimport qidoc.templates\nimport qibuild.sh\n\n\ndef configure(src, dest, templates, intersphinx_mapping, doxylink, opts):\n \"\"\" Configure a sphinx repo\n\n The sphix repo MUST have a src/source/ directory\n (NOT the default of sphinx-quickstart)\n\n The conf.py will be put in src/qidoc/conf.py\n concatening the contents of the templates with the conf.py from\n src/qidoc/conf.in.py, so that you can put src/source/conf.py\n under version control\n\n \"\"\"\n # Rebuild a doxylink dict with relative paths\n rel_doxylink = doxylink.copy()\n for (name, (tag_file, prefix)) in rel_doxylink.iteritems():\n full_prefix = os.path.join(dest, prefix)\n rel_prefix = os.path.relpath(full_prefix, dest)\n rel_doxylink[name] = (tag_file, rel_prefix)\n\n # Deal with conf.py\n conf_py_tmpl = os.path.join(templates, \"sphinx\", \"conf.in.py\")\n conf_py_in = os.path.join(src, \"qidoc\", \"conf.in.py\")\n if not os.path.exists(conf_py_in):\n mess = \"Could not configure sphinx sources in:%s \\n\" % src\n mess += \"qidoc/conf.in.py does not exists\"\n ui.warning(mess)\n return\n\n opts[\"doxylink\"] = str(rel_doxylink)\n opts[\"intersphinx_mapping\"] = str(intersphinx_mapping)\n opts[\"themes_path\"] = os.path.join(templates, \"sphinx\", \"_themes\")\n opts[\"themes_path\"] = qibuild.sh.to_posix_path(opts[\"themes_path\"])\n opts[\"ext_path\"] = os.path.join(templates, \"sphinx\", \"tools\")\n opts[\"ext_path\"] = qibuild.sh.to_posix_path(opts[\"ext_path\"])\n\n conf_py_out = os.path.join(src, \"qidoc\", \"conf.py\")\n qidoc.templates.configure_file(conf_py_tmpl, conf_py_out,\n append_file=conf_py_in,\n opts=opts)\n\n\ndef gen_download_zips(src):\n \"\"\" Process sources of the documentation, looking for\n every directory containing a .zipme, and\n copying it do src/_zips/\n\n \"\"\"\n zips_path = os.path.join(src, \"_zips\")\n qibuild.sh.mkdir(zips_path)\n for (root, directories, _files) in os.walk(src):\n for directory in directories:\n zipme = os.path.join(root, directory, \".zipme\")\n if os.path.exists(zipme):\n qibuild.archive.compress(os.path.join(root, directory), algo=\"zip\")\n\n\ndef build(src, dest, opts):\n \"\"\" Run sphinx-build on a sphinx repo\n\n configure() should have been called first\n\n \"\"\"\n ui.info(ui.green, \"Building sphinx\", src)\n config_path = os.path.join(src, \"qidoc\")\n # Try with sphinx-build2 (for arch), then fall back on\n # sphinx-build\n sphinx_build2 = qibuild.command.find_program(\"sphinx-build2\")\n if sphinx_build2:\n cmd = [sphinx_build2]\n else:\n sphinx_build = qibuild.command.find_program(\"sphinx-build\")\n if not sphinx_build:\n raise Exception(\"sphinx-build not in path, please install it\")\n cmd = [sphinx_build]\n\n if os.path.exists(os.path.join(config_path, \"conf.py\")):\n cmd.extend([\"-c\", config_path])\n if opts.get(\"werror\"):\n cmd.append(\"-W\")\n if opts.get(\"quiet\"):\n cmd.append(\"-q\")\n for flag in opts.get(\"flags\", list()):\n cmd.extend([\"-D\", flag])\n cmd.extend([os.path.join(src, \"source\"), dest])\n\n env = os.environ.copy()\n release = opts.get(\"release\", False)\n if release:\n env[\"build_type\"] = \"release\"\n else:\n env[\"build_type\"] = \"internal\"\n # by-pass sphinx-build bug on mac:\n if sys.platform == \"darwin\":\n env[\"LC_ALL\"] = \"en_US.UTF-8\"\n qibuild.command.call(cmd, cwd=src, env=env)\n"
},
{
"alpha_fraction": 0.6861598491668701,
"alphanum_fraction": 0.688758909702301,
"avg_line_length": 29.176469802856445,
"blob_id": "4d8bab0bb5636a1c55b959b09847aea875d7c151",
"content_id": "e0360b49c376c0a9d97a3daa1a3b026fd87fa697",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1539,
"license_type": "permissive",
"max_line_length": 77,
"num_lines": 51,
"path": "/python/qidoc/actions/list.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\n\"\"\" List the doc projects of the given worktree\n\n\"\"\"\n\nimport operator\nimport os\n\nimport qibuild\nimport qidoc.core\n\ndef configure_parser(parser):\n \"\"\" Configure parser for this action \"\"\"\n qibuild.parsers.default_parser(parser)\n parser.add_argument(\"--work-tree\", dest=\"worktree\")\n\n\ndef do(args):\n \"\"\" Main entry point \"\"\"\n worktree = args.worktree\n worktree = qidoc.core.find_qidoc_root(worktree)\n if not worktree:\n raise Exception(\"No qidoc worktree found.\\n\"\n \"Please call qidoc init or go to a qidoc worktree\")\n\n builder = qidoc.core.QiDocBuilder(worktree)\n\n print \"List of qidoc projects in\", builder.worktree.root\n print\n\n print \"Doxygen docs:\"\n doxydocs = builder.doxydocs.values()\n # Re write the doxydoc.src to be relative to worktree\n for doxydoc in doxydocs:\n doxydoc.src = os.path.relpath(doxydoc.src, builder.worktree.root)\n doxydocs.sort(key=operator.attrgetter(\"src\"))\n for doxydoc in doxydocs:\n print \" \", doxydoc.src\n print\n\n print \"Sphinx docs:\"\n sphinxdocs = builder.sphinxdocs.values()\n # Re write the sphinxdoc.src to be relative to worktree\n for sphinxdoc in sphinxdocs:\n sphinxdoc.src = os.path.relpath(sphinxdoc.src, builder.worktree.root)\n sphinxdocs.sort(key=operator.attrgetter(\"src\"))\n for sphinxdoc in sphinxdocs:\n print \" \", sphinxdoc.src\n"
},
{
"alpha_fraction": 0.6777097582817078,
"alphanum_fraction": 0.681310772895813,
"avg_line_length": 21.395160675048828,
"blob_id": "9181f0502d7153aafbba0230d242a8ac0859fbac",
"content_id": "73276b97a5851684d7b02adf6df9402c895ff4c4",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 2777,
"license_type": "permissive",
"max_line_length": 94,
"num_lines": 124,
"path": "/doc/source/relnotes.rst",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": ".. _qibuild-relnotes:\n\nqiBuild release notes\n=====================\n\nWhat's new in qiBuild 1.16\n---------------------------\n\ngeneral\n+++++++\n\n* Output of most commands are now more colorful and more readable\n\nwortkree\n++++++++\n\n\n* better performances on all qibuild commands: paths of the projects are now stored in\n ``QI_WORKTREE/.qi/worktree.xml``\n\n* buildable projects (directories containing a qiproject.xml and a CMakeLists\n are not automatically added to the project),\n Use ``qisrc add-project`` to add a new project to your worktree\n\n* every buildable git project MUST have a qiproject.xml at the root. Il you\n have subprojet, you must add them this way:\n\n.. code-block:: xml\n\n <project name=\"foo\">\n <project src=\"gui\" />\n <project src=\"lib\" />\n </project>\n\nqibuild\n++++++++\n\n* Add ``qibuild deploy`` to deploy code to a remote target, and easy\n remote debugging.\n\nqisrc\n+++++\n\n\n* ``qisrc init`` now can be used with a git repository url, which lets you\n simply use several worktress with projects on different branches, or with\n different \"profiles\",\n\n* new command to pull every repository, clone missing repositories, configure\n repositories for code review called ``qisrc sync``\n\n* support for code review with ``qisrc push``\n\n* removed ``qisrc fetch``, use ``qisrc init`` instead. The manifest should\n now be given as a git repository and not an url.\n\n* removed ``qisrc pull``, use ``qisrc sync`` instead\n\n\nqidoc\n+++++\n\n* ``qibuild doc`` can now be used to only build one project\n\n* ``qidoc build`` used without arguments will:\n\n * build every doc when run at the top of the worktree\n * build only the current project if you are inside a directory of\n the project.\n For instance, running ``qidoc build`` running from ``qibuild/doc/source``\n will only build the doc for ``qibuild``)\n\n\n* New command: ``qidoc open`` to view the generated documentation in a web\n browser\n\n* ``qibuild doc`` used twice no longer re-compiles everything\n\n\nqicd\n++++\n\nYou can add the following to ``~/.profile`` on git bash or the equivalent\non linux\n\n.. code-block:: bash\n\n source /path/to/qibuild/bin/qicd.sh\n\nAnd then you can use\n\n.. code-block:: console\n\n qicd libqi\n\nTo go directly to ``lib/libqi``.\n\nNote: the command will match the first basemane matching\nthe start of the argument ::\n\n qicd foo -> bar/foo\n qicd foo-g -> gui/foo-gui\n\ncmake\n+++++\n\n* ``qibuild configure`` no longer creates a ``build-tests`` folder at the root of the project,\n the folder in whih the XML files are generated is now in ``build-<config>/test-results``\n\n .. seealso::\n\n * :ref:`qibuild-ctest`\n\nPrevious release notes\n----------------------\n\n* :ref:`qibuild-relnotes-1.14`\n* :ref:`qibuild-relnotes-1.12.1`\n\n\nFull Changelog\n--------------\n\n* :ref:`qibuild-changelog`\n"
},
{
"alpha_fraction": 0.5694010257720947,
"alphanum_fraction": 0.5740517973899841,
"avg_line_length": 28.62232780456543,
"blob_id": "77164d99a8d884435147ad9994c9722da3924099",
"content_id": "f6adcf2eb0edaa79bc6d2ca2d480334b577e3de3",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 12471,
"license_type": "permissive",
"max_line_length": 83,
"num_lines": 421,
"path": "/python/qibuild/command.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\n\"\"\" This module contains few functions around subprocess\n\n\"\"\"\n\nimport os\nimport sys\nimport contextlib\nimport subprocess\nimport threading\nimport Queue\n\nfrom qibuild import ui\nimport qibuild\n\n\n# Quick hack: in order to be able to configure how\n# qibuild.command works, we have to use this\n# global variable\nCONFIG = dict()\n\n# Cache for find_program()\n_FIND_PROGRAM_CACHE = dict()\n\nclass ProcessThread(threading.Thread):\n \"\"\" A simple way to run commands.\n\n The thread will terminate when the command terminates\n\n The full log is available in self.out, and the subprocess.Popen\n object in self.process\n\n \"\"\"\n def __init__(self, cmd, name=None, verbose=False, cwd=None, env=None):\n if name is None:\n thread_name = \"ProcessThread\"\n else:\n thread_name = \"ProcessThread<%s>\" % name\n threading.Thread.__init__(self, name=thread_name)\n self.cmd = cmd\n self.cwd = cwd\n self.env = env\n self.out = \"\"\n self.process = None\n self.exception = \"\"\n self.verbose = verbose\n\n def run(self):\n ui.debug(\"Calling:\", \" \".join(self.cmd))\n try:\n self.process = subprocess.Popen(self.cmd,\n stdout=subprocess.PIPE,\n stderr=subprocess.STDOUT,\n cwd=self.cwd,\n env=self.env)\n except Exception, e:\n self.exception = e\n return\n\n while self.process.poll() is None:\n line = self.process.stdout.readline()\n self.out += line\n if self.verbose:\n sys.stdout.write(line)\n #program is finished, does not mean we read all lines\n #read them!\n while True:\n line = self.process.stdout.readline()\n if line == \"\":\n break\n self.out += line\n if self.verbose:\n sys.stdout.write(line)\n\n\nclass CommandFailedException(Exception):\n \"\"\"Custom exception \"\"\"\n def __init__(self, cmd, returncode, cwd=None):\n self.cmd = cmd\n if cwd is None:\n self.cwd = os.getcwd()\n else:\n self.cwd = cwd\n self.returncode = returncode\n\n def __str__(self):\n mess = \"\"\"The following command failed\n{cmd}\nReturn code is {returncode}\nWorking dir was {cwd}\n\"\"\"\n return mess.format(cmd=self.cmd, returncode=self.returncode, cwd=self.cwd)\n\n\nclass ProcessCrashedError(Exception):\n \"\"\"An other custom exception, used by call_background \"\"\"\n def __init__(self, cmd):\n self.cmd = cmd\n\n def __str__(self):\n mess = \"%s crashed!\\n\" % os.path.basename(self.cmd[0])\n mess += \"Full command: %s\" % self.cmd\n return mess\n\nclass NotInPath(Exception):\n \"\"\"Custom exception \"\"\"\n def __init__(self, executable, env=None):\n self.executable = executable\n self.env = env\n\n def __str__(self):\n if self.env:\n path_env = self.env.get(\"PATH\")\n else:\n path_env = os.environ[\"PATH\"]\n mess = \"Could not find executable: %s\\n\" % self.executable\n mess += \"Looked in:\\n\"\n mess += \"\\n\".join(path_env.split(os.pathsep))\n return mess\n\n\ndef find_program(executable, env=None, raises=False):\n \"\"\"Get the full path of an executable by\n looking at PATH environment variable\n (and PATHEXT on windows)\n\n :return: None if program was not found,\n the full path to executable otherwize\n \"\"\"\n if executable in _FIND_PROGRAM_CACHE:\n return _FIND_PROGRAM_CACHE[executable]\n full_path = None\n res = None\n if not env:\n env = qibuild.config.get_build_env()\n if not env:\n env = os.environ\n env_path = env.get(\"PATH\", \"\")\n for path in env_path.split(os.pathsep):\n path = qibuild.sh.to_native_path(path)\n full_path = os.path.join(path, executable)\n if os.access(full_path, os.X_OK) and os.path.isfile(full_path):\n res = full_path\n break\n pathext = os.environ.get(\"PATHEXT\")\n if pathext:\n for ext in pathext.split(\";\"):\n with_ext = full_path + ext\n if os.access(with_ext, os.X_OK):\n res = qibuild.sh.to_native_path(with_ext)\n break\n if res:\n _FIND_PROGRAM_CACHE[executable] = res\n return res\n else:\n if raises:\n raise NotInPath(executable, env=env)\n return None\n\n\ndef check_output(*popenargs, **kwargs):\n \"\"\"Run command with arguments and return its output as a byte string.\n\n If the exit code was non-zero it raises a CalledProcessError. The\n CalledProcessError object will have the return code in the returncode\n attribute and output in the output attribute.\n\n The arguments are the same as for the Popen constructor. Example:\n\n >>> check_output([\"ls\", \"-l\", \"/dev/null\"])\n 'crw-rw-rw- 1 root root 1, 3 Oct 18 2007 /dev/null\\n'\n\n The stdout argument is not allowed as it is used internally.\n To capture standard error in the result, use stderr=STDOUT.\n\n >>> check_output([\"/bin/sh\", \"-c\",\n ... \"ls -l non_existent_file ; exit 0\"],\n ... stderr=STDOUT)\n 'ls: non_existent_file: No such file or directory\\n'\n \"\"\"\n if sys.version_info <= (2, 7):\n if 'stdout' in kwargs:\n raise ValueError('stdout argument not allowed, it will be overridden.')\n process = subprocess.Popen(stdout=subprocess.PIPE, *popenargs, **kwargs)\n output, unused_err = process.communicate()\n retcode = process.poll()\n if retcode:\n cmd = kwargs.get(\"args\")\n if cmd is None:\n cmd = popenargs[0]\n raise subprocess.CalledProcessError(retcode, cmd, output=output)\n return output\n else:\n return subprocess.check_output(*popenargs, **kwargs)\n\n\ndef check_is_in_path(executable, build_env=None):\n \"\"\"Check that the given executable is to be found in %PATH%\"\"\"\n if find_program(executable, env=build_env) is None:\n raise NotInPath(executable, env=build_env)\n\n\ndef call(cmd, cwd=None, env=None, ignore_ret_code=False, quiet=None):\n \"\"\" Execute a command line.\n\n If ignore_ret_code is False:\n raise CommandFailedException if returncode is None.\n Else:\n simply returns the returncode of the process\n\n Note: first arg of the cmd is assumed to be something\n inside %PATH%. (or in env[PATH] if env is not None)\n\n Note: the shell= argument of the subprocess.Popen\n call will always be False.\n\n can raise:\n * CommandFailedException if ignore_ret_code is False\n and returncode is non zero\n * NotInPath if first arg of cmd is not in %PATH%\n * And a normal exception if cwd is given and is not\n an existing directory.\n\n \"\"\"\n exe_full_path = find_program(cmd[0], env=env)\n if not exe_full_path:\n raise NotInPath(cmd[0], env=env)\n cmd[0] = exe_full_path\n\n if cwd:\n if not os.path.exists(cwd):\n # We know we are likely to have a problem on windows here,\n # so always raise.\n raise Exception(\"Trying to to run %s in non-existing %s\" %\n (\" \".join(cmd), cwd))\n\n ui.debug(\"Calling:\", \" \".join(cmd))\n ring_buffer = RingBuffer(300)\n\n returncode = 0\n if quiet:\n quiet_command = quiet\n else:\n quiet_command = CONFIG.get(\"quiet\", False)\n # This code won't work on windows with python < 2.7,\n # so quiet will be ignored\n if sys.platform.startswith(\"win\") and sys.version_info < (2, 7):\n quiet_command = False\n if not quiet_command:\n returncode = subprocess.call(cmd, env=env, cwd=cwd)\n else:\n cmdline = CommandLine(cmd, cwd=cwd, env=env)\n for(out, err) in cmdline.execute():\n if out is not None:\n ring_buffer.append(out)\n if err is not None:\n ring_buffer.append(err)\n returncode = cmdline.returncode\n\n if ignore_ret_code:\n return returncode\n\n if returncode != 0:\n if quiet_command:\n lines = ring_buffer.get()\n for line in lines:\n sys.stdout.write(line)\n sys.stdout.flush()\n # Raise correct exception\n raise CommandFailedException(cmd, returncode, cwd)\n\n\[email protected]\ndef call_background(cmd, cwd=None, env=None):\n \"\"\"\n To be used in a \"with\" statement::\n\n with call_background(...):\n do_stuff()\n\n do_other_stuff()\n\n Process is run in the background, then do_stuff()\n is called.\n\n By the time you are executing do_other_stuff(),\n you know that the process has been killed,\n better yet, if an exception has occurred during\n do_stuff, this exception is re-raised *after*\n the process has been killed.\n\n \"\"\"\n process = subprocess.Popen(cmd, cwd=cwd, env=env)\n caught_error = None\n try:\n yield\n except Exception, err:\n caught_error = err\n finally:\n try:\n if process.poll() != None:\n # Process should not have died !\n raise ProcessCrashedError(cmd)\n else:\n process.kill()\n except ProcessCrashedError, err:\n caught_error = err\n if caught_error:\n #pylint: disable-msg=E0702\n #(we are not going to raise None...)\n raise caught_error\n\n\n\n\n# This CommandLine class with an .execute generator\n# is a idea taken from Bitten (BSD license), thanks pals!\nclass CommandLine:\n \"\"\"Helper for executing subprocess\n\n \"\"\"\n def __init__(self, cmd, cwd=None, env=None):\n self.cmd = cmd\n self.cwd = cwd\n self.env = env\n\n self.returncode = None\n\n def execute(self):\n \"\"\"Execute the command, and return a generator for iterating over\n the output written to the standard output and error streams.\n\n \"\"\"\n def reader(pipe, pipe_name, queue):\n \"To be called in a thread\"\n while pipe and not pipe.closed:\n line = pipe.readline()\n if line == '':\n break\n queue.put((pipe_name, line))\n if not pipe.closed:\n pipe.close()\n ui.debug(\"Calling:\", \" \".join(self.cmd))\n process = subprocess.Popen(\n self.cmd,\n stdout=subprocess.PIPE, stderr=subprocess.PIPE,\n cwd=self.cwd,\n env=self.env)\n queue = Queue.Queue()\n\n pipe_out = threading.Thread(target=reader,\n args=(process.stdout, 'stdout', queue))\n pipe_err = threading.Thread(target=reader,\n args=(process.stderr, 'stderr', queue))\n\n pipe_out.start()\n pipe_err.start()\n\n while True:\n if process.poll() is not None and self.returncode is None:\n self.returncode = process.returncode\n try:\n name, line = queue.get(block=True, timeout=.01)\n if name == \"stderr\":\n yield(None, line)\n else:\n yield(line, None)\n except Queue.Empty:\n if self.returncode is not None:\n break\n\n pipe_out.join()\n pipe_err.join()\n\ndef configure_call(args):\n \"\"\" Configure qibuild.command.call behavoir\n from command line\n\n \"\"\"\n CONFIG[\"quiet\"] = getattr(args, \"quiet_commands\", False)\n\n\nclass RingBuffer:\n \"\"\"Quick'n dirty implementation of a ring buffer\n\n >>> rb = RingBuffer(4)\n >>> rb.append(1)\n >>> rb.get()\n [1]\n >>> rb.append(2); rb.append(3); rb.append(4)\n >>> rb.get()\n [1, 2, 3, 4]\n >>> rb.append(5)\n >>> rb.get()\n [2, 3, 4, 5]\n >>> rb.append(6)\n >>> rb.get()\n [3, 4, 5, 6]\n\n \"\"\"\n def __init__(self, size):\n self.size = size\n self._data = list()\n self._full = False\n self._index = 0\n\n def append(self, x):\n if self._full:\n self._data[self._index] = x\n else:\n self._data.append(x)\n if len(self._data) == self.size:\n self._full = True\n self._index = (self._index + 1) % self.size\n\n def get(self):\n return self._data[self._index:] + \\\n self._data[:self._index]\n"
},
{
"alpha_fraction": 0.6583769917488098,
"alphanum_fraction": 0.6714659929275513,
"avg_line_length": 33.727272033691406,
"blob_id": "21af8bc11442dc393af777300918bd57109667d0",
"content_id": "5ddc398eeed2762dcfcccd5df770eab236fd72ac",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 764,
"license_type": "permissive",
"max_line_length": 75,
"num_lines": 22,
"path": "/python/qibuild/test/test_deploy.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\n\nimport pytest\nimport qibuild.sh\nimport qibuild.deploy\n\ndef test_parse_url():\n res = qibuild.deploy.parse_url(\"[email protected]:some/really_strange-path\")\n assert res == (\"john42-bar\", \"foo.bar.com\", \"some/really_strange-path\")\n res = qibuild.deploy.parse_url(\"john@foo:\")\n assert res == (\"john\", \"foo\", \"\")\n # pylint: disable-msg=E1101\n with pytest.raises(Exception):\n qibuild.deploy.parse_url(\"john@bar\")\n\ndef test_parse_url_no_username(monkeypatch):\n monkeypatch.setenv(\"USERNAME\", \"john\")\n res = qibuild.deploy.parse_url(\"foo.bar:\")\n assert res == (\"john\", \"foo.bar\", \"\")\n"
},
{
"alpha_fraction": 0.6329271197319031,
"alphanum_fraction": 0.6341705918312073,
"avg_line_length": 43.18681335449219,
"blob_id": "e82e97d22d4421c980b719b784f562df2142b062",
"content_id": "83eaf7311fc167640221dcedf2386420f025abf6",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 4021,
"license_type": "permissive",
"max_line_length": 124,
"num_lines": 91,
"path": "/python/qibuild/actions/depends.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\n\"\"\" Display dependencies of projects\n\n\"\"\"\n\nimport qibuild\nimport qibuild.ui\nfrom qibuild.dependencies_solver import DependenciesSolver\n\ndef configure_parser(parser):\n \"\"\"Configure parser for this action\"\"\"\n qibuild.parsers.toc_parser(parser)\n qibuild.parsers.build_parser(parser)\n qibuild.parsers.project_parser(parser)\n group = parser.add_argument_group(\"depends arguments\")\n parser.add_argument(\"--reverse\", \"-r\", action=\"store_true\", help=\"display reverse dependencies\")\n parser.add_argument(\"--deep\", action=\"store_true\", help=\"display all dependencies using a depth traversal\")\n\ndef get_reverse_deps(toc, project_name):\n bproject_names = []\n rproject_names = []\n for p in toc.projects:\n dep_solver = DependenciesSolver(projects=toc.projects, packages=toc.packages, active_projects=toc.active_projects)\n (bp, _, _) = dep_solver.solve([p.name], runtime=False)\n (rp, _, _) = dep_solver.solve([p.name], runtime=True)\n if project_name in bp:\n bproject_names.append(p.name)\n if project_name in rp:\n rproject_names.append(p.name)\n return (bproject_names, rproject_names, set(), set())\n\ndef get_deps(toc, project_name):\n dep_solver = DependenciesSolver(projects=toc.projects, packages=toc.packages, active_projects=toc.active_projects)\n (bproject_names, bpackage_names, _) = dep_solver.solve([project_name], runtime=False)\n (rproject_names, rpackage_names, _) = dep_solver.solve([project_name], runtime=True)\n return (bproject_names, rproject_names, bpackage_names, rpackage_names)\n\ndef do(args):\n \"\"\"Main entry point\"\"\"\n logger = qibuild.log.get_logger(__name__)\n toc = qibuild.toc_open(args.worktree, args)\n\n qibuild.ui.info(\"legend:\",\n qibuild.ui.red , \"buildtime\",\n qibuild.ui.white, \"buildtime+runtime\",\n qibuild.ui.green, \"runtime\")\n qibuild.ui.info()\n\n active_projects = toc.active_projects\n if args.deep and not args.reverse:\n (active_projects, _, _) = toc.resolve_deps()\n elif args.deep and args.reverse:\n qibuild.ui.error(\"you can't use --deep with --reverse.\")\n exit(1)\n for pname in active_projects:\n project = toc.get_project(pname)\n if args.reverse:\n qibuild.ui.info(qibuild.ui.green, \"*\", qibuild.ui.blue, project.name, qibuild.ui.reset, \"reverse dependencies:\")\n else:\n qibuild.ui.info(qibuild.ui.green, \"*\", qibuild.ui.blue, project.name, qibuild.ui.reset, \"dependencies:\")\n\n if args.reverse:\n (bproject_names, rproject_names,\n bpackage_names, rpackage_names) = get_reverse_deps(toc, pname)\n else:\n (bproject_names, rproject_names,\n bpackage_names, rpackage_names) = get_deps(toc, pname)\n\n bproject_names = set(bproject_names) - set([pname])\n rproject_names = set(rproject_names) - set([pname])\n\n brproject_names = set(bproject_names).intersection(set(rproject_names))\n brpackage_names = set(bpackage_names).intersection(set(rpackage_names))\n\n bproject_names = set(bproject_names) - set(brproject_names)\n rproject_names = set(rproject_names) - set(brproject_names)\n\n bpackage_names = set(bpackage_names) - set(brpackage_names)\n rpackage_names = set(rpackage_names) - set(brpackage_names)\n\n qibuild.ui.info(\" projects:\",\n qibuild.ui.red , \" \".join(bproject_names),\n qibuild.ui.white, \" \".join(brproject_names),\n qibuild.ui.green, \" \".join(rproject_names))\n qibuild.ui.info(\" packages:\",\n qibuild.ui.red , \" \".join(bpackage_names),\n qibuild.ui.white, \" \".join(brpackage_names),\n qibuild.ui.green, \" \".join(rpackage_names))\n"
},
{
"alpha_fraction": 0.6308952569961548,
"alphanum_fraction": 0.6340016722679138,
"avg_line_length": 36.273685455322266,
"blob_id": "23985ecc4947111b7eabdf8912d00de96ff8eade",
"content_id": "4f109327d00dc669f88f0c0aff02e3de442f379d",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3541,
"license_type": "permissive",
"max_line_length": 82,
"num_lines": 95,
"path": "/python/qitoolchain/actions/convert_package.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\n\"\"\"Convert a package (binary archive or install directory) into a qiBuild package.\n\n\"\"\"\n\nimport os\n\nimport qibuild\nfrom qitoolchain.binary_package import open_package\nfrom qitoolchain.binary_package import convert_to_qibuild\n\ndef configure_parser(parser):\n \"\"\"Configure parser for this action \"\"\"\n qibuild.parsers.toc_parser(parser)\n parser.add_argument(\"package_name\", metavar='NAME',\n help=\"The name of the package\", nargs='?')\n parser.add_argument(\"package_path\", metavar='PACKAGE_PATH',\n help=\"\"\"\\\nThe path to the package (archive or root install directory) to be convert.\nIf PACKAGE_PATH points to a directory, then NAME is a mandatory.\"\"\")\n parser.add_argument(\"-d\", \"--directory\", dest=\"dest_dir\",\n metavar='DESTDIR',\n help=\"qiBuild package destination directory \\\n (default: aside the original package)\")\n parser.add_argument(\"-b\", \"--batch\", dest=\"batch\", action=\"store_true\",\n default=False, help=\"enable non-interactive mode\")\n return\n\n\ndef do(args):\n \"\"\"Convert a package (binary archive or install directory) into a\n qiBuild package.\n\n - Check that there is a CMake module for this binary package\n (provided by the package itself or qiBuild)\n - If not CMake module for the package, then generate it\n - Turn the file tree into a qiBuild package\n - Build a qiBuild package\n\n \"\"\"\n package_name = args.package_name\n package_path = os.path.abspath(args.package_path)\n dest_dir = args.dest_dir\n interactive = not args.batch\n other_names = list()\n if dest_dir is None:\n dest_dir = os.path.dirname(package_path)\n if os.path.isdir(package_path):\n if package_name is None:\n message = \"\"\"\nError: when turning an install directory into a qiBuild package,\na package name must be passed to the command line.\n\"\"\"\n raise Exception(message)\n package = package_path\n else:\n package = open_package(package_path)\n package_metadata = package.get_metadata()\n if package_name is None:\n package_name = package_metadata['name']\n other_names.append(package_metadata['name'])\n other_names.append(package_name)\n other_names = list(set(other_names))\n message = \"\"\"\nConverting '{0}' into a qiBuild package ...\n\"\"\".format(package_path)\n qibuild.ui.info(message)\n\n with qibuild.sh.TempDir() as tmp:\n conversion = convert_to_qibuild(tmp, package, package_name,\n other_names=other_names,\n interactive=interactive)\n qibuild_package_path = conversion[0]\n modules_package = conversion[1]\n modules_qibuild = conversion[2]\n src = os.path.abspath(qibuild_package_path)\n dst = os.path.join(dest_dir, os.path.basename(qibuild_package_path))\n dst = os.path.abspath(dst)\n qibuild.sh.mkdir(dest_dir, recursive=True)\n qibuild.sh.rm(dst)\n qibuild.sh.mv(src, dst)\n qibuild_package_path = dst\n message = \"\"\"\\\nConversion succedded.\n\nqiBuild package:\n {1}\n\nYou can add this qiBuild package to a toolchain using:\n qitoolchain -c <toolchain name> {0} {1}\\\n\"\"\".format(package_name, qibuild_package_path)\n qibuild.ui.info(message)\n"
},
{
"alpha_fraction": 0.6666666865348816,
"alphanum_fraction": 0.6666666865348816,
"avg_line_length": 13.25,
"blob_id": "e46d405d1d9821895cc0f19e06bf3aee86157bbc",
"content_id": "2617410c0d6e4fe86cfd1b18479941de80360f66",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "INI",
"length_bytes": 57,
"license_type": "permissive",
"max_line_length": 20,
"num_lines": 4,
"path": "/coverage.ini",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "[run]\nsource = python\nomit = python/.tox/*\nbranch = True\n"
},
{
"alpha_fraction": 0.5858407020568848,
"alphanum_fraction": 0.5911504626274109,
"avg_line_length": 19.071428298950195,
"blob_id": "5a4138dd090e2d8b15e7838ff47845b42db6663f",
"content_id": "5fe49d3c057bf51766e01502b0210aa17d874dab",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 565,
"license_type": "permissive",
"max_line_length": 65,
"num_lines": 28,
"path": "/doc/source/ref/python/packages/qibuild/ui.rst",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "qibuild.ui -- Tools for the command line user interface\n=======================================================\n\n.. py:module:: qibuild.ui\n\nOutput messages for the user\n----------------------------\n\n.. autofunction:: error\n\n.. autofunction:: warning\n\n.. autofunction:: info\n\n.. autofunction:: debug\n\nYou can use each of this functions as you would do for the\n``print`` function in Python3.\n\nTo add colors, use the various colors defined in ``qibuild.ui``\n\n\nExample ::\n\n\n from qibuild import ui\n\n ui.info(ui.green, \"*\", ui.bold, \"(1/1)\", ui.blue, project_name)\n\n\n\n"
},
{
"alpha_fraction": 0.5900276899337769,
"alphanum_fraction": 0.5927977561950684,
"avg_line_length": 32.976470947265625,
"blob_id": "128ecf0ca0c455008f1cf38ab00f60ea7022c9dd",
"content_id": "83b49086dac4492e0d3b6f3c73caac651434f3f5",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2888,
"license_type": "permissive",
"max_line_length": 92,
"num_lines": 85,
"path": "/python/qibuild/gdb.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\n\"\"\" Tools for the GNU debbugger\n\n\"\"\"\n\nimport os\n\nfrom qibuild import ui\nimport qibuild.sh\nimport qibuild.command\n\n\ndef split_debug(base_dir, objcopy=None):\n \"\"\" Split the debug information out of all the binaries in\n lib/ and bin/\n\n The debug information will be put in a .debug directory next\n to the executable\n\n <base_dir>/bin/foo\n <base_dir>/bin/.debug/foo\n\n Also uses objcopy so that the binaries and libraries still remain\n usable with gdb\n\n :param: the objcopy executable to use. (defaults to\n the first objcopy executable found in PATH)\n\n\n \"\"\"\n if objcopy is None:\n objcopy = \"objcopy\"\n def _get_binaries(path):\n res = list()\n for root, _, filenames in os.walk(path):\n if os.path.basename(root) == \".debug\":\n continue\n for filename in filenames:\n full_path = os.path.join(root, filename)\n if qibuild.sh.is_binary(full_path):\n res.append(full_path)\n return res\n binaries = list()\n bin_dir = os.path.join(base_dir, \"bin\")\n lib_dir = os.path.join(base_dir, \"lib\")\n binaries.extend(_get_binaries(bin_dir))\n binaries.extend(_get_binaries(lib_dir))\n\n for src in binaries:\n dirname, basename = os.path.split(src)\n debug_dir = os.path.join(dirname, \".debug\")\n qibuild.sh.mkdir(debug_dir)\n dest = os.path.join(src, debug_dir, basename)\n to_run = list()\n to_run.append([objcopy, \"--only-keep-debug\", src, dest])\n to_run.append([objcopy, \"--strip-debug\", \"--strip-unneeded\",\n \"--add-gnu-debuglink=%s\" % dest, src])\n retcode = 0\n #check if we need to do something\n #if mtime of src and dest are the same continue, else do the work and set\n #the mtime of dest to the one of src.\n stsrc = os.stat(src)\n stdst = None\n if os.path.exists(dest):\n stdst = os.stat(dest)\n if stdst and stsrc.st_mtime == stdst.st_mtime:\n ui.info(\"Debug info up-to-date for %s\" % os.path.relpath(src, base_dir))\n continue\n for cmd in to_run:\n retcode = 0\n # FIXME: we should of course not try to split debug info twice, but\n # that's a hard problem\n retcode += qibuild.command.call(cmd, ignore_ret_code=True, quiet=True)\n if retcode == 0:\n os.utime(dest, (stsrc.st_atime, stsrc.st_mtime))\n ui.info(\"Debug info extracted for %s\" % os.path.relpath(src, base_dir))\n else:\n ui.error(\"Error while extracting debug for %s\" % os.path.relpath(src, base_dir))\n\nif __name__ == \"__main__\":\n import sys\n split_debug(sys.argv[1])\n"
},
{
"alpha_fraction": 0.7301990389823914,
"alphanum_fraction": 0.7301990389823914,
"avg_line_length": 27.10714340209961,
"blob_id": "1c998a8a5311b9172211f1df6e00c9fec283436e",
"content_id": "1ed07deb70dd4be73e463b34f20804903a5ba742",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "reStructuredText",
"length_bytes": 2363,
"license_type": "permissive",
"max_line_length": 79,
"num_lines": 84,
"path": "/doc/source/guide/overview/building_a_project.rst",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": ".. _qibuild-building-project:\n\nBuilding a project\n==================\n\n\nSimple build\n------------\n\nLet’s assume you only want to compile your project once.\n\nDoing so is easy:\n\n.. code-block:: console\n\n $ qibuild make foo\n\nOr, to build in release, use:\n\n.. code-block:: console\n\n $ qibuild make --release foo\n\nUsing an IDE\n------------\n\nqiBuild is based on CMake, which in turns knows how to generate project files\nfor many of IDEs : XCode, Eclipse, Visual Studio.\n\nHere we are only dealing with the details for:\n\n* QtCreator on Mac and Linux\n\n* Visual Studio on Windows.\n\nqiBuild is known to work fine with these IDEs, there may be some work to do to\nbe able to use XCode or Eclipse. Patches and tutorials welcome !\n\nqiBuild and QtCreator\n+++++++++++++++++++++\n\nThe only thing to remember is that you should not let QtCreator call CMake by\nitself the first time.\n\nUse ``qibuild configure`` then ``qibuild make`` to be sure everything works\nfine.\n\nThen open the root CMakeLists in qtcreator.\n\nYou will be prompted to use a build directory, chose the one that was created\nby qibuild.\n\nQtCreator will read the settings from the exising build directory, so\neverything should work fine.\n\nRemember to use the same CMake generator in QtCreator and in your configuration\nfile, if qtcreator asks you to choose one.\n\nNote: If QtCreator does not ask you for a build directory, one way to force it\ndo to so is deleting the ``CMakeLists.txt.user`` file.\n\nqiBuild and Visual Studio\n+++++++++++++++++++++++++\n\nWhen you have run ``qibuild configure``, you will have a .sln file generated in\nyour build directory.\n\nYour solution should already be properly configured. Please avoid making\nchanges to the solution file by hand, they will be lost the next time you\nchange a CMake file or run CMake. To keep your project cross-platform and\nsharable with others you are strongly advised to use your CMakeLists.txt to\nmake any changes to your solution. After each change of your CMakeLists.txt,\nrun qibuild configure to update your solution file.\n\n.. note:: The .sln generated by CMake is also capable to run CMake to\n re-generate itself. This sadly does not always work, so if you\n experience trouble, it's best to close the project,\n then re-run ``qibuild configure`` by hand\n\n\nUsing Aldebaran packages\n-------------------------\n\nSee: :ref:`qibuild-using-aldebaran-packages`\n"
},
{
"alpha_fraction": 0.6190544962882996,
"alphanum_fraction": 0.6210846900939941,
"avg_line_length": 35.680850982666016,
"blob_id": "2f4096ec18765b509d7cc9d272a41d7e76fdb754",
"content_id": "9d29d5ec9c7cc6f451e5529a311d2a09a7528704",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 6896,
"license_type": "permissive",
"max_line_length": 82,
"num_lines": 188,
"path": "/python/qitoolchain/binary_package/__init__.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\n\"\"\"This module contains function to import binary packages in qiBuild\ntoolchains.\n\nqiBuild toolchains contain a set of packages which can be extended.\n\nThis module provides utility functions to import binary packages used by some\nother compatible distribution into a qiBuild toolchain.\n\nAll qiBuild packages should have the same layout.\n\"\"\"\n\nimport os\n\nimport qibuild\nimport qibuild.cmake.modules as cmake_modules\nfrom qitoolchain.binary_package.core import BinaryPackage\nfrom qitoolchain.binary_package.core import BinaryPackageException\n\nWITH_PORTAGE = True\ntry:\n import portage\nexcept ImportError:\n WITH_PORTAGE = False\n\nif WITH_PORTAGE:\n from qitoolchain.binary_package.gentoo_portage import GentooPackage\nelse:\n from qitoolchain.binary_package.gentoo import GentooPackage\n\n_PKG_TYPES = {\n 'gentoo': {\n 'extension': '.tbz2',\n 'class': GentooPackage,\n },\n # Not yet implemented, so use the default Package class\n 'debian': {\n 'extension': '.deb',\n 'class': BinaryPackage,\n },\n 'redhat': {\n 'extension': '.rpm',\n 'class': BinaryPackage,\n },\n 'archlinux': {\n 'extension': '.pkg.tar.xz',\n 'class': BinaryPackage,\n },\n}\n\n\ndef _guess_package_type(package_path):\n for typename, data in _PKG_TYPES.iteritems():\n if package_path.endswith(data.get('extension')):\n return typename\n return None\n\n\ndef open_package(package_path):\n \"\"\" Open the given binary package.\n\n :return: A ``Package`` instance\n\n \"\"\"\n if not os.path.exists(package_path):\n mess = \"No such file or directory: {0}\".format(package_path)\n raise SystemError(mess)\n package = None\n typename = _guess_package_type(package_path)\n if typename is None:\n mess = \"Unknown package type\"\n raise BinaryPackageException(mess)\n generator = _PKG_TYPES.get(typename).get('class')\n package = generator(package_path)\n return package\n\n\ndef _fix_package_tree(root_dir):\n \"\"\" Make the package tree comply with qiBuild.\n\n \"\"\"\n usr_dir = os.path.join(root_dir, 'usr')\n if not os.path.exists(usr_dir):\n return\n for item in os.listdir(usr_dir):\n src = os.path.join(root_dir, 'usr', item)\n dst = os.path.join(root_dir, item)\n if os.path.exists(dst):\n mess = \"Destination already exists\"\n raise Exception(mess)\n qibuild.sh.mv(src, dst)\n qibuild.sh.rm(os.path.join(root_dir, 'usr'))\n return\n\n\ndef convert_to_qibuild(dest_dir, package, package_name, other_names=None,\n package_metadata=None, interactive=True):\n \"\"\" Convert a binary package into a qiBuild package.\n\n :param dest_dir: destination directory for the converted qiBuild\n package\n :param package: input package to be converted, it could be either a\n path to a directory, or a path to a archive, or an\n instance of qitoolchain.binary_package.BinaryPackage.\n :param package_name: name of the qiBuild package\n :param other_name: other names which could match existing CMake modules\n\n :return: tuple (path to the qiBuild package,\n list of CMake module found in the package,\n list of CMake module provided by qiBuild)\n\n \"\"\"\n modules_package = list()\n modules_qibuild = list()\n qipkg_path = None\n pkg_names = list()\n if other_names is not None:\n pkg_names.extend(other_names)\n pkg_names.append(package_name)\n pkg_names = list(set(pkg_names))\n if isinstance(package, BinaryPackage):\n package_type = \"binpkg_object\"\n elif os.path.exists(package) and os.path.isdir(package):\n package_type = \"directory\"\n elif os.path.exists(package) and os.path.isdir(package):\n package = open_package(package)\n package_type = \"binpkg_object\"\n else:\n message = \"\"\"\nunsupported operand type: {0} (type: {1})\n\"\"\".format(str(package), type(package))\n raise TypeError(message)\n if package_type == \"binpkg_object\" and not package_metadata:\n package_metadata = package.get_metadata()\n with qibuild.sh.TempDir() as work_dir:\n if package_type == \"binpkg_object\":\n root_dir = package.extract(work_dir)\n elif package_type == \"directory\":\n root_dir = os.path.join(work_dir, os.path.basename(package))\n qibuild.sh.install(package, root_dir, quiet=True)\n else:\n message = \"Unsupported package type: {0}\".format(package_type)\n raise RuntimeError(message)\n top_dir = os.path.basename(root_dir)\n pkg_names.append(top_dir)\n pkg_names = list(set(pkg_names))\n _fix_package_tree(root_dir)\n path_list = qibuild.sh.ls_r(root_dir)\n checks = cmake_modules.check_for_module_generation(pkg_names,\n path_list=path_list)\n module_status = checks[0]\n modules_package = checks[1]\n modules_qibuild = checks[2]\n need_generation = module_status == \"nonexistent\"\n cmake_modules.show_exiting_modules(package_name, modules_package,\n modules_qibuild)\n if interactive and module_status == \"provided_by_qibuild\":\n question = \"\"\"\\\nDo you want to generate a CMake module for {0},\nthough some from qiBuild may already exist for this package?\\\n\"\"\".format(package_name)\n need_generation = qibuild.interact.ask_yes_no(question, default=False)\n cmake_module = cmake_modules.CMakeModule(name=package_name)\n if need_generation:\n cmake_module.generate_from_directory(root_dir, package_name,\n path_list=path_list,\n interactive=interactive)\n cmake_module.write(root_dir)\n qipkg_name = cmake_module.name\n if package_metadata:\n for key in ['version', 'revision', 'arch', 'arch_variant']:\n if key in package_metadata and package_metadata[key]:\n qipkg_name += \"-{0}\".format(package_metadata[key])\n if top_dir != qipkg_name:\n src = root_dir\n dst = os.path.join(os.path.dirname(root_dir), qipkg_name)\n qibuild.sh.mv(src, dst)\n root_dir = dst\n qipkg_path = qibuild.archive.compress(root_dir, algo=\"zip\", quiet=True)\n src = qipkg_path\n dst = os.path.join(dest_dir, os.path.basename(qipkg_path))\n qibuild.sh.rm(dst)\n qibuild.sh.mv(src, dst)\n qipkg_path = os.path.abspath(dst)\n return (qipkg_path, modules_package, modules_qibuild)\n"
},
{
"alpha_fraction": 0.5711188912391663,
"alphanum_fraction": 0.5714523792266846,
"avg_line_length": 32.40668487548828,
"blob_id": "5b07d4254b2f89bf83b7258c281f415d418e2d07",
"content_id": "6077cb72b59baa8677fcea586ab0befba1c92940",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 11994,
"license_type": "permissive",
"max_line_length": 90,
"num_lines": 359,
"path": "/python/qidoc/core.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\n\"\"\" This package contains the QiDoc object\n\n\"\"\"\nimport os\nimport sys\nimport pprint\nimport webbrowser\n\nimport qisrc\n\nfrom qibuild import ui\nimport qibuild\nfrom qibuild.dependencies_solver import topological_sort\nimport qidoc.config\nimport qidoc.sphinx\nimport qidoc.doxygen\n\n\nclass QiDocBuilder:\n \"\"\" A class to handle doc generation of several\n projects\n\n \"\"\"\n def __init__(self, in_dir, out_dir=\"build-doc\"):\n self.worktree = qisrc.worktree.open_worktree(in_dir)\n self.in_dir = in_dir\n self.out_dir = out_dir\n # Set during configure_all()\n self.opts = dict()\n\n self.templates_path = None\n self.sphinxdocs = dict()\n self.doxydocs = dict()\n\n # Will fill up self.templates_path, self.sphinxdocs and self.doxydocs\n self._load_doc_projects()\n self.deps_tree = self.get_deps_tree()\n ui.debug(\"QiDocBuilder dep tree: \", pprint.pformat(self.deps_tree))\n\n if not self.templates_path:\n mess = \"Could not find any template repo\\n\"\n mess += \"Please make sure that one of the qiproject.xml looks like:\\n\"\n mess += '<qiproject template_repo=\"yes\" />\\n'\n raise Exception(mess)\n self.doxytags_path = os.path.join(self.out_dir, \"doxytags\")\n\n def get_deps_tree(self):\n \"\"\" Get the tree of dependencies\n\n It is a dict {type:deps_tree} where\n type is 'sphinx' or 'doxygen', and\n deps_tree is a dict:\n {name:[dep names]}\n \"\"\"\n doxy_tree = dict()\n sphinx_tree = dict()\n res = dict()\n for doxydoc in self.doxydocs.values():\n doxy_tree[doxydoc.name] = doxydoc.depends\n # Check that every dep exists:\n for dep in doxydoc.depends:\n if self.get_doc(\"doxygen\", dep) is None:\n mess = \"Could not find doxygen doc dep: %s\\n\" % dep\n mess += \"(brought by: %s)\" % doxydoc.name\n ui.warning(mess)\n doxydoc.depends.remove(dep)\n\n for sphinxdoc in self.sphinxdocs.values():\n sphinx_tree[sphinxdoc.name] = sphinxdoc.depends\n # Check that every dep exists:\n for dep in sphinxdoc.depends:\n if self.get_doc(\"sphinx\", dep) is None:\n mess = \"Could not find sphinx doc dep %s\\n\" % dep\n mess += \"(brought by: %s)\" % sphinxdoc.name\n ui.warning(mess)\n sphinxdoc.depends.remove(dep)\n\n res[\"doxygen\"] = doxy_tree\n res[\"sphinx\"] = sphinx_tree\n return res\n\n\n def configure_all(self, opts):\n \"\"\" Configure every projects.\n\n Always called before building anything\n\n \"\"\"\n version = opts.get(\"version\")\n if not version:\n raise Exception(\"opts dict must at least contain a 'version' key\")\n\n self.opts = opts.copy()\n qibuild.sh.mkdir(self.doxytags_path, recursive=True)\n doxylink = dict()\n\n doxydocs = self.sort_doxygen()\n for doxydoc in doxydocs:\n doxygen_mapping = self.get_doxygen_mapping(doxydoc.name)\n qidoc.doxygen.configure(doxydoc.src,\n self.templates_path,\n opts,\n project_name=doxydoc.name,\n doxytags_path=self.doxytags_path,\n doxygen_mapping=doxygen_mapping)\n\n tag_file = os.path.join(self.doxytags_path, doxydoc.name + \".tag\")\n # Store full path here because we'll need to compute\n # a relative path later\n doxylink[doxydoc.name] = (tag_file, doxydoc.dest)\n\n sphinxdocs = self.sort_sphinx()\n for sphinxdoc in sphinxdocs:\n intersphinx_mapping = self.get_intersphinx_mapping(sphinxdoc.name)\n qidoc.sphinx.configure(sphinxdoc.src, sphinxdoc.dest,\n self.templates_path,\n intersphinx_mapping,\n doxylink,\n opts)\n qidoc.sphinx.gen_download_zips(sphinxdoc.src)\n\n def build_all(self, opts):\n \"\"\" Build everything\n\n \"\"\"\n self.configure_all(opts)\n doxydocs = self.sort_doxygen()\n for doxydoc in doxydocs:\n qidoc.doxygen.build(doxydoc.src, doxydoc.dest, opts)\n sphinxdocs = self.sort_sphinx()\n for sphinxdoc in sphinxdocs:\n qidoc.sphinx.build(sphinxdoc.src, sphinxdoc.dest, opts)\n\n\n def build_single(self, project, opts):\n \"\"\" Used to build a single project\n\n \"\"\"\n sphinx = self.get_doc(\"sphinx\", project)\n doxy = self.get_doc(\"doxygen\", project)\n\n if sphinx is None and doxy is None:\n raise Exception(\"No such project: %s\" % project)\n\n self.configure_all(opts)\n\n if sphinx:\n qidoc.sphinx.build(sphinx.src, sphinx.dest, opts)\n if doxy:\n qidoc.doxygen.build(doxy.src, doxy.dest, opts)\n\n\n def open_main(self):\n \"\"\" Used to open main doc. We assume one of the project\n as a dest equals to \".\"\n\n \"\"\"\n index_html = os.path.join(self.out_dir, \"index.html\")\n print \"Opening\", index_html, \"in a web browser\"\n if sys.platform == \"darwin\":\n index_html = \"file://\" + index_html\n webbrowser.open(index_html)\n\n def open_single(self, project):\n \"\"\" User to open a single doc\n\n \"\"\"\n\n doc_proj = self.get_doc(\"sphinx\", project)\n if not doc_proj:\n doc_proj = self.get_doc(\"doxygen\", project)\n if not doc_proj:\n raise Exception(\"No such project: %s\" % project)\n\n index_html = os.path.join(doc_proj.dest, \"index.html\")\n print \"Opening\", index_html, \"in a web browser\"\n if sys.platform == \"darwin\":\n index_html = \"file://\" + index_html\n webbrowser.open(index_html)\n\n def sort_doxygen(self):\n \"\"\" Get a list of doxygen docs to build\n\n \"\"\"\n deps_tree = self.deps_tree[\"doxygen\"]\n doc_names = topological_sort(deps_tree, self.doxydocs.keys())\n res = [self.get_doc(\"doxygen\", d) for d in doc_names]\n return res\n\n def sort_sphinx(self):\n \"\"\" Get a list of sphinx docs to build, in the\n correct order\n\n \"\"\"\n deps_tree = self.deps_tree[\"sphinx\"]\n doc_names = topological_sort(deps_tree, self.sphinxdocs.keys())\n res = [self.get_doc(\"sphinx\", d) for d in doc_names]\n return res\n\n def get_intersphinx_mapping(self, name):\n \"\"\" Get the relevant intersphinx_mapping for\n the given name\n\n \"\"\"\n res = dict()\n deps_tree = self.deps_tree[\"sphinx\"]\n doc_names = topological_sort(deps_tree, [name])\n docs = [self.get_doc(\"sphinx\", d) for d in doc_names]\n for doc in docs:\n # Remove self from the list:\n if doc.name != name:\n res[doc.name] = (doc.dest, None)\n return res\n\n def get_doxygen_mapping(self, name):\n \"\"\" Get the relevant Doxygen TAGFILES setting\n\n \"\"\"\n doc = self.get_doc(\"doxygen\", name)\n res = dict()\n deps_tree = self.deps_tree[\"doxygen\"]\n dep_doc_names = topological_sort(deps_tree, [name])\n dep_docs = [self.get_doc(\"doxygen\", d) for d in dep_doc_names]\n for dep_doc in dep_docs:\n # Remove self from the list\n if dep_doc.name == name:\n continue\n doxytag_file = os.path.join(self.doxytags_path,\n dep_doc.name + \".tag\")\n dep_dest = dep_doc.dest\n rel_path = os.path.relpath(dep_dest, doc.dest)\n res[doxytag_file] = rel_path\n\n return res\n\n\n def get_doc(self, type_, name):\n \"\"\" Retun a qibuild.config.SphinxDoc or a\n qidoc.config.DoxyDoc object\n\n \"\"\"\n if type_ == \"doxygen\":\n return self.doxydocs.get(name)\n if type_ == \"sphinx\":\n return self.sphinxdocs.get(name)\n\n def _load_doc_projects(self):\n \"\"\" Explore the qibuild projects, building the\n sphinxdocs and doxydocs attributes\n\n \"\"\"\n for project in self.worktree.projects:\n qiproj_xml = os.path.join(project.path, \"qiproject.xml\")\n if not os.path.exists(qiproj_xml):\n continue\n (doxydocs, sphinxdocs) = qidoc.config.parse_project_config(qiproj_xml)\n # Fixup src, dest attributes:\n for doxydoc in doxydocs:\n self.set_paths(project, doxydoc)\n self.check_collision(doxydoc, \"doxygen\")\n self.doxydocs[doxydoc.name] = doxydoc\n for sphinxdoc in sphinxdocs:\n self.set_paths(project, sphinxdoc)\n self.check_collision(sphinxdoc, \"sphinx\")\n self.sphinxdocs[sphinxdoc.name] = sphinxdoc\n # Check if the project is a template project:\n self.check_template(project.path, qiproj_xml)\n\n\n def set_paths(self, worktree_project, doc_project):\n \"\"\" Set src and dest attributes of the doc project\n\n \"\"\"\n src = os.path.join(worktree_project.path, doc_project.src)\n doc_project.src = qibuild.sh.to_native_path(src)\n dest = os.path.join(self.out_dir, doc_project.dest)\n doc_project.dest = qibuild.sh.to_native_path(dest)\n\n def check_collision(self, project, doc_type):\n \"\"\"\" Check for collision between doc projects\n\n \"\"\"\n name = project.name\n if doc_type == \"doxygen\":\n other_project = self.doxydocs.get(name)\n elif doc_type == \"sphinx\":\n other_project = self.sphinxdocs.get(name)\n\n if not other_project:\n return\n\n mess = \"Two %s projects have the same name: %s\\n\" % (doc_type, name)\n mess += \"First project is in: %s\\n\" % other_project.path\n mess += \"Other project is in: %s\\n\" % project.path\n mess += \"Please check your configuration\"\n raise Exception(mess)\n\n def check_template(self, p_path, qiproj_xml):\n \"\"\" Check whether a project is a template project\n If not templates project has been found yet, set\n self.templates_path, else raise an exception\n\n \"\"\"\n is_template = qidoc.config.is_template(qiproj_xml)\n if not is_template:\n return\n if self.templates_path:\n mess = \"Could not add project in %s\" % (p_path)\n mess += \"as a template repository.\\n\"\n mess += \"There is already a template repository in %s\\n\" % self.templates_path\n mess += \"Please check your configuration\"\n raise Exception(mess)\n self.templates_path = p_path\n\n def project_from_cwd(self, cwd=None):\n \"\"\" Get a doc project name from the current working dir\n\n \"\"\"\n if not cwd:\n cwd = os.getcwd()\n\n for doxydoc in self.doxydocs.values():\n if doxydoc.src in cwd:\n return doxydoc.name\n for sphinxdoc in self.sphinxdocs.values():\n if sphinxdoc.src in cwd:\n return sphinxdoc.name\n\n\ndef find_qidoc_root(cwd=None):\n \"\"\" Find a qidoc root\n\n \"\"\"\n if not cwd:\n cwd = os.getcwd()\n dirname = None\n while dirname or cwd:\n if os.path.exists(os.path.join(cwd, \".qi\", \"worktree.xml\")):\n return cwd\n (new_cwd, dirname) = os.path.split(cwd)\n if new_cwd == cwd:\n return\n cwd = new_cwd\n\ndef create_builder(worktree=None):\n \"\"\" Open a new QiDocBuilder using\n os.getcwd and looking for a qidoc.xml if root is None\n\n \"\"\"\n if worktree is None:\n worktree = find_qidoc_root(os.getcwd())\n if not worktree:\n raise Exception(\"Could not find qidoc worktree\")\n builder = QiDocBuilder(worktree)\n return builder\n\n"
},
{
"alpha_fraction": 0.5410019755363464,
"alphanum_fraction": 0.5572348237037659,
"avg_line_length": 24.161972045898438,
"blob_id": "4075c1b9e8c5ddbf81df15533e4247bfa637910f",
"content_id": "b006bcd66f6d7ae6c9317c0aa6c04ab5000fdaa0",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 3573,
"license_type": "permissive",
"max_line_length": 73,
"num_lines": 142,
"path": "/python/qibuild/ui.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\n\n# Colorized output to console code inspired by\n# pygments (http://pygments.org/) BSD License.\n\n\"\"\" Tools for a nice user interface\n\n\"\"\"\n\nimport sys\nimport datetime\n\nON_WIN = sys.platform.startswith(\"win\")\n\n# Try using pyreadline so that we can\n# have colors on windows, too.\n_console = None\nHAS_PYREADLINE = True\nif ON_WIN:\n try:\n # pylint: disable-msg=F0401\n from pyreadline.console import Console\n _console = Console()\n except ImportError:\n HAS_PYREADLINE = False\n\n# ANSI color codes, as classes,\n# so that we can use ::\n#\n# qibuild.ui.msg(\"qibuild.ui.bold, \"This is bold\", qibuild.ui.reset)`\nclass _Color:\n def __init__(self, code):\n self.code = code\n\n_esc = \"\\033[\"\n\nreset = _Color(_esc + \"0m\")\nbold = _Color(_esc + \"1m\")\nfaint = _Color(_esc + \"2m\")\nstandout = _Color(_esc + \"3m\")\nunderline = _Color(_esc + \"4m\")\nblink = _Color(_esc + \"5m\")\noverline = _Color(_esc + \"6m\")\n\nblack = _Color(_esc + \"30m\")\ndarkred = _Color(_esc + \"31m\")\ndarkgreen = _Color(_esc + \"32m\")\nbrown = _Color(_esc + \"33m\")\ndarkblue = _Color(_esc + \"34m\")\npurple = _Color(_esc + \"35m\")\nteal = _Color(_esc + \"36m\")\nlightgray = _Color(_esc + \"37m\")\n\ndarkgray = _Color(_esc + \"30;1m\")\nred = _Color(_esc + \"31;1m\")\ngreen = _Color(_esc + \"32;1m\")\nyellow = _Color(_esc + \"33;1m\")\nblue = _Color(_esc + \"34;1m\")\nfuchsia = _Color(_esc + \"35;1m\")\nturquoise = _Color(_esc + \"36;1m\")\nwhite = _Color(_esc + \"37;1m\")\n\ndarkteal = turquoise\ndarkyellow = brown\nfuscia = fuchsia\n\n\n# Global variable to store qibuild.ui configuration\n\nCONFIG = {\n \"verbose\" : False,\n \"quiet\" : False,\n \"color\" : True,\n \"timestamp\" : False\n}\n\n\n\ndef _msg(*tokens, **kwargs):\n \"\"\" Helper method for error, warning, info, debug\n\n \"\"\"\n fp = kwargs.get(\"fp\", sys.stdout)\n sep = kwargs.get(\"sep\", \" \")\n end = kwargs.get(\"end\", \"\\n\")\n with_color = CONFIG[\"color\"]\n if ON_WIN and not HAS_PYREADLINE or not fp.isatty():\n with_color = False\n if CONFIG[\"timestamp\"]:\n now = datetime.datetime.now()\n res = now.strftime(\"[%Y-%m-%d %H:%M:%S] \")\n else:\n res = \"\"\n for i, token in enumerate(tokens):\n if not token:\n continue\n if isinstance(token, _Color):\n if with_color:\n res += token.code\n else:\n if sep == \" \" and token == \"\\n\":\n res += \"\\n\"\n else:\n res += str(token)\n res += sep\n # always reset:\n if with_color:\n res += reset.code\n res += end\n if _console and with_color:\n _console.write_color(res)\n else:\n fp.write(res)\n fp.flush()\n\ndef error(*tokens, **kwargs):\n \"\"\" Print an error message \"\"\"\n tokens = [bold, red, \"[ERROR]: \"] + list(tokens)\n kwargs[\"fp\"] = sys.stderr\n _msg(*tokens, **kwargs)\n\ndef warning(*tokens, **kwargs):\n \"\"\" Print a warning message \"\"\"\n tokens = [brown, \"[WARN ]: \"] + list(tokens)\n kwargs[\"fp\"] = sys.stderr\n _msg(*tokens, **kwargs)\n\ndef info(*tokens, **kwargs):\n \"\"\" Print an informative message \"\"\"\n if CONFIG[\"quiet\"]:\n return\n _msg(*tokens, **kwargs)\n\ndef debug(*tokens, **kwargs):\n \"\"\" Print a debug message \"\"\"\n if not CONFIG[\"verbose\"]:\n return\n tokens = [blue, \"[DEBUG]: \"] + list(tokens)\n _msg(*tokens, **kwargs)\n"
},
{
"alpha_fraction": 0.6545253992080688,
"alphanum_fraction": 0.6589403748512268,
"avg_line_length": 25.647058486938477,
"blob_id": "6d47432c6d73d7395802cc6cf9d86cef625af508",
"content_id": "bf27552f1ed7b626bd66d4e773b22a2eaede3507",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 906,
"license_type": "permissive",
"max_line_length": 74,
"num_lines": 34,
"path": "/python/qisrc/actions/list.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\n\"\"\" List the names and paths of every project, or those matching a pattern\n\n\"\"\"\n\nimport re\nimport qibuild.log\n\nLOGGER = qibuild.log.get_logger(__name__)\n\nimport qisrc\nimport qibuild\n\n\ndef configure_parser(parser):\n \"\"\" Configure parser for this action \"\"\"\n qibuild.parsers.worktree_parser(parser)\n parser.add_argument(\"pattern\", metavar=\"PATTERN\", nargs=\"?\",\n help=\"pattern to be matched\")\n\ndef do(args):\n \"\"\" Main method \"\"\"\n qiwt = qisrc.open_worktree(args.worktree)\n regex = args.pattern\n if args.pattern:\n regex = re.compile(regex)\n print \"Projects in :\", qiwt.root\n print\n for project in qiwt.projects:\n if not regex or regex.search(project.src):\n print project.src\n"
},
{
"alpha_fraction": 0.6197028160095215,
"alphanum_fraction": 0.6224545836448669,
"avg_line_length": 36.081634521484375,
"blob_id": "f70bbbd74240136a9f4de9ecdc8911b3bd3c8f39",
"content_id": "1fbf2de983a0d24a69f67237c53b84e24ae560b5",
"detected_licenses": [
"Python-2.0",
"BSD-3-Clause",
"LicenseRef-scancode-public-domain"
],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 1817,
"license_type": "permissive",
"max_line_length": 85,
"num_lines": 49,
"path": "/python/qibuild/actions/test.py",
"repo_name": "sanyaade-research-hub/qibuild",
"src_encoding": "UTF-8",
"text": "## Copyright (c) 2012 Aldebaran Robotics. All rights reserved.\n## Use of this source code is governed by a BSD-style license that can be\n## found in the COPYING file.\n\n\"\"\" Launch automatic tests\n\"\"\"\n\nimport os\nimport sys\n\nimport qibuild\n\ndef configure_parser(parser):\n \"\"\"Configure parser for this action\"\"\"\n qibuild.parsers.toc_parser(parser)\n qibuild.parsers.build_parser(parser)\n parser.add_argument(\"project\", nargs=\"?\")\n parser.add_argument(\"-k\", \"--pattern\", dest=\"pattern\",\n help=\"Filter tests matching this pattern\")\n parser.add_argument(\"-n\" , \"--dry-run\", dest=\"dry_run\",\n action=\"store_true\",\n help=\"Just list what tests would be run\")\n parser.add_argument(\"--slow\", action=\"store_true\",\n help=\"Also run slow tests\")\n parser.add_argument(\"-V\", action=\"store_true\", dest=\"verbose_tests\",\n help=\"verbose tests\")\n parser.add_argument(\"--valgrind\", dest=\"valgrind\", action=\"store_true\",\n help=\"run tests under valgrind\")\n parser.set_defaults(slow=False)\n\ndef do(args):\n \"\"\"Main entry point\"\"\"\n toc = qibuild.toc_open(args.worktree, args)\n if not args.project:\n project_name = qibuild.project.project_from_cwd()\n else:\n project_name = args.project\n project = toc.get_project(project_name)\n\n build_dir = project.build_directory\n cmake_cache = os.path.join(build_dir, \"CMakeCache.txt\")\n if not os.path.exists(cmake_cache):\n qibuild.toc.advise_using_configure(toc, project)\n\n res = qibuild.ctest.run_tests(project, toc.build_env,\n pattern=args.pattern, slow=args.slow,\n dry_run=args.dry_run, valgrind=args.valgrind, verbose=args.verbose_tests)\n if not res:\n sys.exit(1)\n"
}
] | 26 |
ottvladimir/11-microservices | https://github.com/ottvladimir/11-microservices | 427c6d4e165a9112ace6ea7cb5de6e1acdae00a1 | 0b58d5b9235b32a0ff904ae28e44bd26c21f5b8b | ced07fced61539863bdd99cb68fff552092ee42f | refs/heads/master | 2023-08-04T14:55:00.609591 | 2021-09-27T03:27:09 | 2021-09-27T03:27:09 | 406,560,317 | 0 | 7 | null | null | null | null | null | [
{
"alpha_fraction": 0.5287008881568909,
"alphanum_fraction": 0.5485541820526123,
"avg_line_length": 27.617284774780273,
"blob_id": "9306b64e46f104e0049c3e791e63eabf922eff1b",
"content_id": "3a8f5f710fadd104e6e831355ff350cc7896ad2c",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "JavaScript",
"length_bytes": 2317,
"license_type": "no_license",
"max_line_length": 93,
"num_lines": 81,
"path": "/11-microservices-02-principles/uploader/src/server.js",
"repo_name": "ottvladimir/11-microservices",
"src_encoding": "UTF-8",
"text": "const { Client } = require('minio'),\n express = require('express'),\n metrics = require('express-prometheus-middleware'),\n { v4: uuidv4 } = require('uuid'),\n FileType = require('file-type');\n;\n\nconst {\n S3_HOST,\n S3_PORT,\n S3_ACCESS_KEY,\n S3_ACCESS_SECRET,\n S3_BUCKET,\n PORT\n} = process.env;\n\nconsole.log(`S3: ${S3_HOST}:${S3_PORT} ${S3_BUCKET}`);\n\nconst app = express(),\n client = new Client({\n endPoint: S3_HOST,\n port: parseInt(S3_PORT),\n useSSL: false,\n accessKey: S3_ACCESS_KEY,\n secretKey: S3_ACCESS_SECRET\n });\n\napp.disable('etag');\napp.use(metrics(\n {\n metricsPath: '/metrics',\n collectDefaultMetrics: true,\n normalizeStatus: false,\n requestDurationBuckets: [0.1, 0.5, 1, 1.5, 2],\n customLabels: ['app_name'],\n transformLabels(labels, req) {\n labels.app_name = 'uploader';\n }\n }\n));\n\napp.get('/status', (_, response) => {\n return response.status(200).json({ \"status\": \"OK\" });\n});\n\napp.post('/v1/upload', (request, response) => { \n var bufs = [];\n request.on('data', (d) => bufs.push(d));\n request.on('end', async () => {\n var buf = Buffer.concat(bufs);\n\n const fileType = await FileType.fromBuffer(buf);\n console.log(`Detected file type: ${fileType.mime}`);\n\n if(!fileType) {\n console.warn(`Failed to detect file mime type`);\n return response.status(400).json({ 'error': 'Failed to detect file mime type' });\n }\n\n if(!fileType.mime.startsWith('image/')) {\n console.warn(`Expected image, but got ${fileType.mime}`);\n return response.status(400).json({ 'error': 'File expected to be image' });\n }\n\n const id = uuidv4();\n const filename = `${id}.${fileType.ext}`;\n \n client.putObject(S3_BUCKET, filename, buf, function (err, objInfo) {\n if (err) {\n console.error(`Failed to save file due to error ${err}`);\n return response.status(500).json({ \"error\": err });\n }\n console.log(`Saved file: ${filename}`);\n return response.json({filename});\n })\n }); \n});\n\nconst port = PORT || 3000;\napp.listen(port, \"0.0.0.0\");\nconsole.log(`Listening on port ${port}`);"
},
{
"alpha_fraction": 0.6915887594223022,
"alphanum_fraction": 0.6915887594223022,
"avg_line_length": 12.5,
"blob_id": "effd89f96df6242ab124d63ad5a043fa7254108c",
"content_id": "43d6d699e1b0291e20044d6451968c01de85e7de",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Dockerfile",
"length_bytes": 107,
"license_type": "no_license",
"max_line_length": 25,
"num_lines": 8,
"path": "/11-microservices-02-principles/uploader/Dockerfile",
"repo_name": "ottvladimir/11-microservices",
"src_encoding": "UTF-8",
"text": "FROM node:alpine\nWORKDIR /app\n\nCOPY package*.json ./\nRUN npm install\nCOPY src ./\n\nCMD [\"node\", \"server.js\"]"
},
{
"alpha_fraction": 0.695695698261261,
"alphanum_fraction": 0.7017017006874084,
"avg_line_length": 42.39130401611328,
"blob_id": "be5f95e47b2156c05f26a4a233033067235e0fac",
"content_id": "bc887aa42ac3a8d0a95488259de0845ee7bf808d",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1616,
"license_type": "no_license",
"max_line_length": 156,
"num_lines": 23,
"path": "/11-microservices-02-principles.md",
"repo_name": "ottvladimir/11-microservices",
"src_encoding": "UTF-8",
"text": "\n# Домашнее задание к занятию \"11.02 Микросервисы: принципы\"\n\nВы работаете в крупной компанию, которая строит систему на основе микросервисной архитектуры.\nВам как DevOps специалисту необходимо выдвинуть предложение по организации инфраструктуры, для разработки и эксплуатации.\n\n## Задача 1: API Gateway \n\nЯ бы предложил nginx в качестве балансировщика + kong как масштабируемое решение, реализующее слой API Gateway,расширяемый за счет дополнительных плагинов. \n\n\n\n## Задача 2: Брокер сообщений\n\n| Параметр\\Брокер | RabbitMQ | Apache Kafka | ActiveMQ | WebSphereMQ | \n|---|---|---|---|---|\n| Поддержка кластеризации | + | + | + | + | \n| Хранение сообщений в процессе доставки | + | + | + | + | \n| Высокая скорость | - | + | - | + | \n| Поддержка различных форматов | + | + | - | + | \n| Разделение прав доступа | + | + | + | + |\n| Простота эксплуатации | - | + | + | + | \n\nОсновываясь на сравнении брокеров оптимально выбрать Kafka , так как у него наибольшее количество плюсов и большое коммьюнити.\n"
},
{
"alpha_fraction": 0.5871015787124634,
"alphanum_fraction": 0.6634544134140015,
"avg_line_length": 29,
"blob_id": "f5cacdc96f524db803f11ee507a7f9a15a110659",
"content_id": "ce910f092ec593dc7be986ba88082504dbb5783a",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1539,
"license_type": "no_license",
"max_line_length": 137,
"num_lines": 45,
"path": "/11-microservices-02-principles/readme.md",
"repo_name": "ottvladimir/11-microservices",
"src_encoding": "UTF-8",
"text": "# Как запускать\nПосле написания nginx.conf для запуска выполните команду\n```\ndocker-compose up --build\n```\n\n# Как тестировать\n\n## Login\nПолучить токен\n```\ncurl -X POST -H 'Content-Type: application/json' -d '{\"login\":\"bob\", \"password\":\"qwe123\"}' http://localhost/token\n```\nПример\n```\n$ curl -X POST -H 'Content-Type: application/json' -d '{\"login\":\"bob\", \"password\":\"qwe123\"}' http://localhost/token\neyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJib2IifQ.hiMVLmssoTsy1MqbmIoviDeFPvo-nCd92d4UFiN2O2I\n```\n\n## Test\nИспользовать полученный токен для загрузки картинки\n```\ncurl -X POST -H 'Authorization: Bearer <TODO: INSERT TOKEN>' -H 'Content-Type: octet/stream' --data-binary @1.jpg http://localhost/upload\n```\nПример\n```\n$ curl -X POST -H 'Authorization: Bearer eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOiJib2IifQ.hiMVLmssoTsy1MqbmIoviDeFPvo-nCd92d4UFiN2O2I' -H 'Content-Type: octet/stream' --data-binary @1.jpg http://localhost/upload\n{\"filename\":\"c31e9789-3fab-4689-aa67-e7ac2684fb0e.jpg\"}\n```\n\n ## Проверить\nЗагрузить картинку и проверить что она открывается\n```\ncurl localhost/image/<filnename> > <filnename>\n```\nExample\n```\n$ curl localhost/images/c31e9789-3fab-4689-aa67-e7ac2684fb0e.jpg > c31e9789-3fab-4689-aa67-e7ac2684fb0e.jpg\n % Total % Received % Xferd Average Speed Time Time Time Current\n Dload Upload Total Spent Left Speed\n100 13027 100 13027 0 0 706k 0 --:--:-- --:--:-- --:--:-- 748k\n\n$ ls\nc31e9789-3fab-4689-aa67-e7ac2684fb0e.jpg\n```"
},
{
"alpha_fraction": 0.5728038549423218,
"alphanum_fraction": 0.6022863984107971,
"avg_line_length": 23.086956024169922,
"blob_id": "0bcff45b59abb96472bd63a7486872ee4bfa9219",
"content_id": "75991b64e0394763665dd9cc7688e23ebba5eba3",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "YAML",
"length_bytes": 1662,
"license_type": "no_license",
"max_line_length": 141,
"num_lines": 69,
"path": "/11-microservices-02-principles/docker-compose.yaml",
"repo_name": "ottvladimir/11-microservices",
"src_encoding": "UTF-8",
"text": "volumes:\n data:\n prometheus-data:\n grafana_data:\n\nservices:\n storage:\n image: minio/minio:latest\n command: server /data\n restart: always\n expose: \n - 9000\n environment:\n MINIO_ROOT_USER: ${Storage_AccessKey:-STORAGE_ACCESS_KEY}\n MINIO_ROOT_PASSWORD: ${Storage_Secret:-STORAGE_SECRET_KEY}\n MINIO_PROMETHEUS_AUTH_TYPE: public\n volumes:\n - data:/data\n healthcheck:\n test: [\"CMD\", \"curl\", \"-f\", \"http://localhost:9000/minio/health/live\"]\n interval: 30s\n timeout: 20s\n retries: 3\n\n createbuckets:\n image: minio/mc\n depends_on:\n - storage\n restart: on-failure\n entrypoint: > \n /bin/sh -c \" \n /usr/bin/mc config host add storage http://storage:9000 ${Storage_AccessKey-STORAGE_ACCESS_KEY} ${Storage_Secret-STORAGE_SECRET_KEY} &&\n /usr/bin/mc mb --ignore-existing storage/${Storage_Bucket:-data} &&\n /usr/bin/mc policy set download storage/${Storage_Bucket:-data} &&\n exit 0;\n \"\n\n uploader:\n build: ./uploader\n depends_on:\n - storage\n - createbuckets\n expose: \n - 3000\n environment:\n PORT: 3000\n S3_HOST: storage\n S3_PORT: 9000\n S3_ACCESS_KEY: ${Storage_AccessKey:-STORAGE_ACCESS_KEY}\n S3_ACCESS_SECRET: ${Storage_Secret:-STORAGE_SECRET_KEY}\n S3_BUCKET: ${Storage_Bucket:-STORAGE_BUCKET}\n \n security:\n build: ./security\n expose: \n - 3000\n environment:\n PORT: 3000\n\n gateway:\n image: nginx:alpine\n volumes:\n - ./gateway/nginx.conf:/etc/nginx/nginx.conf:ro\n ports:\n - \"80:8080\" \n depends_on:\n - storage\n - uploader\n - security\n"
},
{
"alpha_fraction": 0.8030035495758057,
"alphanum_fraction": 0.8091872930526733,
"avg_line_length": 74.4000015258789,
"blob_id": "e9242862c652ded8716848ce1998924e315576fa",
"content_id": "26abfbce6fcfc628aed807136ed579db8b26485b",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1942,
"license_type": "no_license",
"max_line_length": 384,
"num_lines": 15,
"path": "/11-microservices-03-approaches.md",
"repo_name": "ottvladimir/11-microservices",
"src_encoding": "UTF-8",
"text": "# Домашнее задание к занятию \"11.03 Микросервисы: подходы\"\n\n## Задача 1: Обеспечить разработку\n\nЯ бы предложил связку Gitlab + Jenkins, Gitlab полностью удовлетворяет условиям Ci Cd, контроль версий + свой docker regestry и хранение артефактов, Jenkins как один изпопулярнейших средств автоматизированного создания, тестирования и развертывания программного обеспечения, хорошая развернутая документация. В случае столь широкого ТЗ можно использовать И GitHub + Dockerhub + Sentry\n\n## Задача 2: Логи\n\nВ зависимости от размеров проекта можно использовать ELK (или аналог) - модно, молодежно, огромное количество кейсов на разный вкус и цвет. Но если проект маленький и простой, то можно использовать более простые инструменты типа Syslog-Ng.\n\n## Задача 3: Мониторинг\n\nМониторинг зависит от системы на которой установлены микросервисы: \n* Если у нас микросервисы в облаке (в т.ч. и On-prem) то лучше использовать встроенный мониторинг.\n* Если мы имеем отдельные контейнеры то на сегодняшний день, наверное, prometheus + grafana лучший выбор - большое коммьюнити, куча кейсов и мануалов. Возможность очень тонко настраивать метрики.\n\n"
},
{
"alpha_fraction": 0.7335766553878784,
"alphanum_fraction": 0.8029196858406067,
"avg_line_length": 59.88888931274414,
"blob_id": "f3d135ac8e2bb3c1965050639311de71f633370f",
"content_id": "8349d6b4db21a9346b1a1d67388b18bda4a3f7d4",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 666,
"license_type": "no_license",
"max_line_length": 129,
"num_lines": 9,
"path": "/README.md",
"repo_name": "ottvladimir/11-microservices",
"src_encoding": "UTF-8",
"text": "## Модуль 11. Микросервисная архитектура\n\n11.1. [Введение в микросервисы](https://github.com/ottvladimir/11-microservices/blob/master/11-microservices-01-intro.md)\n\n11.2. [Микросервисы: принципы](https://github.com/ottvladimir/11-microservices/blob/master/11-microservices-02-principles.md)\n\n11.3. [Микросервисы: подходы](https://github.com/ottvladimir/11-microservices/blob/master/11-microservices-03-approaches.md)\n\n11.4. [Микросервисы: масштабирование](https://github.com/ottvladimir/11-microservices/blob/master/11-microservices-04-scaling.md)\n"
},
{
"alpha_fraction": 0.7249334454536438,
"alphanum_fraction": 0.7293699979782104,
"avg_line_length": 55.29999923706055,
"blob_id": "37d5ecdcfe3c99042da2687ceb0a3e9209559275",
"content_id": "55b2ea731a355504aafd0ab045e2c839e17e35f9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 1869,
"license_type": "no_license",
"max_line_length": 182,
"num_lines": 20,
"path": "/11-microservices-04-scaling.md",
"repo_name": "ottvladimir/11-microservices",
"src_encoding": "UTF-8",
"text": "\n# Домашнее задание к занятию \"11.04 Микросервисы: масштабирование\"\n\nВы работаете в крупной компанию, которая строит систему на основе микросервисной архитектуры.\nВам как DevOps специалисту необходимо выдвинуть предложение по организации инфраструктуры, для разработки и эксплуатации.\n\n## Задача 1: Кластеризация\n\n## Решение\n\n| Параметр\\Название | Apache Mesos (+Marathon, Aurora) | OpenShift | Nomand | Kubernetes|\n|---|---|---|---|---|\n| Поддержка контейнеров | + | + | + | + |\n| Обнаружение сервисов и маршрутизация запросов | + | + | - | + |\n| Возможность горизонтального масштабирования | + | + | + | + |\n| Возможность автоматического масштабирования | + | + | + | + |\n| Явное разделение ресурсов доступных извне и внутри системы | + | + | + | + |\n| Возможность конфигурировать приложения с помощью переменных среды | + | + | + | + |\n\nРешения представленные в таблице похожи. Выбор зависит от условий, в которых мы находимся. Готова ли компания содержать и обучать свой штат админов Kubernets, или платить за аутсорс.\nЯ бы выбрал Kubernetes так как он наиболее доступен с точки зрения финансов, документации и комьюнити.\n"
},
{
"alpha_fraction": 0.6357702612876892,
"alphanum_fraction": 0.6636205315589905,
"avg_line_length": 33.31343460083008,
"blob_id": "f204d11528bcf82bf399cd71e018f375683af451",
"content_id": "793cf6ba137a457e708d61b52b50b157a158c0e2",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Python",
"length_bytes": 2298,
"license_type": "no_license",
"max_line_length": 134,
"num_lines": 67,
"path": "/11-microservices-02-principles/security/src/server.py",
"repo_name": "ottvladimir/11-microservices",
"src_encoding": "UTF-8",
"text": "from os import getenv\nfrom flask import Flask, request, make_response, jsonify\nfrom prometheus_flask_exporter import PrometheusMetrics, NO_PREFIX\nfrom passlib.hash import pbkdf2_sha256\nimport jwt\n\nserver = Flask(__name__)\nmetrics = PrometheusMetrics(server, defaults_prefix=NO_PREFIX, buckets=[0.1, 0.5, 1, 1.5, 2], default_labels={\"app_name\": \"security\"})\nmetrics.info('app_info', 'Application info', version='1.0')\n\njwt_key = 'secret'\ndata = {\n 'bob': pbkdf2_sha256.hash('qwe123')\n}\n\[email protected]('/status', methods=['GET'])\ndef status():\n return {'status':'OK'}\n\[email protected]('/v1/token', methods=['POST'])\ndef login():\n if not request.json or not 'login' in request.json or not 'password' in request.json:\n return make_response(jsonify({'error':'Bad request'})), 400\n\n login = request.json['login']\n password = request.json['password']\n \n if not login in data:\n return make_response(jsonify({'error':'Unknown login or password'})), 401\n\n hash = data[login]\n if not pbkdf2_sha256.verify(password, hash):\n return make_response(jsonify({'error':'Unknown login or password'})), 401\n\n return jwt.encode({'sub': login}, jwt_key, algorithm=\"HS256\")\n\n\[email protected]('/v1/token/validation', methods=['GET'])\ndef validate():\n auth_header = request.headers.get('Authorization')\n\n if not auth_header:\n return make_response(jsonify({'error':'Missing Authorization header'})), 401 \n \n try:\n auth_header_parts = auth_header.split(' ')\n auth_schema = auth_header_parts[0]\n auth_token = auth_header_parts[1]\n except IndexError:\n return make_response(jsonify({'error':'Invalid Authorization header'})), 401 \n\n if not auth_schema == 'Bearer':\n return make_response(jsonify({'error':'Invalid Authorization schema'})), 401 \n\n if not auth_token:\n return make_response(jsonify({'error':'Invalid Authorization value'})), 401 \n\n try:\n return jwt.decode(auth_token, jwt_key, algorithms=\"HS256\")\n except jwt.ExpiredSignatureError:\n return 'Signature expired. Please log in again.'\n except jwt.InvalidTokenError:\n return 'Invalid token. Please log in again.'\n\nif __name__ == '__main__':\n port = int(getenv('PORT') or '8080')\n server.run(host='0.0.0.0', port=port)"
},
{
"alpha_fraction": 0.8278182744979858,
"alphanum_fraction": 0.8306225538253784,
"avg_line_length": 56.51612854003906,
"blob_id": "5069bdca377ffcfc161977102771ae46d77be87b",
"content_id": "aba2853d28a998d23785b1184e6aca91b845431e",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Markdown",
"length_bytes": 3256,
"license_type": "no_license",
"max_line_length": 199,
"num_lines": 31,
"path": "/11-microservices-01-intro.md",
"repo_name": "ottvladimir/11-microservices",
"src_encoding": "UTF-8",
"text": "# Домашнее задание к занятию \"11.01 Введение в микросервисы\"\n\n## Задача 1: Интернет Магазин\n\nРуководство крупного интернет магазина у которого постоянно растёт пользовательская база и количество заказов рассматривает возможность переделки своей внутренней ИТ системы на основе микросервисов. \n\nВас пригласили в качестве консультанта для оценки целесообразности перехода на микросервисную архитектуру. \n\n### Выгоды которые может получить компания от перехода на микросервисную архитектуру \n* легкая масштабируемость; \n* быстрое тестирование и быстырые циклы обновления и повторного развертывания; \n* возможность быстро внедрить мелкие исправления и улучшения; \n* отсутствие простоев при обновлении; \n* легкое внедрение новых технологий и языков программирования; \n* возможность выборочного масштабирования необходимых компонентов или функций. \n* воспроизводимость практически в любых средах.\n* отказоустойчивость\n* разделение на команды по компетенциям и зонам ответственности\n* возможность более подробного мониторинга\n### Недостатки\n* Необходим внешний сборщик логов (логи хранятся только от последней сборки)\n* Необходима стандартизация api\n* Из-за более быстрой и разделенной разработки возможно быстрое устаревание документации (дополнительные затраты человекоресурсов на актуализацию)\n* Сложнее мониторить\n### Проблемы которые необходимо будет решить в первую очередь.\n* При разбиении монолита на микросервисы возможно придется переписать весь код; \n* Необходимо определить бизнес-цели каждого сервиса;\n* Возможно некоторое снижение производительности; \n* Усложнение сопровождения из-за увеличивающейся инфраструктуры; \n* Управление версиями при большом количестве сервисов;\n* Определение инструментов мниторинга и логгирования, резервного копирования и управления;\n"
},
{
"alpha_fraction": 0.517241358757019,
"alphanum_fraction": 0.7011494040489197,
"avg_line_length": 16.600000381469727,
"blob_id": "007a8d94bbffe0af75fce50b78ca627ea4e74b4a",
"content_id": "d71f752b5e5c8b6092cb9c7d6b0caabf6813bed9",
"detected_licenses": [],
"is_generated": false,
"is_vendor": false,
"language": "Text",
"length_bytes": 87,
"license_type": "no_license",
"max_line_length": 33,
"num_lines": 5,
"path": "/11-microservices-02-principles/security/requirements.txt",
"repo_name": "ottvladimir/11-microservices",
"src_encoding": "UTF-8",
"text": "Flask==1.1.1\nPyJwt==2.0.1\npasslib==1.7.4\nPyJWT==2.0.1\nprometheus-flask-exporter==0.18.1"
}
] | 11 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.